blob: 1439ed14c064ee23a68a8209afc402fc494e3542 [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
Douglas Gregor18274032010-07-03 00:47:00 +000034unsigned ASTContext::NumImplicitDefaultConstructors;
35unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000036unsigned ASTContext::NumImplicitCopyConstructors;
37unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000038unsigned ASTContext::NumImplicitCopyAssignmentOperators;
39unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000040unsigned ASTContext::NumImplicitDestructors;
41unsigned ASTContext::NumImplicitDestructorsDeclared;
42
Reid Spencer5f016e22007-07-11 17:01:13 +000043enum FloatingRank {
44 FloatRank, DoubleRank, LongDoubleRank
45};
46
Douglas Gregor3e1274f2010-06-16 21:09:37 +000047void
48ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
49 TemplateTemplateParmDecl *Parm) {
50 ID.AddInteger(Parm->getDepth());
51 ID.AddInteger(Parm->getPosition());
52 // FIXME: Parameter pack
53
54 TemplateParameterList *Params = Parm->getTemplateParameters();
55 ID.AddInteger(Params->size());
56 for (TemplateParameterList::const_iterator P = Params->begin(),
57 PEnd = Params->end();
58 P != PEnd; ++P) {
59 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
60 ID.AddInteger(0);
61 ID.AddBoolean(TTP->isParameterPack());
62 continue;
63 }
64
65 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
66 ID.AddInteger(1);
67 // FIXME: Parameter pack
68 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
69 continue;
70 }
71
72 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
73 ID.AddInteger(2);
74 Profile(ID, TTP);
75 }
76}
77
78TemplateTemplateParmDecl *
79ASTContext::getCanonicalTemplateTemplateParmDecl(
80 TemplateTemplateParmDecl *TTP) {
81 // Check if we already have a canonical template template parameter.
82 llvm::FoldingSetNodeID ID;
83 CanonicalTemplateTemplateParm::Profile(ID, TTP);
84 void *InsertPos = 0;
85 CanonicalTemplateTemplateParm *Canonical
86 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
87 if (Canonical)
88 return Canonical->getParam();
89
90 // Build a canonical template parameter list.
91 TemplateParameterList *Params = TTP->getTemplateParameters();
92 llvm::SmallVector<NamedDecl *, 4> CanonParams;
93 CanonParams.reserve(Params->size());
94 for (TemplateParameterList::const_iterator P = Params->begin(),
95 PEnd = Params->end();
96 P != PEnd; ++P) {
97 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
98 CanonParams.push_back(
99 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
100 SourceLocation(), TTP->getDepth(),
101 TTP->getIndex(), 0, false,
102 TTP->isParameterPack()));
103 else if (NonTypeTemplateParmDecl *NTTP
104 = dyn_cast<NonTypeTemplateParmDecl>(*P))
105 CanonParams.push_back(
106 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
107 SourceLocation(), NTTP->getDepth(),
108 NTTP->getPosition(), 0,
109 getCanonicalType(NTTP->getType()),
110 0));
111 else
112 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
113 cast<TemplateTemplateParmDecl>(*P)));
114 }
115
116 TemplateTemplateParmDecl *CanonTTP
117 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
118 SourceLocation(), TTP->getDepth(),
119 TTP->getPosition(), 0,
120 TemplateParameterList::Create(*this, SourceLocation(),
121 SourceLocation(),
122 CanonParams.data(),
123 CanonParams.size(),
124 SourceLocation()));
125
126 // Get the new insert position for the node we care about.
127 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
128 assert(Canonical == 0 && "Shouldn't be in the map!");
129 (void)Canonical;
130
131 // Create the canonical template template parameter entry.
132 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
133 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
134 return CanonTTP;
135}
136
Chris Lattner61710852008-10-05 17:34:18 +0000137ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000138 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000139 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000140 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +0000141 bool FreeMem, unsigned size_reserve) :
John McCallef990012010-06-11 11:07:21 +0000142 TemplateSpecializationTypes(this_()),
143 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000144 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
145 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000146 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000147 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCallbf1a0282010-06-04 23:28:52 +0000148 NullTypeSourceInfo(QualType()),
Douglas Gregorc6fbbed2010-03-19 22:13:20 +0000149 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000150 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000151 BuiltinInfo(builtins),
152 DeclarationNames(*this),
153 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000154 LastSDM(0, 0),
155 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000156 ObjCIdRedefinitionType = QualType();
157 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +0000158 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000159 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000160 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000161 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000162}
163
Reid Spencer5f016e22007-07-11 17:01:13 +0000164ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000165 // Release the DenseMaps associated with DeclContext objects.
166 // FIXME: Is this the ideal solution?
167 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000168
Douglas Gregor00545312010-05-23 18:26:36 +0000169 if (!FreeMemory) {
170 // Call all of the deallocation functions.
171 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
172 Deallocations[I].first(Deallocations[I].second);
173 }
174
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000175 // Release all of the memory associated with overridden C++ methods.
176 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
177 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
178 OM != OMEnd; ++OM)
179 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000180
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000181 if (FreeMemory) {
182 // Deallocate all the types.
183 while (!Types.empty()) {
184 Types.back()->Destroy(*this);
185 Types.pop_back();
186 }
Eli Friedmanb26153c2008-05-27 03:08:09 +0000187
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000188 for (llvm::FoldingSet<ExtQuals>::iterator
189 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
190 // Increment in loop to prevent using deallocated memory.
John McCall0953e762009-09-24 19:53:00 +0000191 Deallocate(&*I++);
Nuno Lopesb74668e2008-12-17 22:30:25 +0000192 }
Nuno Lopesb74668e2008-12-17 22:30:25 +0000193
Ted Kremenek503524a2010-03-08 20:56:29 +0000194 for (llvm::DenseMap<const ObjCContainerDecl*,
195 const ASTRecordLayout*>::iterator
196 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
197 // Increment in loop to prevent using deallocated memory.
198 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
199 R->Destroy(*this);
200 }
Nuno Lopesb74668e2008-12-17 22:30:25 +0000201 }
202
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000203 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
204 // even when using the BumpPtrAllocator because they can contain
205 // DenseMaps.
206 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
207 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
208 // Increment in loop to prevent using deallocated memory.
209 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
210 R->Destroy(*this);
211 }
212
Douglas Gregorab452ba2009-03-26 23:50:42 +0000213 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +0000214 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
215 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +0000216 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000217 NNS != NNSEnd; ) {
218 // Increment in loop to prevent using deallocated memory.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +0000219 (*NNS++).Destroy(*this);
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000220 }
Douglas Gregorab452ba2009-03-26 23:50:42 +0000221
222 if (GlobalNestedNameSpecifier)
223 GlobalNestedNameSpecifier->Destroy(*this);
224
Eli Friedmanb26153c2008-05-27 03:08:09 +0000225 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000226}
227
Douglas Gregor00545312010-05-23 18:26:36 +0000228void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
229 Deallocations.push_back(std::make_pair(Callback, Data));
230}
231
Mike Stump1eb44332009-09-09 15:08:12 +0000232void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000233ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
234 ExternalSource.reset(Source.take());
235}
236
Reid Spencer5f016e22007-07-11 17:01:13 +0000237void ASTContext::PrintStats() const {
238 fprintf(stderr, "*** AST Context Stats:\n");
239 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000240
Douglas Gregordbe833d2009-05-26 14:40:08 +0000241 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000242#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000243#define ABSTRACT_TYPE(Name, Parent)
244#include "clang/AST/TypeNodes.def"
245 0 // Extra
246 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000247
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
249 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000250 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000251 }
252
Douglas Gregordbe833d2009-05-26 14:40:08 +0000253 unsigned Idx = 0;
254 unsigned TotalBytes = 0;
255#define TYPE(Name, Parent) \
256 if (counts[Idx]) \
257 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
258 TotalBytes += counts[Idx] * sizeof(Name##Type); \
259 ++Idx;
260#define ABSTRACT_TYPE(Name, Parent)
261#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000262
Douglas Gregordbe833d2009-05-26 14:40:08 +0000263 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000264
Douglas Gregor4923aa22010-07-02 20:37:36 +0000265 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000266 fprintf(stderr, " %u/%u implicit default constructors created\n",
267 NumImplicitDefaultConstructorsDeclared,
268 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000269 fprintf(stderr, " %u/%u implicit copy constructors created\n",
270 NumImplicitCopyConstructorsDeclared,
271 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000272 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
273 NumImplicitCopyAssignmentOperatorsDeclared,
274 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000275 fprintf(stderr, " %u/%u implicit destructors created\n",
276 NumImplicitDestructorsDeclared, NumImplicitDestructors);
277
Douglas Gregor2cf26342009-04-09 22:27:44 +0000278 if (ExternalSource.get()) {
279 fprintf(stderr, "\n");
280 ExternalSource->PrintStats();
281 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000282}
283
284
John McCalle27ec8a2009-10-23 23:03:21 +0000285void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000286 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000287 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000288 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000289}
290
Reid Spencer5f016e22007-07-11 17:01:13 +0000291void ASTContext::InitBuiltinTypes() {
292 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 // C99 6.2.5p19.
295 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 // C99 6.2.5p2.
298 InitBuiltinType(BoolTy, BuiltinType::Bool);
299 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000300 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 InitBuiltinType(CharTy, BuiltinType::Char_S);
302 else
303 InitBuiltinType(CharTy, BuiltinType::Char_U);
304 // C99 6.2.5p4.
305 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
306 InitBuiltinType(ShortTy, BuiltinType::Short);
307 InitBuiltinType(IntTy, BuiltinType::Int);
308 InitBuiltinType(LongTy, BuiltinType::Long);
309 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 // C99 6.2.5p6.
312 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
313 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
314 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
315 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
316 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Reid Spencer5f016e22007-07-11 17:01:13 +0000318 // C99 6.2.5p10.
319 InitBuiltinType(FloatTy, BuiltinType::Float);
320 InitBuiltinType(DoubleTy, BuiltinType::Double);
321 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000322
Chris Lattner2df9ced2009-04-30 02:43:43 +0000323 // GNU extension, 128-bit integers.
324 InitBuiltinType(Int128Ty, BuiltinType::Int128);
325 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
326
Chris Lattner3a250322009-02-26 23:43:47 +0000327 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
328 InitBuiltinType(WCharTy, BuiltinType::WChar);
329 else // C99
330 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000331
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000332 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
333 InitBuiltinType(Char16Ty, BuiltinType::Char16);
334 else // C99
335 Char16Ty = getFromTargetType(Target.getChar16Type());
336
337 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
338 InitBuiltinType(Char32Ty, BuiltinType::Char32);
339 else // C99
340 Char32Ty = getFromTargetType(Target.getChar32Type());
341
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000342 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000343 InitBuiltinType(OverloadTy, BuiltinType::Overload);
344
345 // Placeholder type for type-dependent expressions whose type is
346 // completely unknown. No code should ever check a type against
347 // DependentTy and users should never see it; however, it is here to
348 // help diagnose failures to properly check for type-dependent
349 // expressions.
350 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000351
Mike Stump1eb44332009-09-09 15:08:12 +0000352 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000353 // not yet been deduced.
354 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 // C99 6.2.5p11.
357 FloatComplexTy = getComplexType(FloatTy);
358 DoubleComplexTy = getComplexType(DoubleTy);
359 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000360
Steve Naroff7e219e42007-10-15 14:41:52 +0000361 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Steve Naroffde2e22d2009-07-15 18:40:39 +0000363 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
364 ObjCIdTypedefType = QualType();
365 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000366 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000368 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000369 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
370 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000371 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000372
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000373 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000375 // void * type
376 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000377
378 // nullptr type (C++0x 2.14.7)
379 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000380}
381
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000382MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000383ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000384 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000385 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000386 = InstantiatedFromStaticDataMember.find(Var);
387 if (Pos == InstantiatedFromStaticDataMember.end())
388 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Douglas Gregor7caa6822009-07-24 20:34:43 +0000390 return Pos->second;
391}
392
Mike Stump1eb44332009-09-09 15:08:12 +0000393void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000394ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000395 TemplateSpecializationKind TSK,
396 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000397 assert(Inst->isStaticDataMember() && "Not a static data member");
398 assert(Tmpl->isStaticDataMember() && "Not a static data member");
399 assert(!InstantiatedFromStaticDataMember[Inst] &&
400 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000401 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000402 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000403}
404
John McCall7ba107a2009-11-18 02:36:19 +0000405NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000406ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000407 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000408 = InstantiatedFromUsingDecl.find(UUD);
409 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000410 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Anders Carlsson0d8df782009-08-29 19:37:28 +0000412 return Pos->second;
413}
414
415void
John McCalled976492009-12-04 22:46:56 +0000416ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
417 assert((isa<UsingDecl>(Pattern) ||
418 isa<UnresolvedUsingValueDecl>(Pattern) ||
419 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
420 "pattern decl is not a using decl");
421 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
422 InstantiatedFromUsingDecl[Inst] = Pattern;
423}
424
425UsingShadowDecl *
426ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
427 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
428 = InstantiatedFromUsingShadowDecl.find(Inst);
429 if (Pos == InstantiatedFromUsingShadowDecl.end())
430 return 0;
431
432 return Pos->second;
433}
434
435void
436ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
437 UsingShadowDecl *Pattern) {
438 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
439 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000440}
441
Anders Carlssond8b285f2009-09-01 04:26:58 +0000442FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
443 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
444 = InstantiatedFromUnnamedFieldDecl.find(Field);
445 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
446 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Anders Carlssond8b285f2009-09-01 04:26:58 +0000448 return Pos->second;
449}
450
451void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
452 FieldDecl *Tmpl) {
453 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
454 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
455 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
456 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Anders Carlssond8b285f2009-09-01 04:26:58 +0000458 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
459}
460
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000461ASTContext::overridden_cxx_method_iterator
462ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
463 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
464 = OverriddenMethods.find(Method);
465 if (Pos == OverriddenMethods.end())
466 return 0;
467
468 return Pos->second.begin();
469}
470
471ASTContext::overridden_cxx_method_iterator
472ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
473 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
474 = OverriddenMethods.find(Method);
475 if (Pos == OverriddenMethods.end())
476 return 0;
477
478 return Pos->second.end();
479}
480
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000481unsigned
482ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
483 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
484 = OverriddenMethods.find(Method);
485 if (Pos == OverriddenMethods.end())
486 return 0;
487
488 return Pos->second.size();
489}
490
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000491void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
492 const CXXMethodDecl *Overridden) {
493 OverriddenMethods[Method].push_back(Overridden);
494}
495
Douglas Gregor2e222532009-07-02 17:08:52 +0000496namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000497 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000498 : std::binary_function<SourceRange, SourceRange, bool> {
499 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregor2e222532009-07-02 17:08:52 +0000501 public:
502 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Douglas Gregor2e222532009-07-02 17:08:52 +0000504 bool operator()(SourceRange X, SourceRange Y) {
505 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
506 }
507 };
508}
509
Chris Lattner464175b2007-07-18 17:52:12 +0000510//===----------------------------------------------------------------------===//
511// Type Sizing and Analysis
512//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000513
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000514/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
515/// scalar floating point type.
516const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000517 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000518 assert(BT && "Not a floating point type!");
519 switch (BT->getKind()) {
520 default: assert(0 && "Not a floating point type!");
521 case BuiltinType::Float: return Target.getFloatFormat();
522 case BuiltinType::Double: return Target.getDoubleFormat();
523 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
524 }
525}
526
Ken Dyck8b752f12010-01-27 17:10:57 +0000527/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000528/// specified decl. Note that bitfields do not have a valid alignment, so
529/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000530/// If @p RefAsPointee, references are treated like their underlying type
531/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000532CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000533 unsigned Align = Target.getCharWidth();
534
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000535 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000536 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000537
Chris Lattneraf707ab2009-01-24 21:53:27 +0000538 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
539 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000540 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000541 if (RefAsPointee)
542 T = RT->getPointeeType();
543 else
544 T = getPointerType(RT->getPointeeType());
545 }
546 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindola6deecb02010-06-04 23:15:27 +0000547 unsigned MinWidth = Target.getLargeArrayMinWidth();
548 unsigned ArrayAlign = Target.getLargeArrayAlign();
549 if (isa<VariableArrayType>(T) && MinWidth != 0)
550 Align = std::max(Align, ArrayAlign);
551 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
552 unsigned Size = getTypeSize(CT);
553 if (MinWidth != 0 && MinWidth <= Size)
554 Align = std::max(Align, ArrayAlign);
555 }
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000556 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000557 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
558 T = cast<ArrayType>(T)->getElementType();
559
560 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
561 }
Charles Davis05f62472010-02-23 04:52:00 +0000562 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
563 // In the case of a field in a packed struct, we want the minimum
564 // of the alignment of the field and the alignment of the struct.
565 Align = std::min(Align,
566 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
567 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000568 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000569
Ken Dyck8b752f12010-01-27 17:10:57 +0000570 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000571}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000572
John McCallea1471e2010-05-20 01:18:31 +0000573std::pair<CharUnits, CharUnits>
574ASTContext::getTypeInfoInChars(const Type *T) {
575 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
576 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
577 CharUnits::fromQuantity(Info.second / getCharWidth()));
578}
579
580std::pair<CharUnits, CharUnits>
581ASTContext::getTypeInfoInChars(QualType T) {
582 return getTypeInfoInChars(T.getTypePtr());
583}
584
Chris Lattnera7674d82007-07-13 22:13:22 +0000585/// getTypeSize - Return the size of the specified type, in bits. This method
586/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000587///
588/// FIXME: Pointers into different addr spaces could have different sizes and
589/// alignment requirements: getPointerInfo should take an AddrSpace, this
590/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000591std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000592ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000593 uint64_t Width=0;
594 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000595 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000596#define TYPE(Class, Base)
597#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000598#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000599#define DEPENDENT_TYPE(Class, Base) case Type::Class:
600#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000601 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000602 break;
603
Chris Lattner692233e2007-07-13 22:27:08 +0000604 case Type::FunctionNoProto:
605 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000606 // GCC extension: alignof(function) = 32 bits
607 Width = 0;
608 Align = 32;
609 break;
610
Douglas Gregor72564e72009-02-26 23:50:07 +0000611 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000612 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000613 Width = 0;
614 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
615 break;
616
Steve Narofffb22d962007-08-30 01:06:46 +0000617 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000618 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Chris Lattner98be4942008-03-05 18:54:05 +0000620 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000621 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000622 Align = EltInfo.second;
623 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000624 }
Nate Begeman213541a2008-04-18 23:10:10 +0000625 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000626 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000627 const VectorType *VT = cast<VectorType>(T);
628 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
629 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000630 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000631 // If the alignment is not a power of 2, round up to the next power of 2.
632 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000633 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000634 Align = llvm::NextPowerOf2(Align);
635 Width = llvm::RoundUpToAlignment(Width, Align);
636 }
Chris Lattner030d8842007-07-19 22:06:24 +0000637 break;
638 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000639
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000640 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000641 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000642 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000643 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000644 // GCC extension: alignof(void) = 8 bits.
645 Width = 0;
646 Align = 8;
647 break;
648
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000649 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000650 Width = Target.getBoolWidth();
651 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000652 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000653 case BuiltinType::Char_S:
654 case BuiltinType::Char_U:
655 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000656 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000657 Width = Target.getCharWidth();
658 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000659 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000660 case BuiltinType::WChar:
661 Width = Target.getWCharWidth();
662 Align = Target.getWCharAlign();
663 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000664 case BuiltinType::Char16:
665 Width = Target.getChar16Width();
666 Align = Target.getChar16Align();
667 break;
668 case BuiltinType::Char32:
669 Width = Target.getChar32Width();
670 Align = Target.getChar32Align();
671 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000672 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000673 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000674 Width = Target.getShortWidth();
675 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000676 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000677 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000678 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000679 Width = Target.getIntWidth();
680 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000681 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000682 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000683 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000684 Width = Target.getLongWidth();
685 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000686 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000687 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000688 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000689 Width = Target.getLongLongWidth();
690 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000691 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000692 case BuiltinType::Int128:
693 case BuiltinType::UInt128:
694 Width = 128;
695 Align = 128; // int128_t is 128-bit aligned on all targets.
696 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000697 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000698 Width = Target.getFloatWidth();
699 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000700 break;
701 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000702 Width = Target.getDoubleWidth();
703 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000704 break;
705 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000706 Width = Target.getLongDoubleWidth();
707 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000708 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000709 case BuiltinType::NullPtr:
710 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
711 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000712 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000713 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000714 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000715 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000716 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000717 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000718 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000719 case Type::BlockPointer: {
720 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
721 Width = Target.getPointerWidth(AS);
722 Align = Target.getPointerAlign(AS);
723 break;
724 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000725 case Type::LValueReference:
726 case Type::RValueReference: {
727 // alignof and sizeof should never enter this code path here, so we go
728 // the pointer route.
729 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
730 Width = Target.getPointerWidth(AS);
731 Align = Target.getPointerAlign(AS);
732 break;
733 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000734 case Type::Pointer: {
735 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000736 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000737 Align = Target.getPointerAlign(AS);
738 break;
739 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000740 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000741 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000742 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000743 getTypeInfo(getPointerDiffType());
744 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000745 if (Pointee->isFunctionType())
746 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000747 Align = PtrDiffInfo.second;
748 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000749 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000750 case Type::Complex: {
751 // Complex types have the same alignment as their elements, but twice the
752 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000753 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000754 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000755 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000756 Align = EltInfo.second;
757 break;
758 }
John McCallc12c5bb2010-05-15 11:32:37 +0000759 case Type::ObjCObject:
760 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000761 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000762 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000763 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
764 Width = Layout.getSize();
765 Align = Layout.getAlignment();
766 break;
767 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000768 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000769 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000770 const TagType *TT = cast<TagType>(T);
771
772 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000773 Width = 1;
774 Align = 1;
775 break;
776 }
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Daniel Dunbar1d751182008-11-08 05:48:37 +0000778 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000779 return getTypeInfo(ET->getDecl()->getIntegerType());
780
Daniel Dunbar1d751182008-11-08 05:48:37 +0000781 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000782 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
783 Width = Layout.getSize();
784 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000785 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000786 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000787
Chris Lattner9fcfe922009-10-22 05:17:15 +0000788 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000789 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
790 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000791
Douglas Gregor18857642009-04-30 17:32:17 +0000792 case Type::Typedef: {
793 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000794 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000795 Align = std::max(Aligned->getMaxAlignment(),
796 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000797 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
798 } else
799 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000800 break;
Chris Lattner71763312008-04-06 22:05:18 +0000801 }
Douglas Gregor18857642009-04-30 17:32:17 +0000802
803 case Type::TypeOfExpr:
804 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
805 .getTypePtr());
806
807 case Type::TypeOf:
808 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
809
Anders Carlsson395b4752009-06-24 19:06:50 +0000810 case Type::Decltype:
811 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
812 .getTypePtr());
813
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000814 case Type::Elaborated:
815 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Douglas Gregor18857642009-04-30 17:32:17 +0000817 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000818 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000819 "Cannot request the size of a dependent type");
820 // FIXME: this is likely to be wrong once we support template
821 // aliases, since a template alias could refer to a typedef that
822 // has an __aligned__ attribute on it.
823 return getTypeInfo(getCanonicalType(T));
824 }
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Chris Lattner464175b2007-07-18 17:52:12 +0000826 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000827 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000828}
829
Ken Dyckbdc601b2009-12-22 14:23:30 +0000830/// getTypeSizeInChars - Return the size of the specified type, in characters.
831/// This method does not work on incomplete types.
832CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000833 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000834}
835CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000836 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000837}
838
Ken Dyck16e20cc2010-01-26 17:25:18 +0000839/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000840/// characters. This method does not work on incomplete types.
841CharUnits ASTContext::getTypeAlignInChars(QualType T) {
842 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
843}
844CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
845 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
846}
847
Chris Lattner34ebde42009-01-27 18:08:34 +0000848/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
849/// type for the current target in bits. This can be different than the ABI
850/// alignment in cases where it is beneficial for performance to overalign
851/// a data type.
852unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
853 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000854
855 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000856 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000857 T = CT->getElementType().getTypePtr();
858 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
859 T->isSpecificBuiltinType(BuiltinType::LongLong))
860 return std::max(ABIAlign, (unsigned)getTypeSize(T));
861
Chris Lattner34ebde42009-01-27 18:08:34 +0000862 return ABIAlign;
863}
864
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000865static void CollectLocalObjCIvars(ASTContext *Ctx,
866 const ObjCInterfaceDecl *OI,
867 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000868 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
869 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000870 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000871 if (!IVDecl->isInvalidDecl())
872 Fields.push_back(cast<FieldDecl>(IVDecl));
873 }
874}
875
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000876void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
877 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
878 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
879 CollectObjCIvars(SuperClass, Fields);
880 CollectLocalObjCIvars(this, OI, Fields);
881}
882
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000883/// ShallowCollectObjCIvars -
884/// Collect all ivars, including those synthesized, in the current class.
885///
886void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000887 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000888 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
889 E = OI->ivar_end(); I != E; ++I) {
890 Ivars.push_back(*I);
891 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000892
893 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000894}
895
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000896/// CollectNonClassIvars -
897/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000898/// This includes synthesized ivars (via @synthesize) and those in
899// class's @implementation.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000900///
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000901void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000902 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000903 // Find ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000904 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
905 CDecl = CDecl->getNextClassExtension()) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000906 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
907 E = CDecl->ivar_end(); I != E; ++I) {
908 Ivars.push_back(*I);
909 }
910 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000911
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000912 // Also add any ivar defined in this class's implementation. This
913 // includes synthesized ivars.
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000914 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
915 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
916 E = ImplDecl->ivar_end(); I != E; ++I)
917 Ivars.push_back(*I);
918 }
Fariborz Jahanian98200742009-05-12 18:14:29 +0000919}
920
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000921/// CollectInheritedProtocols - Collect all protocols in current class and
922/// those inherited by it.
923void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000924 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000925 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
926 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
927 PE = OI->protocol_end(); P != PE; ++P) {
928 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000929 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000930 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000931 PE = Proto->protocol_end(); P != PE; ++P) {
932 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000933 CollectInheritedProtocols(*P, Protocols);
934 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000935 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000936
937 // Categories of this Interface.
938 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
939 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
940 CollectInheritedProtocols(CDeclChain, Protocols);
941 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
942 while (SD) {
943 CollectInheritedProtocols(SD, Protocols);
944 SD = SD->getSuperClass();
945 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000946 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000947 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
948 PE = OC->protocol_end(); P != PE; ++P) {
949 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000950 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000951 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
952 PE = Proto->protocol_end(); P != PE; ++P)
953 CollectInheritedProtocols(*P, Protocols);
954 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000955 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000956 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
957 PE = OP->protocol_end(); P != PE; ++P) {
958 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000959 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000960 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
961 PE = Proto->protocol_end(); P != PE; ++P)
962 CollectInheritedProtocols(*P, Protocols);
963 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000964 }
965}
966
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000967unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
968 unsigned count = 0;
969 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000970 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
971 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000972 count += CDecl->ivar_size();
973
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000974 // Count ivar defined in this class's implementation. This
975 // includes synthesized ivars.
976 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000977 count += ImplDecl->ivar_size();
978
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000979 return count;
980}
981
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000982/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
983ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
984 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
985 I = ObjCImpls.find(D);
986 if (I != ObjCImpls.end())
987 return cast<ObjCImplementationDecl>(I->second);
988 return 0;
989}
990/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
991ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
992 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
993 I = ObjCImpls.find(D);
994 if (I != ObjCImpls.end())
995 return cast<ObjCCategoryImplDecl>(I->second);
996 return 0;
997}
998
999/// \brief Set the implementation of ObjCInterfaceDecl.
1000void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1001 ObjCImplementationDecl *ImplD) {
1002 assert(IFaceD && ImplD && "Passed null params");
1003 ObjCImpls[IFaceD] = ImplD;
1004}
1005/// \brief Set the implementation of ObjCCategoryDecl.
1006void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1007 ObjCCategoryImplDecl *ImplD) {
1008 assert(CatD && ImplD && "Passed null params");
1009 ObjCImpls[CatD] = ImplD;
1010}
1011
John McCalla93c9342009-12-07 02:54:59 +00001012/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001013///
John McCalla93c9342009-12-07 02:54:59 +00001014/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001015/// the TypeLoc wrappers.
1016///
1017/// \param T the type that will be the basis for type source info. This type
1018/// should refer to how the declarator was written in source code, not to
1019/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001020TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001021 unsigned DataSize) {
1022 if (!DataSize)
1023 DataSize = TypeLoc::getFullDataSizeForType(T);
1024 else
1025 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001026 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001027
John McCalla93c9342009-12-07 02:54:59 +00001028 TypeSourceInfo *TInfo =
1029 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1030 new (TInfo) TypeSourceInfo(T);
1031 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001032}
1033
John McCalla93c9342009-12-07 02:54:59 +00001034TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001035 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001036 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001037 DI->getTypeLoc().initialize(L);
1038 return DI;
1039}
1040
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001041const ASTRecordLayout &
1042ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1043 return getObjCLayout(D, 0);
1044}
1045
1046const ASTRecordLayout &
1047ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1048 return getObjCLayout(D->getClassInterface(), D);
1049}
1050
Chris Lattnera7674d82007-07-13 22:13:22 +00001051//===----------------------------------------------------------------------===//
1052// Type creation/memoization methods
1053//===----------------------------------------------------------------------===//
1054
John McCall0953e762009-09-24 19:53:00 +00001055QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1056 unsigned Fast = Quals.getFastQualifiers();
1057 Quals.removeFastQualifiers();
1058
1059 // Check if we've already instantiated this type.
1060 llvm::FoldingSetNodeID ID;
1061 ExtQuals::Profile(ID, TypeNode, Quals);
1062 void *InsertPos = 0;
1063 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1064 assert(EQ->getQualifiers() == Quals);
1065 QualType T = QualType(EQ, Fast);
1066 return T;
1067 }
1068
John McCall6b304a02009-09-24 23:30:46 +00001069 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001070 ExtQualNodes.InsertNode(New, InsertPos);
1071 QualType T = QualType(New, Fast);
1072 return T;
1073}
1074
1075QualType ASTContext::getVolatileType(QualType T) {
1076 QualType CanT = getCanonicalType(T);
1077 if (CanT.isVolatileQualified()) return T;
1078
1079 QualifierCollector Quals;
1080 const Type *TypeNode = Quals.strip(T);
1081 Quals.addVolatile();
1082
1083 return getExtQualType(TypeNode, Quals);
1084}
1085
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001086QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001087 QualType CanT = getCanonicalType(T);
1088 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001089 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001090
John McCall0953e762009-09-24 19:53:00 +00001091 // If we are composing extended qualifiers together, merge together
1092 // into one ExtQuals node.
1093 QualifierCollector Quals;
1094 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001095
John McCall0953e762009-09-24 19:53:00 +00001096 // If this type already has an address space specified, it cannot get
1097 // another one.
1098 assert(!Quals.hasAddressSpace() &&
1099 "Type cannot be in multiple addr spaces!");
1100 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001101
John McCall0953e762009-09-24 19:53:00 +00001102 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001103}
1104
Chris Lattnerb7d25532009-02-18 22:53:11 +00001105QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001106 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001107 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001108 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001109 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001111 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001112 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001113 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001114 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1115 return getPointerType(ResultType);
1116 }
1117 }
Mike Stump1eb44332009-09-09 15:08:12 +00001118
John McCall0953e762009-09-24 19:53:00 +00001119 // If we are composing extended qualifiers together, merge together
1120 // into one ExtQuals node.
1121 QualifierCollector Quals;
1122 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001123
John McCall0953e762009-09-24 19:53:00 +00001124 // If this type already has an ObjCGC specified, it cannot get
1125 // another one.
1126 assert(!Quals.hasObjCGCAttr() &&
1127 "Type cannot have multiple ObjCGCs!");
1128 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001129
John McCall0953e762009-09-24 19:53:00 +00001130 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001131}
Chris Lattnera7674d82007-07-13 22:13:22 +00001132
Rafael Espindola264ba482010-03-30 20:24:48 +00001133static QualType getExtFunctionType(ASTContext& Context, QualType T,
1134 const FunctionType::ExtInfo &Info) {
John McCall0953e762009-09-24 19:53:00 +00001135 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001136 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1137 QualType Pointee = Pointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001138 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001139 if (ResultType == Pointee)
1140 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001141
1142 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001143 } else if (const BlockPointerType *BlockPointer
1144 = T->getAs<BlockPointerType>()) {
1145 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001146 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001147 if (ResultType == Pointee)
1148 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001149
1150 ResultType = Context.getBlockPointerType(ResultType);
1151 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001152 if (F->getExtInfo() == Info)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001153 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001154
Douglas Gregor43c79c22009-12-09 00:47:37 +00001155 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001156 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001157 Info);
John McCall0953e762009-09-24 19:53:00 +00001158 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001159 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001160 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001161 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1162 FPT->getNumArgs(), FPT->isVariadic(),
1163 FPT->getTypeQuals(),
1164 FPT->hasExceptionSpec(),
1165 FPT->hasAnyExceptionSpec(),
1166 FPT->getNumExceptions(),
1167 FPT->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001168 Info);
John McCall0953e762009-09-24 19:53:00 +00001169 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001170 } else
1171 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001172
1173 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1174}
1175
1176QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001177 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001178 return getExtFunctionType(*this, T,
1179 Info.withNoReturn(AddNoReturn));
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001180}
1181
1182QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001183 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001184 return getExtFunctionType(*this, T,
1185 Info.withCallingConv(CallConv));
Mike Stump24556362009-07-25 21:26:53 +00001186}
1187
Rafael Espindola425ef722010-03-30 22:15:11 +00001188QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1189 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1190 return getExtFunctionType(*this, T,
1191 Info.withRegParm(RegParm));
1192}
1193
Reid Spencer5f016e22007-07-11 17:01:13 +00001194/// getComplexType - Return the uniqued reference to the type for a complex
1195/// number with the specified element type.
1196QualType ASTContext::getComplexType(QualType T) {
1197 // Unique pointers, to guarantee there is only one pointer of a particular
1198 // structure.
1199 llvm::FoldingSetNodeID ID;
1200 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 void *InsertPos = 0;
1203 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1204 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Reid Spencer5f016e22007-07-11 17:01:13 +00001206 // If the pointee type isn't canonical, this won't be a canonical type either,
1207 // so fill in the canonical type field.
1208 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001209 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001210 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 // Get the new insert position for the node we care about.
1213 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001214 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 }
John McCall6b304a02009-09-24 23:30:46 +00001216 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 Types.push_back(New);
1218 ComplexTypes.InsertNode(New, InsertPos);
1219 return QualType(New, 0);
1220}
1221
Reid Spencer5f016e22007-07-11 17:01:13 +00001222/// getPointerType - Return the uniqued reference to the type for a pointer to
1223/// the specified type.
1224QualType ASTContext::getPointerType(QualType T) {
1225 // Unique pointers, to guarantee there is only one pointer of a particular
1226 // structure.
1227 llvm::FoldingSetNodeID ID;
1228 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 void *InsertPos = 0;
1231 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1232 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 // If the pointee type isn't canonical, this won't be a canonical type either,
1235 // so fill in the canonical type field.
1236 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001237 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001238 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 // Get the new insert position for the node we care about.
1241 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001242 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001243 }
John McCall6b304a02009-09-24 23:30:46 +00001244 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 Types.push_back(New);
1246 PointerTypes.InsertNode(New, InsertPos);
1247 return QualType(New, 0);
1248}
1249
Mike Stump1eb44332009-09-09 15:08:12 +00001250/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001251/// a pointer to the specified block.
1252QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001253 assert(T->isFunctionType() && "block of function types only");
1254 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001255 // structure.
1256 llvm::FoldingSetNodeID ID;
1257 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Steve Naroff5618bd42008-08-27 16:04:49 +00001259 void *InsertPos = 0;
1260 if (BlockPointerType *PT =
1261 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1262 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001263
1264 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001265 // type either so fill in the canonical type field.
1266 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001267 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001268 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Steve Naroff5618bd42008-08-27 16:04:49 +00001270 // Get the new insert position for the node we care about.
1271 BlockPointerType *NewIP =
1272 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001273 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001274 }
John McCall6b304a02009-09-24 23:30:46 +00001275 BlockPointerType *New
1276 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001277 Types.push_back(New);
1278 BlockPointerTypes.InsertNode(New, InsertPos);
1279 return QualType(New, 0);
1280}
1281
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001282/// getLValueReferenceType - Return the uniqued reference to the type for an
1283/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001284QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 // Unique pointers, to guarantee there is only one pointer of a particular
1286 // structure.
1287 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001288 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001289
1290 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001291 if (LValueReferenceType *RT =
1292 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001294
John McCall54e14c42009-10-22 22:37:11 +00001295 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1296
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 // If the referencee type isn't canonical, this won't be a canonical type
1298 // either, so fill in the canonical type field.
1299 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001300 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1301 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1302 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001303
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001305 LValueReferenceType *NewIP =
1306 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001307 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001308 }
1309
John McCall6b304a02009-09-24 23:30:46 +00001310 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001311 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1312 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001313 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001314 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001315
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001316 return QualType(New, 0);
1317}
1318
1319/// getRValueReferenceType - Return the uniqued reference to the type for an
1320/// rvalue reference to the specified type.
1321QualType ASTContext::getRValueReferenceType(QualType T) {
1322 // Unique pointers, to guarantee there is only one pointer of a particular
1323 // structure.
1324 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001325 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001326
1327 void *InsertPos = 0;
1328 if (RValueReferenceType *RT =
1329 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1330 return QualType(RT, 0);
1331
John McCall54e14c42009-10-22 22:37:11 +00001332 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1333
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001334 // If the referencee type isn't canonical, this won't be a canonical type
1335 // either, so fill in the canonical type field.
1336 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001337 if (InnerRef || !T.isCanonical()) {
1338 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1339 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001340
1341 // Get the new insert position for the node we care about.
1342 RValueReferenceType *NewIP =
1343 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1344 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1345 }
1346
John McCall6b304a02009-09-24 23:30:46 +00001347 RValueReferenceType *New
1348 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001349 Types.push_back(New);
1350 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 return QualType(New, 0);
1352}
1353
Sebastian Redlf30208a2009-01-24 21:16:55 +00001354/// getMemberPointerType - Return the uniqued reference to the type for a
1355/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001356QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001357 // Unique pointers, to guarantee there is only one pointer of a particular
1358 // structure.
1359 llvm::FoldingSetNodeID ID;
1360 MemberPointerType::Profile(ID, T, Cls);
1361
1362 void *InsertPos = 0;
1363 if (MemberPointerType *PT =
1364 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1365 return QualType(PT, 0);
1366
1367 // If the pointee or class type isn't canonical, this won't be a canonical
1368 // type either, so fill in the canonical type field.
1369 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001370 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001371 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1372
1373 // Get the new insert position for the node we care about.
1374 MemberPointerType *NewIP =
1375 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1376 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1377 }
John McCall6b304a02009-09-24 23:30:46 +00001378 MemberPointerType *New
1379 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001380 Types.push_back(New);
1381 MemberPointerTypes.InsertNode(New, InsertPos);
1382 return QualType(New, 0);
1383}
1384
Mike Stump1eb44332009-09-09 15:08:12 +00001385/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001386/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001387QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001388 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001389 ArrayType::ArraySizeModifier ASM,
1390 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001391 assert((EltTy->isDependentType() ||
1392 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001393 "Constant array of VLAs is illegal!");
1394
Chris Lattner38aeec72009-05-13 04:12:56 +00001395 // Convert the array size into a canonical width matching the pointer size for
1396 // the target.
1397 llvm::APInt ArySize(ArySizeIn);
1398 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001401 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001404 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001405 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 // If the element type isn't canonical, this won't be a canonical type either,
1409 // so fill in the canonical type field.
1410 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001411 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001412 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001413 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001415 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001416 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001417 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 }
Mike Stump1eb44332009-09-09 15:08:12 +00001419
John McCall6b304a02009-09-24 23:30:46 +00001420 ConstantArrayType *New = new(*this,TypeAlignment)
1421 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001422 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 Types.push_back(New);
1424 return QualType(New, 0);
1425}
1426
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001427/// getVariableArrayType - Returns a non-unique reference to the type for a
1428/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001429QualType ASTContext::getVariableArrayType(QualType EltTy,
1430 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001431 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001432 unsigned EltTypeQuals,
1433 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001434 // Since we don't unique expressions, it isn't possible to unique VLA's
1435 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001436 QualType CanonType;
1437
1438 if (!EltTy.isCanonical()) {
1439 if (NumElts)
1440 NumElts->Retain();
1441 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1442 EltTypeQuals, Brackets);
1443 }
1444
John McCall6b304a02009-09-24 23:30:46 +00001445 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001446 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001447
1448 VariableArrayTypes.push_back(New);
1449 Types.push_back(New);
1450 return QualType(New, 0);
1451}
1452
Douglas Gregor898574e2008-12-05 23:32:09 +00001453/// getDependentSizedArrayType - Returns a non-unique reference to
1454/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001455/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001456QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1457 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001458 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001459 unsigned EltTypeQuals,
1460 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001461 assert((!NumElts || NumElts->isTypeDependent() ||
1462 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001463 "Size must be type- or value-dependent!");
1464
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001465 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001466 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001467 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001468
1469 if (NumElts) {
1470 // Dependently-sized array types that do not have a specified
1471 // number of elements will have their sizes deduced from an
1472 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001473 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1474 EltTypeQuals, NumElts);
1475
1476 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1477 }
1478
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001479 DependentSizedArrayType *New;
1480 if (Canon) {
1481 // We already have a canonical version of this array type; use it as
1482 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001483 New = new (*this, TypeAlignment)
1484 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1485 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001486 } else {
1487 QualType CanonEltTy = getCanonicalType(EltTy);
1488 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001489 New = new (*this, TypeAlignment)
1490 DependentSizedArrayType(*this, EltTy, QualType(),
1491 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001492
Douglas Gregor789b1f62010-02-04 18:10:26 +00001493 if (NumElts) {
1494 DependentSizedArrayType *CanonCheck
1495 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1496 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1497 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001498 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001499 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001500 } else {
1501 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1502 ASM, EltTypeQuals,
1503 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001504 New = new (*this, TypeAlignment)
1505 DependentSizedArrayType(*this, EltTy, Canon,
1506 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001507 }
1508 }
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Douglas Gregor898574e2008-12-05 23:32:09 +00001510 Types.push_back(New);
1511 return QualType(New, 0);
1512}
1513
Eli Friedmanc5773c42008-02-15 18:16:39 +00001514QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1515 ArrayType::ArraySizeModifier ASM,
1516 unsigned EltTypeQuals) {
1517 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001518 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001519
1520 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001521 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001522 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1523 return QualType(ATP, 0);
1524
1525 // If the element type isn't canonical, this won't be a canonical type
1526 // either, so fill in the canonical type field.
1527 QualType Canonical;
1528
John McCall467b27b2009-10-22 20:10:53 +00001529 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001530 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001531 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001532
1533 // Get the new insert position for the node we care about.
1534 IncompleteArrayType *NewIP =
1535 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001536 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001537 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001538
John McCall6b304a02009-09-24 23:30:46 +00001539 IncompleteArrayType *New = new (*this, TypeAlignment)
1540 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001541
1542 IncompleteArrayTypes.InsertNode(New, InsertPos);
1543 Types.push_back(New);
1544 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001545}
1546
Steve Naroff73322922007-07-18 18:00:27 +00001547/// getVectorType - Return the unique reference to a vector type of
1548/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001549QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner788b0fd2010-06-23 06:00:24 +00001550 VectorType::AltiVecSpecific AltiVecSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Chris Lattnerf52ab252008-04-06 22:59:24 +00001553 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001554 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 // Check if we've already instantiated a vector of this type.
1557 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001558 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1559
Reid Spencer5f016e22007-07-11 17:01:13 +00001560 void *InsertPos = 0;
1561 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1562 return QualType(VTP, 0);
1563
1564 // If the element type isn't canonical, this won't be a canonical type either,
1565 // so fill in the canonical type field.
1566 QualType Canonical;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001567 if (!vecType.isCanonical() || (AltiVecSpec == VectorType::AltiVec)) {
1568 // pass VectorType::NotAltiVec for AltiVecSpec to make AltiVec canonical
1569 // vector type (except 'vector bool ...' and 'vector Pixel') the same as
1570 // the equivalent GCC vector types
1571 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1572 VectorType::NotAltiVec);
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 // Get the new insert position for the node we care about.
1575 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001576 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 }
John McCall6b304a02009-09-24 23:30:46 +00001578 VectorType *New = new (*this, TypeAlignment)
Chris Lattner788b0fd2010-06-23 06:00:24 +00001579 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 VectorTypes.InsertNode(New, InsertPos);
1581 Types.push_back(New);
1582 return QualType(New, 0);
1583}
1584
Nate Begeman213541a2008-04-18 23:10:10 +00001585/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001586/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001587QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001588 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Chris Lattnerf52ab252008-04-06 22:59:24 +00001590 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001591 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Steve Naroff73322922007-07-18 18:00:27 +00001593 // Check if we've already instantiated a vector of this type.
1594 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001595 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1596 VectorType::NotAltiVec);
Steve Naroff73322922007-07-18 18:00:27 +00001597 void *InsertPos = 0;
1598 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1599 return QualType(VTP, 0);
1600
1601 // If the element type isn't canonical, this won't be a canonical type either,
1602 // so fill in the canonical type field.
1603 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001604 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001605 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Steve Naroff73322922007-07-18 18:00:27 +00001607 // Get the new insert position for the node we care about.
1608 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001609 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001610 }
John McCall6b304a02009-09-24 23:30:46 +00001611 ExtVectorType *New = new (*this, TypeAlignment)
1612 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001613 VectorTypes.InsertNode(New, InsertPos);
1614 Types.push_back(New);
1615 return QualType(New, 0);
1616}
1617
Mike Stump1eb44332009-09-09 15:08:12 +00001618QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001619 Expr *SizeExpr,
1620 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001621 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001622 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001623 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001625 void *InsertPos = 0;
1626 DependentSizedExtVectorType *Canon
1627 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1628 DependentSizedExtVectorType *New;
1629 if (Canon) {
1630 // We already have a canonical version of this array type; use it as
1631 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001632 New = new (*this, TypeAlignment)
1633 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1634 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001635 } else {
1636 QualType CanonVecTy = getCanonicalType(vecType);
1637 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001638 New = new (*this, TypeAlignment)
1639 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1640 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001641
1642 DependentSizedExtVectorType *CanonCheck
1643 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1644 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1645 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001646 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1647 } else {
1648 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1649 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001650 New = new (*this, TypeAlignment)
1651 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001652 }
1653 }
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001655 Types.push_back(New);
1656 return QualType(New, 0);
1657}
1658
Douglas Gregor72564e72009-02-26 23:50:07 +00001659/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001660///
Rafael Espindola264ba482010-03-30 20:24:48 +00001661QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1662 const FunctionType::ExtInfo &Info) {
1663 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 // Unique functions, to guarantee there is only one function of a particular
1665 // structure.
1666 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001667 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001670 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001671 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001675 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001676 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001677 Canonical =
1678 getFunctionNoProtoType(getCanonicalType(ResultTy),
1679 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Reid Spencer5f016e22007-07-11 17:01:13 +00001681 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001682 FunctionNoProtoType *NewIP =
1683 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001684 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 }
Mike Stump1eb44332009-09-09 15:08:12 +00001686
John McCall6b304a02009-09-24 23:30:46 +00001687 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001688 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001690 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 return QualType(New, 0);
1692}
1693
1694/// getFunctionType - Return a normal function type with a typed argument
1695/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001696QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001697 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001698 unsigned TypeQuals, bool hasExceptionSpec,
1699 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001700 const QualType *ExArray,
1701 const FunctionType::ExtInfo &Info) {
1702 const CallingConv CallConv= Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 // Unique functions, to guarantee there is only one function of a particular
1704 // structure.
1705 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001706 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001707 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001708 NumExs, ExArray, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001709
1710 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001711 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001712 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001713 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001714
1715 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001716 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001718 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001719 isCanonical = false;
1720
1721 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001722 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001724 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 llvm::SmallVector<QualType, 16> CanonicalArgs;
1726 CanonicalArgs.reserve(NumArgs);
1727 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001728 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001729
Chris Lattnerf52ab252008-04-06 22:59:24 +00001730 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001731 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001732 isVariadic, TypeQuals, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00001733 false, 0, 0,
1734 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl465226e2009-05-27 22:11:52 +00001735
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001737 FunctionProtoType *NewIP =
1738 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001739 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001740 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001741
Douglas Gregor72564e72009-02-26 23:50:07 +00001742 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001743 // for two variable size arrays (for parameter and exception types) at the
1744 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001745 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001746 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1747 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001748 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001749 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001750 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001751 ExArray, NumExs, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001753 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 return QualType(FTP, 0);
1755}
1756
John McCall3cb0ebd2010-03-10 03:28:59 +00001757#ifndef NDEBUG
1758static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1759 if (!isa<CXXRecordDecl>(D)) return false;
1760 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1761 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1762 return true;
1763 if (RD->getDescribedClassTemplate() &&
1764 !isa<ClassTemplateSpecializationDecl>(RD))
1765 return true;
1766 return false;
1767}
1768#endif
1769
1770/// getInjectedClassNameType - Return the unique reference to the
1771/// injected class name type for the specified templated declaration.
1772QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1773 QualType TST) {
1774 assert(NeedsInjectedClassNameType(Decl));
1775 if (Decl->TypeForDecl) {
1776 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001777 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001778 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1779 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1780 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1781 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001782 Decl->TypeForDecl =
1783 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001784 Types.push_back(Decl->TypeForDecl);
1785 }
1786 return QualType(Decl->TypeForDecl, 0);
1787}
1788
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001789/// getTypeDeclType - Return the unique reference to the type for the
1790/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001791QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001792 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001793 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001794
John McCall19c85762010-02-16 03:57:14 +00001795 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001796 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001797
John McCallbecb8d52010-03-10 06:48:02 +00001798 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1799 "Template type parameter types are always available.");
1800
John McCall19c85762010-02-16 03:57:14 +00001801 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001802 assert(!Record->getPreviousDeclaration() &&
1803 "struct/union has previous declaration");
1804 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001805 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001806 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001807 assert(!Enum->getPreviousDeclaration() &&
1808 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001809 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001810 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001811 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1812 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001813 } else
John McCallbecb8d52010-03-10 06:48:02 +00001814 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001815
John McCallbecb8d52010-03-10 06:48:02 +00001816 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001817 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001818}
1819
Reid Spencer5f016e22007-07-11 17:01:13 +00001820/// getTypedefType - Return the unique reference to the type for the
1821/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001822QualType
1823ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001824 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001826 if (Canonical.isNull())
1827 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001828 Decl->TypeForDecl = new(*this, TypeAlignment)
1829 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 Types.push_back(Decl->TypeForDecl);
1831 return QualType(Decl->TypeForDecl, 0);
1832}
1833
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001834QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1835 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1836
1837 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1838 if (PrevDecl->TypeForDecl)
1839 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1840
1841 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1842 Types.push_back(Decl->TypeForDecl);
1843 return QualType(Decl->TypeForDecl, 0);
1844}
1845
1846QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1847 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1848
1849 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1850 if (PrevDecl->TypeForDecl)
1851 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1852
1853 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1854 Types.push_back(Decl->TypeForDecl);
1855 return QualType(Decl->TypeForDecl, 0);
1856}
1857
John McCall49a832b2009-10-18 09:09:24 +00001858/// \brief Retrieve a substitution-result type.
1859QualType
1860ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1861 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001862 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001863 && "replacement types must always be canonical");
1864
1865 llvm::FoldingSetNodeID ID;
1866 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1867 void *InsertPos = 0;
1868 SubstTemplateTypeParmType *SubstParm
1869 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1870
1871 if (!SubstParm) {
1872 SubstParm = new (*this, TypeAlignment)
1873 SubstTemplateTypeParmType(Parm, Replacement);
1874 Types.push_back(SubstParm);
1875 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1876 }
1877
1878 return QualType(SubstParm, 0);
1879}
1880
Douglas Gregorfab9d672009-02-05 23:33:38 +00001881/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001882/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001883/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001884QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001885 bool ParameterPack,
Douglas Gregorefed5c82010-06-16 15:23:05 +00001886 IdentifierInfo *Name) {
Douglas Gregorfab9d672009-02-05 23:33:38 +00001887 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00001888 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001889 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001890 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001891 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1892
1893 if (TypeParm)
1894 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Douglas Gregorefed5c82010-06-16 15:23:05 +00001896 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001897 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00001898 TypeParm = new (*this, TypeAlignment)
1899 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001900
1901 TemplateTypeParmType *TypeCheck
1902 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1903 assert(!TypeCheck && "Template type parameter canonical type broken");
1904 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001905 } else
John McCall6b304a02009-09-24 23:30:46 +00001906 TypeParm = new (*this, TypeAlignment)
1907 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001908
1909 Types.push_back(TypeParm);
1910 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1911
1912 return QualType(TypeParm, 0);
1913}
1914
John McCall3cb0ebd2010-03-10 03:28:59 +00001915TypeSourceInfo *
1916ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1917 SourceLocation NameLoc,
1918 const TemplateArgumentListInfo &Args,
1919 QualType CanonType) {
1920 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1921
1922 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1923 TemplateSpecializationTypeLoc TL
1924 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1925 TL.setTemplateNameLoc(NameLoc);
1926 TL.setLAngleLoc(Args.getLAngleLoc());
1927 TL.setRAngleLoc(Args.getRAngleLoc());
1928 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1929 TL.setArgLocInfo(i, Args[i].getLocInfo());
1930 return DI;
1931}
1932
Mike Stump1eb44332009-09-09 15:08:12 +00001933QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001934ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001935 const TemplateArgumentListInfo &Args,
John McCall71d74bc2010-06-13 09:25:03 +00001936 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001937 unsigned NumArgs = Args.size();
1938
John McCall833ca992009-10-29 08:12:44 +00001939 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1940 ArgVec.reserve(NumArgs);
1941 for (unsigned i = 0; i != NumArgs; ++i)
1942 ArgVec.push_back(Args[i].getArgument());
1943
John McCall31f17ec2010-04-27 00:57:59 +00001944 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001945 Canon);
John McCall833ca992009-10-29 08:12:44 +00001946}
1947
1948QualType
1949ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001950 const TemplateArgument *Args,
1951 unsigned NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001952 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001953 if (!Canon.isNull())
1954 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001955 else
1956 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001957
Douglas Gregor1275ae02009-07-28 23:00:59 +00001958 // Allocate the (non-canonical) template specialization type, but don't
1959 // try to unique it: these types typically have location information that
1960 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001961 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001962 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001963 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001964 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00001965 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00001966 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001967 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Douglas Gregor55f6b142009-02-09 18:46:07 +00001969 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001970 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001971}
1972
Mike Stump1eb44332009-09-09 15:08:12 +00001973QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001974ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1975 const TemplateArgument *Args,
1976 unsigned NumArgs) {
1977 // Build the canonical template specialization type.
1978 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1979 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1980 CanonArgs.reserve(NumArgs);
1981 for (unsigned I = 0; I != NumArgs; ++I)
1982 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1983
1984 // Determine whether this canonical template specialization type already
1985 // exists.
1986 llvm::FoldingSetNodeID ID;
1987 TemplateSpecializationType::Profile(ID, CanonTemplate,
1988 CanonArgs.data(), NumArgs, *this);
1989
1990 void *InsertPos = 0;
1991 TemplateSpecializationType *Spec
1992 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1993
1994 if (!Spec) {
1995 // Allocate a new canonical template specialization type.
1996 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1997 sizeof(TemplateArgument) * NumArgs),
1998 TypeAlignment);
1999 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2000 CanonArgs.data(), NumArgs,
2001 QualType());
2002 Types.push_back(Spec);
2003 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2004 }
2005
2006 assert(Spec->isDependentType() &&
2007 "Non-dependent template-id type must have a canonical type");
2008 return QualType(Spec, 0);
2009}
2010
2011QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002012ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2013 NestedNameSpecifier *NNS,
2014 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002015 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002016 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002017
2018 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002019 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002020 if (T)
2021 return QualType(T, 0);
2022
Douglas Gregor789b1f62010-02-04 18:10:26 +00002023 QualType Canon = NamedType;
2024 if (!Canon.isCanonical()) {
2025 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002026 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2027 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002028 (void)CheckT;
2029 }
2030
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002031 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002032 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002033 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002034 return QualType(T, 0);
2035}
2036
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002037QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2038 NestedNameSpecifier *NNS,
2039 const IdentifierInfo *Name,
2040 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00002041 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2042
2043 if (Canon.isNull()) {
2044 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002045 ElaboratedTypeKeyword CanonKeyword = Keyword;
2046 if (Keyword == ETK_None)
2047 CanonKeyword = ETK_Typename;
2048
2049 if (CanonNNS != NNS || CanonKeyword != Keyword)
2050 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002051 }
2052
2053 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002054 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002055
2056 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002057 DependentNameType *T
2058 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002059 if (T)
2060 return QualType(T, 0);
2061
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002062 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002063 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002064 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002065 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002066}
2067
Mike Stump1eb44332009-09-09 15:08:12 +00002068QualType
John McCall33500952010-06-11 00:33:02 +00002069ASTContext::getDependentTemplateSpecializationType(
2070 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002071 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002072 const IdentifierInfo *Name,
2073 const TemplateArgumentListInfo &Args) {
2074 // TODO: avoid this copy
2075 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2076 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2077 ArgCopy.push_back(Args[I].getArgument());
2078 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2079 ArgCopy.size(),
2080 ArgCopy.data());
2081}
2082
2083QualType
2084ASTContext::getDependentTemplateSpecializationType(
2085 ElaboratedTypeKeyword Keyword,
2086 NestedNameSpecifier *NNS,
2087 const IdentifierInfo *Name,
2088 unsigned NumArgs,
2089 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00002090 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2091
Douglas Gregor789b1f62010-02-04 18:10:26 +00002092 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002093 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2094 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002095
2096 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002097 DependentTemplateSpecializationType *T
2098 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002099 if (T)
2100 return QualType(T, 0);
2101
John McCall33500952010-06-11 00:33:02 +00002102 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002103
John McCall33500952010-06-11 00:33:02 +00002104 ElaboratedTypeKeyword CanonKeyword = Keyword;
2105 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2106
2107 bool AnyNonCanonArgs = false;
2108 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2109 for (unsigned I = 0; I != NumArgs; ++I) {
2110 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2111 if (!CanonArgs[I].structurallyEquals(Args[I]))
2112 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002113 }
2114
John McCall33500952010-06-11 00:33:02 +00002115 QualType Canon;
2116 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2117 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2118 Name, NumArgs,
2119 CanonArgs.data());
2120
2121 // Find the insert position again.
2122 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2123 }
2124
2125 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2126 sizeof(TemplateArgument) * NumArgs),
2127 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002128 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002129 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002130 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002131 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002132 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002133}
2134
Chris Lattner88cb27a2008-04-07 04:56:42 +00002135/// CmpProtocolNames - Comparison predicate for sorting protocols
2136/// alphabetically.
2137static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2138 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002139 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002140}
2141
John McCallc12c5bb2010-05-15 11:32:37 +00002142static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002143 unsigned NumProtocols) {
2144 if (NumProtocols == 0) return true;
2145
2146 for (unsigned i = 1; i != NumProtocols; ++i)
2147 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2148 return false;
2149 return true;
2150}
2151
2152static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002153 unsigned &NumProtocols) {
2154 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Chris Lattner88cb27a2008-04-07 04:56:42 +00002156 // Sort protocols, keyed by name.
2157 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2158
2159 // Remove duplicates.
2160 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2161 NumProtocols = ProtocolsEnd-Protocols;
2162}
2163
John McCallc12c5bb2010-05-15 11:32:37 +00002164QualType ASTContext::getObjCObjectType(QualType BaseType,
2165 ObjCProtocolDecl * const *Protocols,
2166 unsigned NumProtocols) {
2167 // If the base type is an interface and there aren't any protocols
2168 // to add, then the interface type will do just fine.
2169 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2170 return BaseType;
2171
2172 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002173 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002174 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002175 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002176 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2177 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002178
John McCallc12c5bb2010-05-15 11:32:37 +00002179 // Build the canonical type, which has the canonical base type and
2180 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002181 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002182 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2183 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2184 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002185 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2186 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002187 unsigned UniqueCount = NumProtocols;
2188
John McCall54e14c42009-10-22 22:37:11 +00002189 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002190 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2191 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002192 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002193 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2194 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002195 }
2196
2197 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002198 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2199 }
2200
2201 unsigned Size = sizeof(ObjCObjectTypeImpl);
2202 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2203 void *Mem = Allocate(Size, TypeAlignment);
2204 ObjCObjectTypeImpl *T =
2205 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2206
2207 Types.push_back(T);
2208 ObjCObjectTypes.InsertNode(T, InsertPos);
2209 return QualType(T, 0);
2210}
2211
2212/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2213/// the given object type.
2214QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2215 llvm::FoldingSetNodeID ID;
2216 ObjCObjectPointerType::Profile(ID, ObjectT);
2217
2218 void *InsertPos = 0;
2219 if (ObjCObjectPointerType *QT =
2220 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2221 return QualType(QT, 0);
2222
2223 // Find the canonical object type.
2224 QualType Canonical;
2225 if (!ObjectT.isCanonical()) {
2226 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2227
2228 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002229 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2230 }
2231
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002232 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002233 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2234 ObjCObjectPointerType *QType =
2235 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002237 Types.push_back(QType);
2238 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002239 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002240}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002241
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002242/// getObjCInterfaceType - Return the unique reference to the type for the
2243/// specified ObjC interface decl. The list of protocols is optional.
John McCallc12c5bb2010-05-15 11:32:37 +00002244QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2245 if (Decl->TypeForDecl)
2246 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002247
John McCallc12c5bb2010-05-15 11:32:37 +00002248 // FIXME: redeclarations?
2249 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2250 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2251 Decl->TypeForDecl = T;
2252 Types.push_back(T);
2253 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002254}
2255
Douglas Gregor72564e72009-02-26 23:50:07 +00002256/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2257/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002258/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002259/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002260/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002261QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002262 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002263 if (tofExpr->isTypeDependent()) {
2264 llvm::FoldingSetNodeID ID;
2265 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002266
Douglas Gregorb1975722009-07-30 23:18:24 +00002267 void *InsertPos = 0;
2268 DependentTypeOfExprType *Canon
2269 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2270 if (Canon) {
2271 // We already have a "canonical" version of an identical, dependent
2272 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002273 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002274 QualType((TypeOfExprType*)Canon, 0));
2275 }
2276 else {
2277 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002278 Canon
2279 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002280 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2281 toe = Canon;
2282 }
2283 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002284 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002285 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002286 }
Steve Naroff9752f252007-08-01 18:02:17 +00002287 Types.push_back(toe);
2288 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002289}
2290
Steve Naroff9752f252007-08-01 18:02:17 +00002291/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2292/// TypeOfType AST's. The only motivation to unique these nodes would be
2293/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002294/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002295/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002296QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002297 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002298 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002299 Types.push_back(tot);
2300 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002301}
2302
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002303/// getDecltypeForExpr - Given an expr, will return the decltype for that
2304/// expression, according to the rules in C++0x [dcl.type.simple]p4
2305static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002306 if (e->isTypeDependent())
2307 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002309 // If e is an id expression or a class member access, decltype(e) is defined
2310 // as the type of the entity named by e.
2311 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2312 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2313 return VD->getType();
2314 }
2315 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2316 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2317 return FD->getType();
2318 }
2319 // If e is a function call or an invocation of an overloaded operator,
2320 // (parentheses around e are ignored), decltype(e) is defined as the
2321 // return type of that function.
2322 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2323 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002324
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002325 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002326
2327 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002328 // defined as T&, otherwise decltype(e) is defined as T.
2329 if (e->isLvalue(Context) == Expr::LV_Valid)
2330 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002332 return T;
2333}
2334
Anders Carlsson395b4752009-06-24 19:06:50 +00002335/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2336/// DecltypeType AST's. The only motivation to unique these nodes would be
2337/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002338/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002339/// on canonical type's (which are always unique).
2340QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002341 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002342 if (e->isTypeDependent()) {
2343 llvm::FoldingSetNodeID ID;
2344 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002345
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002346 void *InsertPos = 0;
2347 DependentDecltypeType *Canon
2348 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2349 if (Canon) {
2350 // We already have a "canonical" version of an equivalent, dependent
2351 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002352 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002353 QualType((DecltypeType*)Canon, 0));
2354 }
2355 else {
2356 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002357 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002358 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2359 dt = Canon;
2360 }
2361 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002362 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002363 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002364 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002365 Types.push_back(dt);
2366 return QualType(dt, 0);
2367}
2368
Reid Spencer5f016e22007-07-11 17:01:13 +00002369/// getTagDeclType - Return the unique reference to the type for the
2370/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002371QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002372 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002373 // FIXME: What is the design on getTagDeclType when it requires casting
2374 // away const? mutable?
2375 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002376}
2377
Mike Stump1eb44332009-09-09 15:08:12 +00002378/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2379/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2380/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002381CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002382 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002383}
2384
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002385/// getSignedWCharType - Return the type of "signed wchar_t".
2386/// Used when in C++, as a GCC extension.
2387QualType ASTContext::getSignedWCharType() const {
2388 // FIXME: derive from "Target" ?
2389 return WCharTy;
2390}
2391
2392/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2393/// Used when in C++, as a GCC extension.
2394QualType ASTContext::getUnsignedWCharType() const {
2395 // FIXME: derive from "Target" ?
2396 return UnsignedIntTy;
2397}
2398
Chris Lattner8b9023b2007-07-13 03:05:23 +00002399/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2400/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2401QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002402 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002403}
2404
Chris Lattnere6327742008-04-02 05:18:44 +00002405//===----------------------------------------------------------------------===//
2406// Type Operators
2407//===----------------------------------------------------------------------===//
2408
John McCall54e14c42009-10-22 22:37:11 +00002409CanQualType ASTContext::getCanonicalParamType(QualType T) {
2410 // Push qualifiers into arrays, and then discard any remaining
2411 // qualifiers.
2412 T = getCanonicalType(T);
2413 const Type *Ty = T.getTypePtr();
2414
2415 QualType Result;
2416 if (isa<ArrayType>(Ty)) {
2417 Result = getArrayDecayedType(QualType(Ty,0));
2418 } else if (isa<FunctionType>(Ty)) {
2419 Result = getPointerType(QualType(Ty, 0));
2420 } else {
2421 Result = QualType(Ty, 0);
2422 }
2423
2424 return CanQualType::CreateUnsafe(Result);
2425}
2426
Chris Lattner77c96472008-04-06 22:41:35 +00002427/// getCanonicalType - Return the canonical (structural) type corresponding to
2428/// the specified potentially non-canonical type. The non-canonical version
2429/// of a type may have many "decorated" versions of types. Decorators can
2430/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2431/// to be free of any of these, allowing two canonical types to be compared
2432/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002433CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002434 QualifierCollector Quals;
2435 const Type *Ptr = Quals.strip(T);
2436 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002437
John McCall0953e762009-09-24 19:53:00 +00002438 // The canonical internal type will be the canonical type *except*
2439 // that we push type qualifiers down through array types.
2440
2441 // If there are no new qualifiers to push down, stop here.
2442 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002443 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002444
John McCall0953e762009-09-24 19:53:00 +00002445 // If the type qualifiers are on an array type, get the canonical
2446 // type of the array with the qualifiers applied to the element
2447 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002448 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2449 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002450 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002451
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002452 // Get the canonical version of the element with the extra qualifiers on it.
2453 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002454 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002455 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002456
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002457 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002458 return CanQualType::CreateUnsafe(
2459 getConstantArrayType(NewEltTy, CAT->getSize(),
2460 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002461 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002462 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002463 return CanQualType::CreateUnsafe(
2464 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002465 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002466
Douglas Gregor898574e2008-12-05 23:32:09 +00002467 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002468 return CanQualType::CreateUnsafe(
2469 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002470 DSAT->getSizeExpr() ?
2471 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002472 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002473 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002474 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002475
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002476 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002477 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002478 VAT->getSizeExpr() ?
2479 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002480 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002481 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002482 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002483}
2484
Chandler Carruth28e318c2009-12-29 07:16:59 +00002485QualType ASTContext::getUnqualifiedArrayType(QualType T,
2486 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002487 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002488 const ArrayType *AT = getAsArrayType(T);
2489 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002490 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002491 }
2492
Chandler Carruth28e318c2009-12-29 07:16:59 +00002493 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002494 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002495 if (Elt == UnqualElt)
2496 return T;
2497
Douglas Gregor9dadd942010-05-17 18:45:21 +00002498 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002499 return getConstantArrayType(UnqualElt, CAT->getSize(),
2500 CAT->getSizeModifier(), 0);
2501 }
2502
Douglas Gregor9dadd942010-05-17 18:45:21 +00002503 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002504 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2505 }
2506
Douglas Gregor9dadd942010-05-17 18:45:21 +00002507 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2508 return getVariableArrayType(UnqualElt,
2509 VAT->getSizeExpr() ?
2510 VAT->getSizeExpr()->Retain() : 0,
2511 VAT->getSizeModifier(),
2512 VAT->getIndexTypeCVRQualifiers(),
2513 VAT->getBracketsRange());
2514 }
2515
2516 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002517 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2518 DSAT->getSizeModifier(), 0,
2519 SourceRange());
2520}
2521
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002522/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2523/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2524/// they point to and return true. If T1 and T2 aren't pointer types
2525/// or pointer-to-member types, or if they are not similar at this
2526/// level, returns false and leaves T1 and T2 unchanged. Top-level
2527/// qualifiers on T1 and T2 are ignored. This function will typically
2528/// be called in a loop that successively "unwraps" pointer and
2529/// pointer-to-member types to compare them at each level.
2530bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2531 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2532 *T2PtrType = T2->getAs<PointerType>();
2533 if (T1PtrType && T2PtrType) {
2534 T1 = T1PtrType->getPointeeType();
2535 T2 = T2PtrType->getPointeeType();
2536 return true;
2537 }
2538
2539 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2540 *T2MPType = T2->getAs<MemberPointerType>();
2541 if (T1MPType && T2MPType &&
2542 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2543 QualType(T2MPType->getClass(), 0))) {
2544 T1 = T1MPType->getPointeeType();
2545 T2 = T2MPType->getPointeeType();
2546 return true;
2547 }
2548
2549 if (getLangOptions().ObjC1) {
2550 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2551 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2552 if (T1OPType && T2OPType) {
2553 T1 = T1OPType->getPointeeType();
2554 T2 = T2OPType->getPointeeType();
2555 return true;
2556 }
2557 }
2558
2559 // FIXME: Block pointers, too?
2560
2561 return false;
2562}
2563
John McCall80ad16f2009-11-24 18:42:40 +00002564DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2565 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2566 return TD->getDeclName();
2567
2568 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2569 if (DTN->isIdentifier()) {
2570 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2571 } else {
2572 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2573 }
2574 }
2575
John McCall0bd6feb2009-12-02 08:04:21 +00002576 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2577 assert(Storage);
2578 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002579}
2580
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002581TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002582 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2583 if (TemplateTemplateParmDecl *TTP
2584 = dyn_cast<TemplateTemplateParmDecl>(Template))
2585 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2586
2587 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002588 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002589 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002590
John McCall0bd6feb2009-12-02 08:04:21 +00002591 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002592
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002593 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2594 assert(DTN && "Non-dependent template names must refer to template decls.");
2595 return DTN->CanonicalTemplateName;
2596}
2597
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002598bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2599 X = getCanonicalTemplateName(X);
2600 Y = getCanonicalTemplateName(Y);
2601 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2602}
2603
Mike Stump1eb44332009-09-09 15:08:12 +00002604TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002605ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2606 switch (Arg.getKind()) {
2607 case TemplateArgument::Null:
2608 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002609
Douglas Gregor1275ae02009-07-28 23:00:59 +00002610 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002611 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Douglas Gregor1275ae02009-07-28 23:00:59 +00002613 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002614 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Douglas Gregor788cd062009-11-11 01:00:40 +00002616 case TemplateArgument::Template:
2617 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2618
Douglas Gregor1275ae02009-07-28 23:00:59 +00002619 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002620 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002621 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002622
Douglas Gregor1275ae02009-07-28 23:00:59 +00002623 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002624 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002625
Douglas Gregor1275ae02009-07-28 23:00:59 +00002626 case TemplateArgument::Pack: {
2627 // FIXME: Allocate in ASTContext
2628 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2629 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002630 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002631 AEnd = Arg.pack_end();
2632 A != AEnd; (void)++A, ++Idx)
2633 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002634
Douglas Gregor1275ae02009-07-28 23:00:59 +00002635 TemplateArgument Result;
2636 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2637 return Result;
2638 }
2639 }
2640
2641 // Silence GCC warning
2642 assert(false && "Unhandled template argument kind");
2643 return TemplateArgument();
2644}
2645
Douglas Gregord57959a2009-03-27 23:10:48 +00002646NestedNameSpecifier *
2647ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002648 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002649 return 0;
2650
2651 switch (NNS->getKind()) {
2652 case NestedNameSpecifier::Identifier:
2653 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002654 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002655 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2656 NNS->getAsIdentifier());
2657
2658 case NestedNameSpecifier::Namespace:
2659 // A namespace is canonical; build a nested-name-specifier with
2660 // this namespace and no prefix.
2661 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2662
2663 case NestedNameSpecifier::TypeSpec:
2664 case NestedNameSpecifier::TypeSpecWithTemplate: {
2665 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002666 return NestedNameSpecifier::Create(*this, 0,
2667 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002668 T.getTypePtr());
2669 }
2670
2671 case NestedNameSpecifier::Global:
2672 // The global specifier is canonical and unique.
2673 return NNS;
2674 }
2675
2676 // Required to silence a GCC warning
2677 return 0;
2678}
2679
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002680
2681const ArrayType *ASTContext::getAsArrayType(QualType T) {
2682 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002683 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002684 // Handle the common positive case fast.
2685 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2686 return AT;
2687 }
Mike Stump1eb44332009-09-09 15:08:12 +00002688
John McCall0953e762009-09-24 19:53:00 +00002689 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002690 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002691 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002692 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002693
John McCall0953e762009-09-24 19:53:00 +00002694 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002695 // implements C99 6.7.3p8: "If the specification of an array type includes
2696 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002697
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002698 // If we get here, we either have type qualifiers on the type, or we have
2699 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002700 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002701
John McCall0953e762009-09-24 19:53:00 +00002702 QualifierCollector Qs;
2703 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002704
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002705 // If we have a simple case, just return now.
2706 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002707 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002708 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002709
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002710 // Otherwise, we have an array and we have qualifiers on it. Push the
2711 // qualifiers into the array element type and return a new array type.
2712 // Get the canonical version of the element with the extra qualifiers on it.
2713 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002714 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002716 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2717 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2718 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002719 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002720 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2721 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2722 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002723 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002724
Mike Stump1eb44332009-09-09 15:08:12 +00002725 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002726 = dyn_cast<DependentSizedArrayType>(ATy))
2727 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002728 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002729 DSAT->getSizeExpr() ?
2730 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002731 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002732 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002733 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002735 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002736 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002737 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002738 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002739 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002740 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002741 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002742}
2743
2744
Chris Lattnere6327742008-04-02 05:18:44 +00002745/// getArrayDecayedType - Return the properly qualified result of decaying the
2746/// specified array type to a pointer. This operation is non-trivial when
2747/// handling typedefs etc. The canonical type of "T" must be an array type,
2748/// this returns a pointer to a properly qualified element of the array.
2749///
2750/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2751QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002752 // Get the element type with 'getAsArrayType' so that we don't lose any
2753 // typedefs in the element type of the array. This also handles propagation
2754 // of type qualifiers from the array type into the element type if present
2755 // (C99 6.7.3p8).
2756 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2757 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002758
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002759 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002760
2761 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002762 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002763}
2764
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002765QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002766 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002767 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2768 QT = AT->getElementType();
2769 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002770}
2771
Anders Carlssonfbbce492009-09-25 01:23:32 +00002772QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2773 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002774
Anders Carlssonfbbce492009-09-25 01:23:32 +00002775 if (const ArrayType *AT = getAsArrayType(ElemTy))
2776 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002777
Anders Carlsson6183a992008-12-21 03:44:36 +00002778 return ElemTy;
2779}
2780
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002781/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002782uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002783ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2784 uint64_t ElementCount = 1;
2785 do {
2786 ElementCount *= CA->getSize().getZExtValue();
2787 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2788 } while (CA);
2789 return ElementCount;
2790}
2791
Reid Spencer5f016e22007-07-11 17:01:13 +00002792/// getFloatingRank - Return a relative rank for floating point types.
2793/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002794static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002795 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002797
John McCall183700f2009-09-21 23:43:11 +00002798 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2799 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002800 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 case BuiltinType::Float: return FloatRank;
2802 case BuiltinType::Double: return DoubleRank;
2803 case BuiltinType::LongDouble: return LongDoubleRank;
2804 }
2805}
2806
Mike Stump1eb44332009-09-09 15:08:12 +00002807/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2808/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002809/// 'typeDomain' is a real floating point or complex type.
2810/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002811QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2812 QualType Domain) const {
2813 FloatingRank EltRank = getFloatingRank(Size);
2814 if (Domain->isComplexType()) {
2815 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002816 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002817 case FloatRank: return FloatComplexTy;
2818 case DoubleRank: return DoubleComplexTy;
2819 case LongDoubleRank: return LongDoubleComplexTy;
2820 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002821 }
Chris Lattner1361b112008-04-06 23:58:54 +00002822
2823 assert(Domain->isRealFloatingType() && "Unknown domain!");
2824 switch (EltRank) {
2825 default: assert(0 && "getFloatingRank(): illegal value for rank");
2826 case FloatRank: return FloatTy;
2827 case DoubleRank: return DoubleTy;
2828 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002829 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002830}
2831
Chris Lattner7cfeb082008-04-06 23:55:33 +00002832/// getFloatingTypeOrder - Compare the rank of the two specified floating
2833/// point types, ignoring the domain of the type (i.e. 'double' ==
2834/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002835/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002836int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2837 FloatingRank LHSR = getFloatingRank(LHS);
2838 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002839
Chris Lattnera75cea32008-04-06 23:38:49 +00002840 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002841 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002842 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002843 return 1;
2844 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002845}
2846
Chris Lattnerf52ab252008-04-06 22:59:24 +00002847/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2848/// routine will assert if passed a built-in type that isn't an integer or enum,
2849/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002850unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002851 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002852 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002853 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002854
Eli Friedmana3426752009-07-05 23:44:27 +00002855 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2856 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2857
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002858 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2859 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2860
2861 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2862 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2863
Chris Lattnerf52ab252008-04-06 22:59:24 +00002864 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002865 default: assert(0 && "getIntegerRank(): not a built-in integer");
2866 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002867 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002868 case BuiltinType::Char_S:
2869 case BuiltinType::Char_U:
2870 case BuiltinType::SChar:
2871 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002872 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002873 case BuiltinType::Short:
2874 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002875 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002876 case BuiltinType::Int:
2877 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002878 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002879 case BuiltinType::Long:
2880 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002881 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002882 case BuiltinType::LongLong:
2883 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002884 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002885 case BuiltinType::Int128:
2886 case BuiltinType::UInt128:
2887 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002888 }
2889}
2890
Eli Friedman04e83572009-08-20 04:21:42 +00002891/// \brief Whether this is a promotable bitfield reference according
2892/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2893///
2894/// \returns the type this bit-field will promote to, or NULL if no
2895/// promotion occurs.
2896QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002897 if (E->isTypeDependent() || E->isValueDependent())
2898 return QualType();
2899
Eli Friedman04e83572009-08-20 04:21:42 +00002900 FieldDecl *Field = E->getBitField();
2901 if (!Field)
2902 return QualType();
2903
2904 QualType FT = Field->getType();
2905
2906 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2907 uint64_t BitWidth = BitWidthAP.getZExtValue();
2908 uint64_t IntSize = getTypeSize(IntTy);
2909 // GCC extension compatibility: if the bit-field size is less than or equal
2910 // to the size of int, it gets promoted no matter what its type is.
2911 // For instance, unsigned long bf : 4 gets promoted to signed int.
2912 if (BitWidth < IntSize)
2913 return IntTy;
2914
2915 if (BitWidth == IntSize)
2916 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2917
2918 // Types bigger than int are not subject to promotions, and therefore act
2919 // like the base type.
2920 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2921 // is ridiculous.
2922 return QualType();
2923}
2924
Eli Friedmana95d7572009-08-19 07:44:53 +00002925/// getPromotedIntegerType - Returns the type that Promotable will
2926/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2927/// integer type.
2928QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2929 assert(!Promotable.isNull());
2930 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002931 if (const EnumType *ET = Promotable->getAs<EnumType>())
2932 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002933 if (Promotable->isSignedIntegerType())
2934 return IntTy;
2935 uint64_t PromotableSize = getTypeSize(Promotable);
2936 uint64_t IntSize = getTypeSize(IntTy);
2937 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2938 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2939}
2940
Mike Stump1eb44332009-09-09 15:08:12 +00002941/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002942/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002943/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002944int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002945 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2946 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002947 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002948
Chris Lattnerf52ab252008-04-06 22:59:24 +00002949 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2950 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002951
Chris Lattner7cfeb082008-04-06 23:55:33 +00002952 unsigned LHSRank = getIntegerRank(LHSC);
2953 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002954
Chris Lattner7cfeb082008-04-06 23:55:33 +00002955 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2956 if (LHSRank == RHSRank) return 0;
2957 return LHSRank > RHSRank ? 1 : -1;
2958 }
Mike Stump1eb44332009-09-09 15:08:12 +00002959
Chris Lattner7cfeb082008-04-06 23:55:33 +00002960 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2961 if (LHSUnsigned) {
2962 // If the unsigned [LHS] type is larger, return it.
2963 if (LHSRank >= RHSRank)
2964 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002965
Chris Lattner7cfeb082008-04-06 23:55:33 +00002966 // If the signed type can represent all values of the unsigned type, it
2967 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002968 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002969 return -1;
2970 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002971
Chris Lattner7cfeb082008-04-06 23:55:33 +00002972 // If the unsigned [RHS] type is larger, return it.
2973 if (RHSRank >= LHSRank)
2974 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002975
Chris Lattner7cfeb082008-04-06 23:55:33 +00002976 // If the signed type can represent all values of the unsigned type, it
2977 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002978 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002979 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002980}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002981
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002982static RecordDecl *
2983CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2984 SourceLocation L, IdentifierInfo *Id) {
2985 if (Ctx.getLangOptions().CPlusPlus)
2986 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2987 else
2988 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2989}
2990
Mike Stump1eb44332009-09-09 15:08:12 +00002991// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002992QualType ASTContext::getCFConstantStringType() {
2993 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002994 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002995 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002996 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00002997 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002998
Anders Carlssonf06273f2007-11-19 00:25:30 +00002999 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003000
Anders Carlsson71993dd2007-08-17 05:31:46 +00003001 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003002 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003003 // int flags;
3004 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003005 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003006 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003007 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003008 FieldTypes[3] = LongTy;
3009
Anders Carlsson71993dd2007-08-17 05:31:46 +00003010 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003011 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003012 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003013 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003014 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003015 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003016 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003017 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003018 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003019 }
3020
Douglas Gregor838db382010-02-11 01:19:42 +00003021 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003022 }
Mike Stump1eb44332009-09-09 15:08:12 +00003023
Anders Carlsson71993dd2007-08-17 05:31:46 +00003024 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003025}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003026
Douglas Gregor319ac892009-04-23 22:29:11 +00003027void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003028 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003029 assert(Rec && "Invalid CFConstantStringType");
3030 CFConstantStringTypeDecl = Rec->getDecl();
3031}
3032
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003033// getNSConstantStringType - Return the type used for constant NSStrings.
3034QualType ASTContext::getNSConstantStringType() {
3035 if (!NSConstantStringTypeDecl) {
3036 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003037 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003038 &Idents.get("__builtin_NSString"));
3039 NSConstantStringTypeDecl->startDefinition();
3040
3041 QualType FieldTypes[3];
3042
3043 // const int *isa;
3044 FieldTypes[0] = getPointerType(IntTy.withConst());
3045 // const char *str;
3046 FieldTypes[1] = getPointerType(CharTy.withConst());
3047 // unsigned int length;
3048 FieldTypes[2] = UnsignedIntTy;
3049
3050 // Create fields
3051 for (unsigned i = 0; i < 3; ++i) {
3052 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3053 SourceLocation(), 0,
3054 FieldTypes[i], /*TInfo=*/0,
3055 /*BitWidth=*/0,
3056 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003057 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003058 NSConstantStringTypeDecl->addDecl(Field);
3059 }
3060
3061 NSConstantStringTypeDecl->completeDefinition();
3062 }
3063
3064 return getTagDeclType(NSConstantStringTypeDecl);
3065}
3066
3067void ASTContext::setNSConstantStringType(QualType T) {
3068 const RecordType *Rec = T->getAs<RecordType>();
3069 assert(Rec && "Invalid NSConstantStringType");
3070 NSConstantStringTypeDecl = Rec->getDecl();
3071}
3072
Mike Stump1eb44332009-09-09 15:08:12 +00003073QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003074 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003075 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003076 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003077 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003078 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003079
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003080 QualType FieldTypes[] = {
3081 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003082 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003083 getPointerType(UnsignedLongTy),
3084 getConstantArrayType(UnsignedLongTy,
3085 llvm::APInt(32, 5), ArrayType::Normal, 0)
3086 };
Mike Stump1eb44332009-09-09 15:08:12 +00003087
Douglas Gregor44b43212008-12-11 16:49:14 +00003088 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003089 FieldDecl *Field = FieldDecl::Create(*this,
3090 ObjCFastEnumerationStateTypeDecl,
3091 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003092 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003093 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003094 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003095 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003096 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003097 }
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003098 if (getLangOptions().CPlusPlus)
Fariborz Jahanian81148e92010-05-27 16:35:00 +00003099 if (CXXRecordDecl *CXXRD =
3100 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003101 CXXRD->setEmpty(false);
Mike Stump1eb44332009-09-09 15:08:12 +00003102
Douglas Gregor838db382010-02-11 01:19:42 +00003103 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003104 }
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003106 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3107}
3108
Mike Stumpadaaad32009-10-20 02:12:22 +00003109QualType ASTContext::getBlockDescriptorType() {
3110 if (BlockDescriptorType)
3111 return getTagDeclType(BlockDescriptorType);
3112
3113 RecordDecl *T;
3114 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003115 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003116 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003117 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003118
3119 QualType FieldTypes[] = {
3120 UnsignedLongTy,
3121 UnsignedLongTy,
3122 };
3123
3124 const char *FieldNames[] = {
3125 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003126 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003127 };
3128
3129 for (size_t i = 0; i < 2; ++i) {
3130 FieldDecl *Field = FieldDecl::Create(*this,
3131 T,
3132 SourceLocation(),
3133 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003134 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003135 /*BitWidth=*/0,
3136 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003137 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003138 T->addDecl(Field);
3139 }
3140
Douglas Gregor838db382010-02-11 01:19:42 +00003141 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003142
3143 BlockDescriptorType = T;
3144
3145 return getTagDeclType(BlockDescriptorType);
3146}
3147
3148void ASTContext::setBlockDescriptorType(QualType T) {
3149 const RecordType *Rec = T->getAs<RecordType>();
3150 assert(Rec && "Invalid BlockDescriptorType");
3151 BlockDescriptorType = Rec->getDecl();
3152}
3153
Mike Stump083c25e2009-10-22 00:49:09 +00003154QualType ASTContext::getBlockDescriptorExtendedType() {
3155 if (BlockDescriptorExtendedType)
3156 return getTagDeclType(BlockDescriptorExtendedType);
3157
3158 RecordDecl *T;
3159 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003160 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003161 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003162 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003163
3164 QualType FieldTypes[] = {
3165 UnsignedLongTy,
3166 UnsignedLongTy,
3167 getPointerType(VoidPtrTy),
3168 getPointerType(VoidPtrTy)
3169 };
3170
3171 const char *FieldNames[] = {
3172 "reserved",
3173 "Size",
3174 "CopyFuncPtr",
3175 "DestroyFuncPtr"
3176 };
3177
3178 for (size_t i = 0; i < 4; ++i) {
3179 FieldDecl *Field = FieldDecl::Create(*this,
3180 T,
3181 SourceLocation(),
3182 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003183 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003184 /*BitWidth=*/0,
3185 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003186 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003187 T->addDecl(Field);
3188 }
3189
Douglas Gregor838db382010-02-11 01:19:42 +00003190 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003191
3192 BlockDescriptorExtendedType = T;
3193
3194 return getTagDeclType(BlockDescriptorExtendedType);
3195}
3196
3197void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3198 const RecordType *Rec = T->getAs<RecordType>();
3199 assert(Rec && "Invalid BlockDescriptorType");
3200 BlockDescriptorExtendedType = Rec->getDecl();
3201}
3202
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003203bool ASTContext::BlockRequiresCopying(QualType Ty) {
3204 if (Ty->isBlockPointerType())
3205 return true;
3206 if (isObjCNSObjectType(Ty))
3207 return true;
3208 if (Ty->isObjCObjectPointerType())
3209 return true;
3210 return false;
3211}
3212
3213QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3214 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003215 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003216 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003217 // unsigned int __flags;
3218 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003219 // void *__copy_helper; // as needed
3220 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003221 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003222 // } *
3223
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003224 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3225
3226 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003227 llvm::SmallString<36> Name;
3228 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3229 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003230 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003231 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003232 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003233 T->startDefinition();
3234 QualType Int32Ty = IntTy;
3235 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3236 QualType FieldTypes[] = {
3237 getPointerType(VoidPtrTy),
3238 getPointerType(getTagDeclType(T)),
3239 Int32Ty,
3240 Int32Ty,
3241 getPointerType(VoidPtrTy),
3242 getPointerType(VoidPtrTy),
3243 Ty
3244 };
3245
3246 const char *FieldNames[] = {
3247 "__isa",
3248 "__forwarding",
3249 "__flags",
3250 "__size",
3251 "__copy_helper",
3252 "__destroy_helper",
3253 DeclName,
3254 };
3255
3256 for (size_t i = 0; i < 7; ++i) {
3257 if (!HasCopyAndDispose && i >=4 && i <= 5)
3258 continue;
3259 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3260 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003261 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003262 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003263 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003264 T->addDecl(Field);
3265 }
3266
Douglas Gregor838db382010-02-11 01:19:42 +00003267 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003268
3269 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003270}
3271
3272
3273QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003274 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003275 llvm::SmallVectorImpl<const Expr *> &Layout) {
3276
Mike Stumpadaaad32009-10-20 02:12:22 +00003277 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003278 llvm::SmallString<36> Name;
3279 llvm::raw_svector_ostream(Name) << "__block_literal_"
3280 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003281 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003282 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003283 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003284 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003285 QualType FieldTypes[] = {
3286 getPointerType(VoidPtrTy),
3287 IntTy,
3288 IntTy,
3289 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003290 (BlockHasCopyDispose ?
3291 getPointerType(getBlockDescriptorExtendedType()) :
3292 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003293 };
3294
3295 const char *FieldNames[] = {
3296 "__isa",
3297 "__flags",
3298 "__reserved",
3299 "__FuncPtr",
3300 "__descriptor"
3301 };
3302
3303 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003304 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003305 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003306 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003307 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003308 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003309 T->addDecl(Field);
3310 }
3311
John McCallea1471e2010-05-20 01:18:31 +00003312 for (unsigned i = 0; i < Layout.size(); ++i) {
3313 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003314
John McCallea1471e2010-05-20 01:18:31 +00003315 QualType FieldType = E->getType();
3316 IdentifierInfo *FieldName = 0;
3317 if (isa<CXXThisExpr>(E)) {
3318 FieldName = &Idents.get("this");
3319 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3320 const ValueDecl *D = BDRE->getDecl();
3321 FieldName = D->getIdentifier();
3322 if (BDRE->isByRef())
3323 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3324 } else {
3325 // Padding.
3326 assert(isa<ConstantArrayType>(FieldType) &&
3327 isa<DeclRefExpr>(E) &&
3328 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3329 "doesn't match characteristics of padding decl");
3330 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003331
3332 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003333 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003334 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003335 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003336 T->addDecl(Field);
3337 }
3338
Douglas Gregor838db382010-02-11 01:19:42 +00003339 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003340
3341 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003342}
3343
Douglas Gregor319ac892009-04-23 22:29:11 +00003344void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003345 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003346 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3347 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3348}
3349
Anders Carlssone8c49532007-10-29 06:33:42 +00003350// This returns true if a type has been typedefed to BOOL:
3351// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003352static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003353 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003354 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3355 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003357 return false;
3358}
3359
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003360/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003361/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003362CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003363 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003364
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003365 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003366 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003367 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003368 // Treat arrays as pointers, since that's how they're passed in.
3369 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003370 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003371 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003372}
3373
3374static inline
3375std::string charUnitsToString(const CharUnits &CU) {
3376 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003377}
3378
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003379/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003380/// declaration.
3381void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3382 std::string& S) {
3383 const BlockDecl *Decl = Expr->getBlockDecl();
3384 QualType BlockTy =
3385 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3386 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003387 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003388 // Compute size of all parameters.
3389 // Start with computing size of a pointer in number of bytes.
3390 // FIXME: There might(should) be a better way of doing this computation!
3391 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003392 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3393 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003394 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003395 E = Decl->param_end(); PI != E; ++PI) {
3396 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003397 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003398 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003399 ParmOffset += sz;
3400 }
3401 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003402 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003403 // Block pointer and offset.
3404 S += "@?0";
3405 ParmOffset = PtrSize;
3406
3407 // Argument types.
3408 ParmOffset = PtrSize;
3409 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3410 Decl->param_end(); PI != E; ++PI) {
3411 ParmVarDecl *PVDecl = *PI;
3412 QualType PType = PVDecl->getOriginalType();
3413 if (const ArrayType *AT =
3414 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3415 // Use array's original type only if it has known number of
3416 // elements.
3417 if (!isa<ConstantArrayType>(AT))
3418 PType = PVDecl->getType();
3419 } else if (PType->isFunctionType())
3420 PType = PVDecl->getType();
3421 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003422 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003423 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003424 }
3425}
3426
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003427/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003428/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003429void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003430 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003431 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003432 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003433 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003434 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003435 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003436 // Compute size of all parameters.
3437 // Start with computing size of a pointer in number of bytes.
3438 // FIXME: There might(should) be a better way of doing this computation!
3439 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003440 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003441 // The first two arguments (self and _cmd) are pointers; account for
3442 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003443 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003444 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003445 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003446 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003447 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003448 assert (sz.isPositive() &&
3449 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003450 ParmOffset += sz;
3451 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003452 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003453 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003454 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003455
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003456 // Argument types.
3457 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003458 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003459 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003460 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003461 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003462 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003463 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3464 // Use array's original type only if it has known number of
3465 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003466 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003467 PType = PVDecl->getType();
3468 } else if (PType->isFunctionType())
3469 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003470 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003471 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003472 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003473 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003474 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003475 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003476 }
3477}
3478
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003479/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003480/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003481/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3482/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003483/// Property attributes are stored as a comma-delimited C string. The simple
3484/// attributes readonly and bycopy are encoded as single characters. The
3485/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3486/// encoded as single characters, followed by an identifier. Property types
3487/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003488/// these attributes are defined by the following enumeration:
3489/// @code
3490/// enum PropertyAttributes {
3491/// kPropertyReadOnly = 'R', // property is read-only.
3492/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3493/// kPropertyByref = '&', // property is a reference to the value last assigned
3494/// kPropertyDynamic = 'D', // property is dynamic
3495/// kPropertyGetter = 'G', // followed by getter selector name
3496/// kPropertySetter = 'S', // followed by setter selector name
3497/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3498/// kPropertyType = 't' // followed by old-style type encoding.
3499/// kPropertyWeak = 'W' // 'weak' property
3500/// kPropertyStrong = 'P' // property GC'able
3501/// kPropertyNonAtomic = 'N' // property non-atomic
3502/// };
3503/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003504void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003505 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003506 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003507 // Collect information from the property implementation decl(s).
3508 bool Dynamic = false;
3509 ObjCPropertyImplDecl *SynthesizePID = 0;
3510
3511 // FIXME: Duplicated code due to poor abstraction.
3512 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003513 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003514 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3515 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003516 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003517 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003518 ObjCPropertyImplDecl *PID = *i;
3519 if (PID->getPropertyDecl() == PD) {
3520 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3521 Dynamic = true;
3522 } else {
3523 SynthesizePID = PID;
3524 }
3525 }
3526 }
3527 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003528 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003529 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003530 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003531 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003532 ObjCPropertyImplDecl *PID = *i;
3533 if (PID->getPropertyDecl() == PD) {
3534 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3535 Dynamic = true;
3536 } else {
3537 SynthesizePID = PID;
3538 }
3539 }
Mike Stump1eb44332009-09-09 15:08:12 +00003540 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003541 }
3542 }
3543
3544 // FIXME: This is not very efficient.
3545 S = "T";
3546
3547 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003548 // GCC has some special rules regarding encoding of properties which
3549 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003550 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003551 true /* outermost type */,
3552 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003553
3554 if (PD->isReadOnly()) {
3555 S += ",R";
3556 } else {
3557 switch (PD->getSetterKind()) {
3558 case ObjCPropertyDecl::Assign: break;
3559 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003560 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003561 }
3562 }
3563
3564 // It really isn't clear at all what this means, since properties
3565 // are "dynamic by default".
3566 if (Dynamic)
3567 S += ",D";
3568
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003569 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3570 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003571
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003572 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3573 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003574 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003575 }
3576
3577 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3578 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003579 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003580 }
3581
3582 if (SynthesizePID) {
3583 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3584 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003585 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003586 }
3587
3588 // FIXME: OBJCGC: weak & strong
3589}
3590
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003591/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003592/// Another legacy compatibility encoding: 32-bit longs are encoded as
3593/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003594/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3595///
3596void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003597 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003598 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003599 if (BT->getKind() == BuiltinType::ULong &&
3600 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003601 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003602 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003603 if (BT->getKind() == BuiltinType::Long &&
3604 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003605 PointeeTy = IntTy;
3606 }
3607 }
3608}
3609
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003610void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003611 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003612 // We follow the behavior of gcc, expanding structures which are
3613 // directly pointed to, and expanding embedded structures. Note that
3614 // these rules are sufficient to prevent recursive encoding of the
3615 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003616 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003617 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003618}
3619
David Chisnall64fd7e82010-06-04 01:10:52 +00003620static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3621 switch (T->getAs<BuiltinType>()->getKind()) {
3622 default: assert(0 && "Unhandled builtin type kind");
3623 case BuiltinType::Void: return 'v';
3624 case BuiltinType::Bool: return 'B';
3625 case BuiltinType::Char_U:
3626 case BuiltinType::UChar: return 'C';
3627 case BuiltinType::UShort: return 'S';
3628 case BuiltinType::UInt: return 'I';
3629 case BuiltinType::ULong:
3630 return
3631 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3632 case BuiltinType::UInt128: return 'T';
3633 case BuiltinType::ULongLong: return 'Q';
3634 case BuiltinType::Char_S:
3635 case BuiltinType::SChar: return 'c';
3636 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003637 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003638 case BuiltinType::Int: return 'i';
3639 case BuiltinType::Long:
3640 return
3641 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3642 case BuiltinType::LongLong: return 'q';
3643 case BuiltinType::Int128: return 't';
3644 case BuiltinType::Float: return 'f';
3645 case BuiltinType::Double: return 'd';
3646 case BuiltinType::LongDouble: return 'd';
3647 }
3648}
3649
Mike Stump1eb44332009-09-09 15:08:12 +00003650static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003651 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003652 const Expr *E = FD->getBitWidth();
3653 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3654 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003655 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003656 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3657 // The GNU runtime requires more information; bitfields are encoded as b,
3658 // then the offset (in bits) of the first element, then the type of the
3659 // bitfield, then the size in bits. For example, in this structure:
3660 //
3661 // struct
3662 // {
3663 // int integer;
3664 // int flags:2;
3665 // };
3666 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3667 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3668 // information is not especially sensible, but we're stuck with it for
3669 // compatibility with GCC, although providing it breaks anything that
3670 // actually uses runtime introspection and wants to work on both runtimes...
3671 if (!Ctx->getLangOptions().NeXTRuntime) {
3672 const RecordDecl *RD = FD->getParent();
3673 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3674 // FIXME: This same linear search is also used in ExprConstant - it might
3675 // be better if the FieldDecl stored its offset. We'd be increasing the
3676 // size of the object slightly, but saving some time every time it is used.
3677 unsigned i = 0;
3678 for (RecordDecl::field_iterator Field = RD->field_begin(),
3679 FieldEnd = RD->field_end();
3680 Field != FieldEnd; (void)++Field, ++i) {
3681 if (*Field == FD)
3682 break;
3683 }
3684 S += llvm::utostr(RL.getFieldOffset(i));
3685 S += ObjCEncodingForPrimitiveKind(Context, T);
3686 }
3687 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003688 S += llvm::utostr(N);
3689}
3690
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003691// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003692void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3693 bool ExpandPointedToStructures,
3694 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003695 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003696 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003697 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003698 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003699 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003700 return EncodeBitField(this, S, T, FD);
3701 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003702 return;
3703 }
Mike Stump1eb44332009-09-09 15:08:12 +00003704
John McCall183700f2009-09-21 23:43:11 +00003705 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003706 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003707 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003708 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003709 return;
3710 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003711
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003712 // encoding for pointer or r3eference types.
3713 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003714 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003715 if (PT->isObjCSelType()) {
3716 S += ':';
3717 return;
3718 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003719 PointeeTy = PT->getPointeeType();
3720 }
3721 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3722 PointeeTy = RT->getPointeeType();
3723 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003724 bool isReadOnly = false;
3725 // For historical/compatibility reasons, the read-only qualifier of the
3726 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3727 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003728 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003729 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003730 if (OutermostType && T.isConstQualified()) {
3731 isReadOnly = true;
3732 S += 'r';
3733 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003734 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003735 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003736 while (P->getAs<PointerType>())
3737 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003738 if (P.isConstQualified()) {
3739 isReadOnly = true;
3740 S += 'r';
3741 }
3742 }
3743 if (isReadOnly) {
3744 // Another legacy compatibility encoding. Some ObjC qualifier and type
3745 // combinations need to be rearranged.
3746 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003747 if (llvm::StringRef(S).endswith("nr"))
3748 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003749 }
Mike Stump1eb44332009-09-09 15:08:12 +00003750
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003751 if (PointeeTy->isCharType()) {
3752 // char pointer types should be encoded as '*' unless it is a
3753 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003754 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003755 S += '*';
3756 return;
3757 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003758 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003759 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3760 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3761 S += '#';
3762 return;
3763 }
3764 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3765 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3766 S += '@';
3767 return;
3768 }
3769 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003770 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003771 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003772 getLegacyIntegralTypeEncoding(PointeeTy);
3773
Mike Stump1eb44332009-09-09 15:08:12 +00003774 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003775 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003776 return;
3777 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003778
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003779 if (const ArrayType *AT =
3780 // Ignore type qualifiers etc.
3781 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003782 if (isa<IncompleteArrayType>(AT)) {
3783 // Incomplete arrays are encoded as a pointer to the array element.
3784 S += '^';
3785
Mike Stump1eb44332009-09-09 15:08:12 +00003786 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003787 false, ExpandStructures, FD);
3788 } else {
3789 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003790
Anders Carlsson559a8332009-02-22 01:38:57 +00003791 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3792 S += llvm::utostr(CAT->getSize().getZExtValue());
3793 else {
3794 //Variable length arrays are encoded as a regular array with 0 elements.
3795 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3796 S += '0';
3797 }
Mike Stump1eb44332009-09-09 15:08:12 +00003798
3799 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003800 false, ExpandStructures, FD);
3801 S += ']';
3802 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003803 return;
3804 }
Mike Stump1eb44332009-09-09 15:08:12 +00003805
John McCall183700f2009-09-21 23:43:11 +00003806 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003807 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003808 return;
3809 }
Mike Stump1eb44332009-09-09 15:08:12 +00003810
Ted Kremenek6217b802009-07-29 21:53:49 +00003811 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003812 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003813 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003814 // Anonymous structures print as '?'
3815 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3816 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003817 if (ClassTemplateSpecializationDecl *Spec
3818 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3819 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3820 std::string TemplateArgsStr
3821 = TemplateSpecializationType::PrintTemplateArgumentList(
3822 TemplateArgs.getFlatArgumentList(),
3823 TemplateArgs.flat_size(),
3824 (*this).PrintingPolicy);
3825
3826 S += TemplateArgsStr;
3827 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003828 } else {
3829 S += '?';
3830 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003831 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003832 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003833 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3834 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003835 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003836 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003837 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003838 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003839 S += '"';
3840 }
Mike Stump1eb44332009-09-09 15:08:12 +00003841
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003842 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003843 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003844 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003845 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003846 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003847 QualType qt = Field->getType();
3848 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003849 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003850 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003851 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003852 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003853 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003854 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003855 return;
3856 }
Mike Stump1eb44332009-09-09 15:08:12 +00003857
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003858 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003859 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003860 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003861 else
3862 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003863 return;
3864 }
Mike Stump1eb44332009-09-09 15:08:12 +00003865
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003866 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003867 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003868 return;
3869 }
Mike Stump1eb44332009-09-09 15:08:12 +00003870
John McCallc12c5bb2010-05-15 11:32:37 +00003871 // Ignore protocol qualifiers when mangling at this level.
3872 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3873 T = OT->getBaseType();
3874
John McCall0953e762009-09-24 19:53:00 +00003875 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003876 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003877 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003878 S += '{';
3879 const IdentifierInfo *II = OI->getIdentifier();
3880 S += II->getName();
3881 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003882 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003883 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003884 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003885 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003886 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003887 RecFields[i]);
3888 else
Mike Stump1eb44332009-09-09 15:08:12 +00003889 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003890 FD);
3891 }
3892 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003893 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003894 }
Mike Stump1eb44332009-09-09 15:08:12 +00003895
John McCall183700f2009-09-21 23:43:11 +00003896 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003897 if (OPT->isObjCIdType()) {
3898 S += '@';
3899 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003900 }
Mike Stump1eb44332009-09-09 15:08:12 +00003901
Steve Naroff27d20a22009-10-28 22:03:49 +00003902 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3903 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3904 // Since this is a binary compatibility issue, need to consult with runtime
3905 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003906 S += '#';
3907 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003908 }
Mike Stump1eb44332009-09-09 15:08:12 +00003909
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003910 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003911 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003912 ExpandPointedToStructures,
3913 ExpandStructures, FD);
3914 if (FD || EncodingProperty) {
3915 // Note that we do extended encoding of protocol qualifer list
3916 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003917 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003918 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3919 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003920 S += '<';
3921 S += (*I)->getNameAsString();
3922 S += '>';
3923 }
3924 S += '"';
3925 }
3926 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003927 }
Mike Stump1eb44332009-09-09 15:08:12 +00003928
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003929 QualType PointeeTy = OPT->getPointeeType();
3930 if (!EncodingProperty &&
3931 isa<TypedefType>(PointeeTy.getTypePtr())) {
3932 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003933 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003934 // {...};
3935 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003936 getObjCEncodingForTypeImpl(PointeeTy, S,
3937 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003938 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003939 return;
3940 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003941
3942 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003943 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003944 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003945 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003946 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3947 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003948 S += '<';
3949 S += (*I)->getNameAsString();
3950 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003951 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003952 S += '"';
3953 }
3954 return;
3955 }
Mike Stump1eb44332009-09-09 15:08:12 +00003956
John McCall532ec7b2010-05-17 23:56:34 +00003957 // gcc just blithely ignores member pointers.
3958 // TODO: maybe there should be a mangling for these
3959 if (T->getAs<MemberPointerType>())
3960 return;
3961
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003962 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003963}
3964
Mike Stump1eb44332009-09-09 15:08:12 +00003965void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003966 std::string& S) const {
3967 if (QT & Decl::OBJC_TQ_In)
3968 S += 'n';
3969 if (QT & Decl::OBJC_TQ_Inout)
3970 S += 'N';
3971 if (QT & Decl::OBJC_TQ_Out)
3972 S += 'o';
3973 if (QT & Decl::OBJC_TQ_Bycopy)
3974 S += 'O';
3975 if (QT & Decl::OBJC_TQ_Byref)
3976 S += 'R';
3977 if (QT & Decl::OBJC_TQ_Oneway)
3978 S += 'V';
3979}
3980
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003981void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003982 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003983
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003984 BuiltinVaListType = T;
3985}
3986
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003987void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003988 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003989}
3990
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003991void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003992 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003993}
3994
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003995void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003996 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003997}
3998
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003999void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004000 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004001}
4002
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004003void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004004 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004005 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004006
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004007 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004008}
4009
John McCall0bd6feb2009-12-02 08:04:21 +00004010/// \brief Retrieve the template name that corresponds to a non-empty
4011/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00004012TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4013 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00004014 unsigned size = End - Begin;
4015 assert(size > 1 && "set is not overloaded!");
4016
4017 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4018 size * sizeof(FunctionTemplateDecl*));
4019 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4020
4021 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004022 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004023 NamedDecl *D = *I;
4024 assert(isa<FunctionTemplateDecl>(D) ||
4025 (isa<UsingShadowDecl>(D) &&
4026 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4027 *Storage++ = D;
4028 }
4029
4030 return TemplateName(OT);
4031}
4032
Douglas Gregor7532dc62009-03-30 22:58:21 +00004033/// \brief Retrieve the template name that represents a qualified
4034/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00004035TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004036 bool TemplateKeyword,
4037 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004038 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004039 llvm::FoldingSetNodeID ID;
4040 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4041
4042 void *InsertPos = 0;
4043 QualifiedTemplateName *QTN =
4044 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4045 if (!QTN) {
4046 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4047 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4048 }
4049
4050 return TemplateName(QTN);
4051}
4052
4053/// \brief Retrieve the template name that represents a dependent
4054/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00004055TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004056 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004057 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004058 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004059
4060 llvm::FoldingSetNodeID ID;
4061 DependentTemplateName::Profile(ID, NNS, Name);
4062
4063 void *InsertPos = 0;
4064 DependentTemplateName *QTN =
4065 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4066
4067 if (QTN)
4068 return TemplateName(QTN);
4069
4070 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4071 if (CanonNNS == NNS) {
4072 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4073 } else {
4074 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4075 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004076 DependentTemplateName *CheckQTN =
4077 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4078 assert(!CheckQTN && "Dependent type name canonicalization broken");
4079 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004080 }
4081
4082 DependentTemplateNames.InsertNode(QTN, InsertPos);
4083 return TemplateName(QTN);
4084}
4085
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004086/// \brief Retrieve the template name that represents a dependent
4087/// template name such as \c MetaFun::template operator+.
4088TemplateName
4089ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4090 OverloadedOperatorKind Operator) {
4091 assert((!NNS || NNS->isDependent()) &&
4092 "Nested name specifier must be dependent");
4093
4094 llvm::FoldingSetNodeID ID;
4095 DependentTemplateName::Profile(ID, NNS, Operator);
4096
4097 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004098 DependentTemplateName *QTN
4099 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004100
4101 if (QTN)
4102 return TemplateName(QTN);
4103
4104 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4105 if (CanonNNS == NNS) {
4106 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4107 } else {
4108 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4109 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004110
4111 DependentTemplateName *CheckQTN
4112 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4113 assert(!CheckQTN && "Dependent template name canonicalization broken");
4114 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004115 }
4116
4117 DependentTemplateNames.InsertNode(QTN, InsertPos);
4118 return TemplateName(QTN);
4119}
4120
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004121/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004122/// TargetInfo, produce the corresponding type. The unsigned @p Type
4123/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004124CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004125 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004126 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004127 case TargetInfo::SignedShort: return ShortTy;
4128 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4129 case TargetInfo::SignedInt: return IntTy;
4130 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4131 case TargetInfo::SignedLong: return LongTy;
4132 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4133 case TargetInfo::SignedLongLong: return LongLongTy;
4134 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4135 }
4136
4137 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004138 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004139}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004140
4141//===----------------------------------------------------------------------===//
4142// Type Predicates.
4143//===----------------------------------------------------------------------===//
4144
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004145/// isObjCNSObjectType - Return true if this is an NSObject object using
4146/// NSObject attribute on a c-style pointer type.
4147/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004148/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004149///
4150bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4151 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4152 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004153 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004154 return true;
4155 }
Mike Stump1eb44332009-09-09 15:08:12 +00004156 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004157}
4158
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004159/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4160/// garbage collection attribute.
4161///
John McCall0953e762009-09-24 19:53:00 +00004162Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4163 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004164 if (getLangOptions().ObjC1 &&
4165 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004166 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004167 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004168 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004169 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004170 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004171 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004172 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004173 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004174 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004175 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004176 // Non-pointers have none gc'able attribute regardless of the attribute
4177 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004178 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004179 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004180 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004181 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004182}
4183
Chris Lattner6ac46a42008-04-07 06:51:04 +00004184//===----------------------------------------------------------------------===//
4185// Type Compatibility Testing
4186//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004187
Mike Stump1eb44332009-09-09 15:08:12 +00004188/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004189/// compatible.
4190static bool areCompatVectorTypes(const VectorType *LHS,
4191 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004192 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004193 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004194 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004195}
4196
Steve Naroff4084c302009-07-23 01:01:38 +00004197//===----------------------------------------------------------------------===//
4198// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4199//===----------------------------------------------------------------------===//
4200
4201/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4202/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004203bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4204 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004205 if (lProto == rProto)
4206 return true;
4207 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4208 E = rProto->protocol_end(); PI != E; ++PI)
4209 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4210 return true;
4211 return false;
4212}
4213
Steve Naroff4084c302009-07-23 01:01:38 +00004214/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4215/// return true if lhs's protocols conform to rhs's protocol; false
4216/// otherwise.
4217bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4218 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4219 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4220 return false;
4221}
4222
4223/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4224/// ObjCQualifiedIDType.
4225bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4226 bool compare) {
4227 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004228 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004229 lhs->isObjCIdType() || lhs->isObjCClassType())
4230 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004231 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004232 rhs->isObjCIdType() || rhs->isObjCClassType())
4233 return true;
4234
4235 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004236 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004237
Steve Naroff4084c302009-07-23 01:01:38 +00004238 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004239
Steve Naroff4084c302009-07-23 01:01:38 +00004240 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004241 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004242 // make sure we check the class hierarchy.
4243 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4244 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4245 E = lhsQID->qual_end(); I != E; ++I) {
4246 // when comparing an id<P> on lhs with a static type on rhs,
4247 // see if static class implements all of id's protocols, directly or
4248 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004249 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004250 return false;
4251 }
4252 }
4253 // If there are no qualifiers and no interface, we have an 'id'.
4254 return true;
4255 }
Mike Stump1eb44332009-09-09 15:08:12 +00004256 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004257 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4258 E = lhsQID->qual_end(); I != E; ++I) {
4259 ObjCProtocolDecl *lhsProto = *I;
4260 bool match = false;
4261
4262 // when comparing an id<P> on lhs with a static type on rhs,
4263 // see if static class implements all of id's protocols, directly or
4264 // through its super class and categories.
4265 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4266 E = rhsOPT->qual_end(); J != E; ++J) {
4267 ObjCProtocolDecl *rhsProto = *J;
4268 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4269 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4270 match = true;
4271 break;
4272 }
4273 }
Mike Stump1eb44332009-09-09 15:08:12 +00004274 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004275 // make sure we check the class hierarchy.
4276 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4277 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4278 E = lhsQID->qual_end(); I != E; ++I) {
4279 // when comparing an id<P> on lhs with a static type on rhs,
4280 // see if static class implements all of id's protocols, directly or
4281 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004282 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004283 match = true;
4284 break;
4285 }
4286 }
4287 }
4288 if (!match)
4289 return false;
4290 }
Mike Stump1eb44332009-09-09 15:08:12 +00004291
Steve Naroff4084c302009-07-23 01:01:38 +00004292 return true;
4293 }
Mike Stump1eb44332009-09-09 15:08:12 +00004294
Steve Naroff4084c302009-07-23 01:01:38 +00004295 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4296 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4297
Mike Stump1eb44332009-09-09 15:08:12 +00004298 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004299 lhs->getAsObjCInterfacePointerType()) {
4300 if (lhsOPT->qual_empty()) {
4301 bool match = false;
4302 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4303 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4304 E = rhsQID->qual_end(); I != E; ++I) {
4305 // when comparing an id<P> on lhs with a static type on rhs,
4306 // see if static class implements all of id's protocols, directly or
4307 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004308 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004309 match = true;
4310 break;
4311 }
4312 }
4313 if (!match)
4314 return false;
4315 }
4316 return true;
4317 }
Mike Stump1eb44332009-09-09 15:08:12 +00004318 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004319 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4320 E = lhsOPT->qual_end(); I != E; ++I) {
4321 ObjCProtocolDecl *lhsProto = *I;
4322 bool match = false;
4323
4324 // when comparing an id<P> on lhs with a static type on rhs,
4325 // see if static class implements all of id's protocols, directly or
4326 // through its super class and categories.
4327 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4328 E = rhsQID->qual_end(); J != E; ++J) {
4329 ObjCProtocolDecl *rhsProto = *J;
4330 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4331 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4332 match = true;
4333 break;
4334 }
4335 }
4336 if (!match)
4337 return false;
4338 }
4339 return true;
4340 }
4341 return false;
4342}
4343
Eli Friedman3d815e72008-08-22 00:56:42 +00004344/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004345/// compatible for assignment from RHS to LHS. This handles validation of any
4346/// protocol qualifiers on the LHS or RHS.
4347///
Steve Naroff14108da2009-07-10 23:34:53 +00004348bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4349 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004350 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4351 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4352
Steve Naroffde2e22d2009-07-15 18:40:39 +00004353 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004354 if (LHS->isObjCUnqualifiedIdOrClass() ||
4355 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004356 return true;
4357
John McCallc12c5bb2010-05-15 11:32:37 +00004358 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004359 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4360 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004361 false);
4362
John McCallc12c5bb2010-05-15 11:32:37 +00004363 // If we have 2 user-defined types, fall into that path.
4364 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004365 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004366
Steve Naroff4084c302009-07-23 01:01:38 +00004367 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004368}
4369
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004370/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4371/// for providing type-safty for objective-c pointers used to pass/return
4372/// arguments in block literals. When passed as arguments, passing 'A*' where
4373/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4374/// not OK. For the return type, the opposite is not OK.
4375bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4376 const ObjCObjectPointerType *LHSOPT,
4377 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004378 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004379 return true;
4380
4381 if (LHSOPT->isObjCBuiltinType()) {
4382 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4383 }
4384
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004385 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004386 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4387 QualType(RHSOPT,0),
4388 false);
4389
4390 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4391 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4392 if (LHS && RHS) { // We have 2 user-defined types.
4393 if (LHS != RHS) {
4394 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4395 return false;
4396 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4397 return true;
4398 }
4399 else
4400 return true;
4401 }
4402 return false;
4403}
4404
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004405/// getIntersectionOfProtocols - This routine finds the intersection of set
4406/// of protocols inherited from two distinct objective-c pointer objects.
4407/// It is used to build composite qualifier list of the composite type of
4408/// the conditional expression involving two objective-c pointer objects.
4409static
4410void getIntersectionOfProtocols(ASTContext &Context,
4411 const ObjCObjectPointerType *LHSOPT,
4412 const ObjCObjectPointerType *RHSOPT,
4413 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4414
John McCallc12c5bb2010-05-15 11:32:37 +00004415 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4416 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4417 assert(LHS->getInterface() && "LHS must have an interface base");
4418 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004419
4420 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4421 unsigned LHSNumProtocols = LHS->getNumProtocols();
4422 if (LHSNumProtocols > 0)
4423 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4424 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004425 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004426 Context.CollectInheritedProtocols(LHS->getInterface(),
4427 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004428 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4429 LHSInheritedProtocols.end());
4430 }
4431
4432 unsigned RHSNumProtocols = RHS->getNumProtocols();
4433 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004434 ObjCProtocolDecl **RHSProtocols =
4435 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004436 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4437 if (InheritedProtocolSet.count(RHSProtocols[i]))
4438 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4439 }
4440 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004441 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004442 Context.CollectInheritedProtocols(RHS->getInterface(),
4443 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004444 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4445 RHSInheritedProtocols.begin(),
4446 E = RHSInheritedProtocols.end(); I != E; ++I)
4447 if (InheritedProtocolSet.count((*I)))
4448 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004449 }
4450}
4451
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004452/// areCommonBaseCompatible - Returns common base class of the two classes if
4453/// one found. Note that this is O'2 algorithm. But it will be called as the
4454/// last type comparison in a ?-exp of ObjC pointer types before a
4455/// warning is issued. So, its invokation is extremely rare.
4456QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004457 const ObjCObjectPointerType *Lptr,
4458 const ObjCObjectPointerType *Rptr) {
4459 const ObjCObjectType *LHS = Lptr->getObjectType();
4460 const ObjCObjectType *RHS = Rptr->getObjectType();
4461 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4462 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4463 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004464 return QualType();
4465
John McCallc12c5bb2010-05-15 11:32:37 +00004466 while ((LDecl = LDecl->getSuperClass())) {
4467 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004468 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004469 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4470 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4471
4472 QualType Result = QualType(LHS, 0);
4473 if (!Protocols.empty())
4474 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4475 Result = getObjCObjectPointerType(Result);
4476 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004477 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004478 }
4479
4480 return QualType();
4481}
4482
John McCallc12c5bb2010-05-15 11:32:37 +00004483bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4484 const ObjCObjectType *RHS) {
4485 assert(LHS->getInterface() && "LHS is not an interface type");
4486 assert(RHS->getInterface() && "RHS is not an interface type");
4487
Chris Lattner6ac46a42008-04-07 06:51:04 +00004488 // Verify that the base decls are compatible: the RHS must be a subclass of
4489 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004490 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004491 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004492
Chris Lattner6ac46a42008-04-07 06:51:04 +00004493 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4494 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004495 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004496 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004497
Chris Lattner6ac46a42008-04-07 06:51:04 +00004498 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4499 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004500 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004501 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004502
John McCallc12c5bb2010-05-15 11:32:37 +00004503 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4504 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004505 LHSPI != LHSPE; LHSPI++) {
4506 bool RHSImplementsProtocol = false;
4507
4508 // If the RHS doesn't implement the protocol on the left, the types
4509 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004510 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4511 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004512 RHSPI != RHSPE; RHSPI++) {
4513 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004514 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004515 break;
4516 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004517 }
4518 // FIXME: For better diagnostics, consider passing back the protocol name.
4519 if (!RHSImplementsProtocol)
4520 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004521 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004522 // The RHS implements all protocols listed on the LHS.
4523 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004524}
4525
Steve Naroff389bf462009-02-12 17:52:19 +00004526bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4527 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004528 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4529 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004530
Steve Naroff14108da2009-07-10 23:34:53 +00004531 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004532 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004533
4534 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4535 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004536}
4537
Mike Stump1eb44332009-09-09 15:08:12 +00004538/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004539/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004540/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004541/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004542bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004543 if (getLangOptions().CPlusPlus)
4544 return hasSameType(LHS, RHS);
4545
Eli Friedman3d815e72008-08-22 00:56:42 +00004546 return !mergeTypes(LHS, RHS).isNull();
4547}
4548
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004549bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4550 return !mergeTypes(LHS, RHS, true).isNull();
4551}
4552
4553QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4554 bool OfBlockPointer) {
John McCall183700f2009-09-21 23:43:11 +00004555 const FunctionType *lbase = lhs->getAs<FunctionType>();
4556 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004557 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4558 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004559 bool allLTypes = true;
4560 bool allRTypes = true;
4561
4562 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004563 QualType retType;
4564 if (OfBlockPointer)
4565 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4566 else
4567 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman3d815e72008-08-22 00:56:42 +00004568 if (retType.isNull()) return QualType();
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004569 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004570 allLTypes = false;
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004571 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004572 allRTypes = false;
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004573 // FIXME: double check this
4574 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4575 // rbase->getRegParmAttr() != 0 &&
4576 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004577 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4578 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004579 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4580 lbaseInfo.getRegParm();
4581 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4582 if (NoReturn != lbaseInfo.getNoReturn() ||
4583 RegParm != lbaseInfo.getRegParm())
4584 allLTypes = false;
4585 if (NoReturn != rbaseInfo.getNoReturn() ||
4586 RegParm != rbaseInfo.getRegParm())
4587 allRTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004588 CallingConv lcc = lbaseInfo.getCC();
4589 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004590 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004591 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004592 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004593
Eli Friedman3d815e72008-08-22 00:56:42 +00004594 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004595 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4596 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004597 unsigned lproto_nargs = lproto->getNumArgs();
4598 unsigned rproto_nargs = rproto->getNumArgs();
4599
4600 // Compatible functions must have the same number of arguments
4601 if (lproto_nargs != rproto_nargs)
4602 return QualType();
4603
4604 // Variadic and non-variadic functions aren't compatible
4605 if (lproto->isVariadic() != rproto->isVariadic())
4606 return QualType();
4607
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004608 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4609 return QualType();
4610
Eli Friedman3d815e72008-08-22 00:56:42 +00004611 // Check argument compatibility
4612 llvm::SmallVector<QualType, 10> types;
4613 for (unsigned i = 0; i < lproto_nargs; i++) {
4614 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4615 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004616 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman3d815e72008-08-22 00:56:42 +00004617 if (argtype.isNull()) return QualType();
4618 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004619 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4620 allLTypes = false;
4621 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4622 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004623 }
4624 if (allLTypes) return lhs;
4625 if (allRTypes) return rhs;
4626 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004627 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004628 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004629 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004630 }
4631
4632 if (lproto) allRTypes = false;
4633 if (rproto) allLTypes = false;
4634
Douglas Gregor72564e72009-02-26 23:50:07 +00004635 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004636 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004637 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004638 if (proto->isVariadic()) return QualType();
4639 // Check that the types are compatible with the types that
4640 // would result from default argument promotions (C99 6.7.5.3p15).
4641 // The only types actually affected are promotable integer
4642 // types and floats, which would be passed as a different
4643 // type depending on whether the prototype is visible.
4644 unsigned proto_nargs = proto->getNumArgs();
4645 for (unsigned i = 0; i < proto_nargs; ++i) {
4646 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004647
4648 // Look at the promotion type of enum types, since that is the type used
4649 // to pass enum values.
4650 if (const EnumType *Enum = argTy->getAs<EnumType>())
4651 argTy = Enum->getDecl()->getPromotionType();
4652
Eli Friedman3d815e72008-08-22 00:56:42 +00004653 if (argTy->isPromotableIntegerType() ||
4654 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4655 return QualType();
4656 }
4657
4658 if (allLTypes) return lhs;
4659 if (allRTypes) return rhs;
4660 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004661 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004662 proto->getTypeQuals(),
4663 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004664 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004665 }
4666
4667 if (allLTypes) return lhs;
4668 if (allRTypes) return rhs;
Rafael Espindola425ef722010-03-30 22:15:11 +00004669 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindola264ba482010-03-30 20:24:48 +00004670 return getFunctionNoProtoType(retType, Info);
Eli Friedman3d815e72008-08-22 00:56:42 +00004671}
4672
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004673QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4674 bool OfBlockPointer) {
Bill Wendling43d69752007-12-03 07:33:35 +00004675 // C++ [expr]: If an expression initially has the type "reference to T", the
4676 // type is adjusted to "T" prior to any further analysis, the expression
4677 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004678 // expression is an lvalue unless the reference is an rvalue reference and
4679 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004680 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4681 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4682
Eli Friedman3d815e72008-08-22 00:56:42 +00004683 QualType LHSCan = getCanonicalType(LHS),
4684 RHSCan = getCanonicalType(RHS);
4685
4686 // If two types are identical, they are compatible.
4687 if (LHSCan == RHSCan)
4688 return LHS;
4689
John McCall0953e762009-09-24 19:53:00 +00004690 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004691 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4692 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004693 if (LQuals != RQuals) {
4694 // If any of these qualifiers are different, we have a type
4695 // mismatch.
4696 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4697 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4698 return QualType();
4699
4700 // Exactly one GC qualifier difference is allowed: __strong is
4701 // okay if the other type has no GC qualifier but is an Objective
4702 // C object pointer (i.e. implicitly strong by default). We fix
4703 // this by pretending that the unqualified type was actually
4704 // qualified __strong.
4705 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4706 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4707 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4708
4709 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4710 return QualType();
4711
4712 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4713 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4714 }
4715 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4716 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4717 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004718 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004719 }
4720
4721 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004722
Eli Friedman852d63b2009-06-01 01:22:52 +00004723 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4724 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004725
Chris Lattner1adb8832008-01-14 05:45:46 +00004726 // We want to consider the two function types to be the same for these
4727 // comparisons, just force one to the other.
4728 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4729 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004730
4731 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004732 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4733 LHSClass = Type::ConstantArray;
4734 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4735 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004736
John McCallc12c5bb2010-05-15 11:32:37 +00004737 // ObjCInterfaces are just specialized ObjCObjects.
4738 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4739 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4740
Nate Begeman213541a2008-04-18 23:10:10 +00004741 // Canonicalize ExtVector -> Vector.
4742 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4743 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004744
Chris Lattnera36a61f2008-04-07 05:43:21 +00004745 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004746 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004747 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004748 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004749 // Compatibility is based on the underlying type, not the promotion
4750 // type.
John McCall183700f2009-09-21 23:43:11 +00004751 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004752 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4753 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004754 }
John McCall183700f2009-09-21 23:43:11 +00004755 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004756 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4757 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004758 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004759
Eli Friedman3d815e72008-08-22 00:56:42 +00004760 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004761 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004762
Steve Naroff4a746782008-01-09 22:43:08 +00004763 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004764 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004765#define TYPE(Class, Base)
4766#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004767#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004768#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4769#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4770#include "clang/AST/TypeNodes.def"
4771 assert(false && "Non-canonical and dependent types shouldn't get here");
4772 return QualType();
4773
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004774 case Type::LValueReference:
4775 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004776 case Type::MemberPointer:
4777 assert(false && "C++ should never be in mergeTypes");
4778 return QualType();
4779
John McCallc12c5bb2010-05-15 11:32:37 +00004780 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00004781 case Type::IncompleteArray:
4782 case Type::VariableArray:
4783 case Type::FunctionProto:
4784 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004785 assert(false && "Types are eliminated above");
4786 return QualType();
4787
Chris Lattner1adb8832008-01-14 05:45:46 +00004788 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004789 {
4790 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004791 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4792 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004793 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4794 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004795 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004796 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004797 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004798 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004799 return getPointerType(ResultType);
4800 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004801 case Type::BlockPointer:
4802 {
4803 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004804 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4805 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004806 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroffc0febd52008-12-10 17:49:55 +00004807 if (ResultType.isNull()) return QualType();
4808 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4809 return LHS;
4810 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4811 return RHS;
4812 return getBlockPointerType(ResultType);
4813 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004814 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004815 {
4816 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4817 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4818 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4819 return QualType();
4820
4821 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4822 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4823 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4824 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004825 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4826 return LHS;
4827 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4828 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004829 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4830 ArrayType::ArraySizeModifier(), 0);
4831 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4832 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004833 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4834 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004835 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4836 return LHS;
4837 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4838 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004839 if (LVAT) {
4840 // FIXME: This isn't correct! But tricky to implement because
4841 // the array's size has to be the size of LHS, but the type
4842 // has to be different.
4843 return LHS;
4844 }
4845 if (RVAT) {
4846 // FIXME: This isn't correct! But tricky to implement because
4847 // the array's size has to be the size of RHS, but the type
4848 // has to be different.
4849 return RHS;
4850 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004851 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4852 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004853 return getIncompleteArrayType(ResultType,
4854 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004855 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004856 case Type::FunctionNoProto:
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004857 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregor72564e72009-02-26 23:50:07 +00004858 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004859 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004860 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004861 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004862 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004863 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004864 case Type::Complex:
4865 // Distinct complex types are incompatible.
4866 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004867 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004868 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00004869 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4870 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004871 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004872 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00004873 case Type::ObjCObject: {
4874 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004875 // FIXME: This should be type compatibility, e.g. whether
4876 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00004877 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4878 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4879 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00004880 return LHS;
4881
Eli Friedman3d815e72008-08-22 00:56:42 +00004882 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004883 }
Steve Naroff14108da2009-07-10 23:34:53 +00004884 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004885 if (OfBlockPointer) {
4886 if (canAssignObjCInterfacesInBlockPointer(
4887 LHS->getAs<ObjCObjectPointerType>(),
4888 RHS->getAs<ObjCObjectPointerType>()))
4889 return LHS;
4890 return QualType();
4891 }
John McCall183700f2009-09-21 23:43:11 +00004892 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4893 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004894 return LHS;
4895
Steve Naroffbc76dd02008-12-10 22:14:21 +00004896 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004897 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004898 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004899
4900 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004901}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004902
Fariborz Jahanian2390a722010-05-19 21:37:30 +00004903/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4904/// 'RHS' attributes and returns the merged version; including for function
4905/// return types.
4906QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4907 QualType LHSCan = getCanonicalType(LHS),
4908 RHSCan = getCanonicalType(RHS);
4909 // If two types are identical, they are compatible.
4910 if (LHSCan == RHSCan)
4911 return LHS;
4912 if (RHSCan->isFunctionType()) {
4913 if (!LHSCan->isFunctionType())
4914 return QualType();
4915 QualType OldReturnType =
4916 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4917 QualType NewReturnType =
4918 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4919 QualType ResReturnType =
4920 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4921 if (ResReturnType.isNull())
4922 return QualType();
4923 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4924 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4925 // In either case, use OldReturnType to build the new function type.
4926 const FunctionType *F = LHS->getAs<FunctionType>();
4927 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4928 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4929 QualType ResultType
4930 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4931 FPT->getNumArgs(), FPT->isVariadic(),
4932 FPT->getTypeQuals(),
4933 FPT->hasExceptionSpec(),
4934 FPT->hasAnyExceptionSpec(),
4935 FPT->getNumExceptions(),
4936 FPT->exception_begin(),
4937 Info);
4938 return ResultType;
4939 }
4940 }
4941 return QualType();
4942 }
4943
4944 // If the qualifiers are different, the types can still be merged.
4945 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4946 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4947 if (LQuals != RQuals) {
4948 // If any of these qualifiers are different, we have a type mismatch.
4949 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4950 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4951 return QualType();
4952
4953 // Exactly one GC qualifier difference is allowed: __strong is
4954 // okay if the other type has no GC qualifier but is an Objective
4955 // C object pointer (i.e. implicitly strong by default). We fix
4956 // this by pretending that the unqualified type was actually
4957 // qualified __strong.
4958 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4959 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4960 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4961
4962 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4963 return QualType();
4964
4965 if (GC_L == Qualifiers::Strong)
4966 return LHS;
4967 if (GC_R == Qualifiers::Strong)
4968 return RHS;
4969 return QualType();
4970 }
4971
4972 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4973 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4974 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4975 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4976 if (ResQT == LHSBaseQT)
4977 return LHS;
4978 if (ResQT == RHSBaseQT)
4979 return RHS;
4980 }
4981 return QualType();
4982}
4983
Chris Lattner5426bf62008-04-07 07:01:58 +00004984//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004985// Integer Predicates
4986//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004987
Eli Friedmanad74a752008-06-28 06:23:08 +00004988unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004989 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004990 return 1;
John McCall842aef82009-12-09 09:09:27 +00004991 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004992 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004993 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004994 return (unsigned)getTypeSize(T);
4995}
4996
4997QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4998 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004999
5000 // Turn <4 x signed int> -> <4 x unsigned int>
5001 if (const VectorType *VTy = T->getAs<VectorType>())
5002 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner788b0fd2010-06-23 06:00:24 +00005003 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005004
5005 // For enums, we return the unsigned version of the base type.
5006 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005007 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005008
5009 const BuiltinType *BTy = T->getAs<BuiltinType>();
5010 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005011 switch (BTy->getKind()) {
5012 case BuiltinType::Char_S:
5013 case BuiltinType::SChar:
5014 return UnsignedCharTy;
5015 case BuiltinType::Short:
5016 return UnsignedShortTy;
5017 case BuiltinType::Int:
5018 return UnsignedIntTy;
5019 case BuiltinType::Long:
5020 return UnsignedLongTy;
5021 case BuiltinType::LongLong:
5022 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005023 case BuiltinType::Int128:
5024 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005025 default:
5026 assert(0 && "Unexpected signed integer type");
5027 return QualType();
5028 }
5029}
5030
Douglas Gregor2cf26342009-04-09 22:27:44 +00005031ExternalASTSource::~ExternalASTSource() { }
5032
5033void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005034
5035
5036//===----------------------------------------------------------------------===//
5037// Builtin Type Computation
5038//===----------------------------------------------------------------------===//
5039
5040/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5041/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00005042static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005043 ASTContext::GetBuiltinTypeError &Error,
5044 bool AllowTypeModifiers = true) {
5045 // Modifiers.
5046 int HowLong = 0;
5047 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005048
Chris Lattner86df27b2009-06-14 00:45:47 +00005049 // Read the modifiers first.
5050 bool Done = false;
5051 while (!Done) {
5052 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005053 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005054 case 'S':
5055 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5056 assert(!Signed && "Can't use 'S' modifier multiple times!");
5057 Signed = true;
5058 break;
5059 case 'U':
5060 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5061 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5062 Unsigned = true;
5063 break;
5064 case 'L':
5065 assert(HowLong <= 2 && "Can't have LLLL modifier");
5066 ++HowLong;
5067 break;
5068 }
5069 }
5070
5071 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005072
Chris Lattner86df27b2009-06-14 00:45:47 +00005073 // Read the base type.
5074 switch (*Str++) {
5075 default: assert(0 && "Unknown builtin type letter!");
5076 case 'v':
5077 assert(HowLong == 0 && !Signed && !Unsigned &&
5078 "Bad modifiers used with 'v'!");
5079 Type = Context.VoidTy;
5080 break;
5081 case 'f':
5082 assert(HowLong == 0 && !Signed && !Unsigned &&
5083 "Bad modifiers used with 'f'!");
5084 Type = Context.FloatTy;
5085 break;
5086 case 'd':
5087 assert(HowLong < 2 && !Signed && !Unsigned &&
5088 "Bad modifiers used with 'd'!");
5089 if (HowLong)
5090 Type = Context.LongDoubleTy;
5091 else
5092 Type = Context.DoubleTy;
5093 break;
5094 case 's':
5095 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5096 if (Unsigned)
5097 Type = Context.UnsignedShortTy;
5098 else
5099 Type = Context.ShortTy;
5100 break;
5101 case 'i':
5102 if (HowLong == 3)
5103 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5104 else if (HowLong == 2)
5105 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5106 else if (HowLong == 1)
5107 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5108 else
5109 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5110 break;
5111 case 'c':
5112 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5113 if (Signed)
5114 Type = Context.SignedCharTy;
5115 else if (Unsigned)
5116 Type = Context.UnsignedCharTy;
5117 else
5118 Type = Context.CharTy;
5119 break;
5120 case 'b': // boolean
5121 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5122 Type = Context.BoolTy;
5123 break;
5124 case 'z': // size_t.
5125 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5126 Type = Context.getSizeType();
5127 break;
5128 case 'F':
5129 Type = Context.getCFConstantStringType();
5130 break;
5131 case 'a':
5132 Type = Context.getBuiltinVaListType();
5133 assert(!Type.isNull() && "builtin va list type not initialized!");
5134 break;
5135 case 'A':
5136 // This is a "reference" to a va_list; however, what exactly
5137 // this means depends on how va_list is defined. There are two
5138 // different kinds of va_list: ones passed by value, and ones
5139 // passed by reference. An example of a by-value va_list is
5140 // x86, where va_list is a char*. An example of by-ref va_list
5141 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5142 // we want this argument to be a char*&; for x86-64, we want
5143 // it to be a __va_list_tag*.
5144 Type = Context.getBuiltinVaListType();
5145 assert(!Type.isNull() && "builtin va list type not initialized!");
5146 if (Type->isArrayType()) {
5147 Type = Context.getArrayDecayedType(Type);
5148 } else {
5149 Type = Context.getLValueReferenceType(Type);
5150 }
5151 break;
5152 case 'V': {
5153 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005154 unsigned NumElements = strtoul(Str, &End, 10);
5155 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00005156
Chris Lattner86df27b2009-06-14 00:45:47 +00005157 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005158
Chris Lattner86df27b2009-06-14 00:45:47 +00005159 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00005160 // FIXME: Don't know what to do about AltiVec.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005161 Type = Context.getVectorType(ElementType, NumElements,
5162 VectorType::NotAltiVec);
Chris Lattner86df27b2009-06-14 00:45:47 +00005163 break;
5164 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005165 case 'X': {
5166 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5167 Type = Context.getComplexType(ElementType);
5168 break;
5169 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005170 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005171 Type = Context.getFILEType();
5172 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005173 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005174 return QualType();
5175 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005176 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005177 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005178 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005179 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005180 else
5181 Type = Context.getjmp_bufType();
5182
Mike Stumpfd612db2009-07-28 23:47:15 +00005183 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005184 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005185 return QualType();
5186 }
5187 break;
Mike Stump782fa302009-07-28 02:25:19 +00005188 }
Mike Stump1eb44332009-09-09 15:08:12 +00005189
Chris Lattner86df27b2009-06-14 00:45:47 +00005190 if (!AllowTypeModifiers)
5191 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005192
Chris Lattner86df27b2009-06-14 00:45:47 +00005193 Done = false;
5194 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005195 switch (char c = *Str++) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005196 default: Done = true; --Str; break;
5197 case '*':
Chris Lattner86df27b2009-06-14 00:45:47 +00005198 case '&':
John McCall187ab372010-03-12 04:21:28 +00005199 {
5200 // Both pointers and references can have their pointee types
5201 // qualified with an address space.
5202 char *End;
5203 unsigned AddrSpace = strtoul(Str, &End, 10);
5204 if (End != Str && AddrSpace != 0) {
5205 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5206 Str = End;
5207 }
5208 }
5209 if (c == '*')
5210 Type = Context.getPointerType(Type);
5211 else
5212 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005213 break;
5214 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5215 case 'C':
John McCall0953e762009-09-24 19:53:00 +00005216 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00005217 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00005218 case 'D':
5219 Type = Context.getVolatileType(Type);
5220 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005221 }
5222 }
Mike Stump1eb44332009-09-09 15:08:12 +00005223
Chris Lattner86df27b2009-06-14 00:45:47 +00005224 return Type;
5225}
5226
5227/// GetBuiltinType - Return the type for the specified builtin.
5228QualType ASTContext::GetBuiltinType(unsigned id,
5229 GetBuiltinTypeError &Error) {
5230 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005231
Chris Lattner86df27b2009-06-14 00:45:47 +00005232 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005233
Chris Lattner86df27b2009-06-14 00:45:47 +00005234 Error = GE_None;
5235 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5236 if (Error != GE_None)
5237 return QualType();
5238 while (TypeStr[0] && TypeStr[0] != '.') {
5239 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5240 if (Error != GE_None)
5241 return QualType();
5242
5243 // Do array -> pointer decay. The builtin should use the decayed type.
5244 if (Ty->isArrayType())
5245 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005246
Chris Lattner86df27b2009-06-14 00:45:47 +00005247 ArgTypes.push_back(Ty);
5248 }
5249
5250 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5251 "'.' should only occur at end of builtin type list!");
5252
5253 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5254 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5255 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005256
5257 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005258 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005259 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00005260 FunctionType::ExtInfo());
Chris Lattner86df27b2009-06-14 00:45:47 +00005261}
Eli Friedmana95d7572009-08-19 07:44:53 +00005262
5263QualType
5264ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5265 // Perform the usual unary conversions. We do this early so that
5266 // integral promotions to "int" can allow us to exit early, in the
5267 // lhs == rhs check. Also, for conversion purposes, we ignore any
5268 // qualifiers. For example, "const float" and "float" are
5269 // equivalent.
5270 if (lhs->isPromotableIntegerType())
5271 lhs = getPromotedIntegerType(lhs);
5272 else
5273 lhs = lhs.getUnqualifiedType();
5274 if (rhs->isPromotableIntegerType())
5275 rhs = getPromotedIntegerType(rhs);
5276 else
5277 rhs = rhs.getUnqualifiedType();
5278
5279 // If both types are identical, no conversion is needed.
5280 if (lhs == rhs)
5281 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005282
Eli Friedmana95d7572009-08-19 07:44:53 +00005283 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5284 // The caller can deal with this (e.g. pointer + int).
5285 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5286 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005287
5288 // At this point, we have two different arithmetic types.
5289
Eli Friedmana95d7572009-08-19 07:44:53 +00005290 // Handle complex types first (C99 6.3.1.8p1).
5291 if (lhs->isComplexType() || rhs->isComplexType()) {
5292 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005293 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005294 // convert the rhs to the lhs complex type.
5295 return lhs;
5296 }
Mike Stump1eb44332009-09-09 15:08:12 +00005297 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005298 // convert the lhs to the rhs complex type.
5299 return rhs;
5300 }
5301 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005302 // When both operands are complex, the shorter operand is converted to the
5303 // type of the longer, and that is the type of the result. This corresponds
5304 // to what is done when combining two real floating-point operands.
5305 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005306 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005307 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005308 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005309 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005310 // "double _Complex" is promoted to "long double _Complex".
5311 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005312
5313 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005314 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005315 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005316 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005317 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005318 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5319 // domains match. This is a requirement for our implementation, C99
5320 // does not require this promotion.
5321 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5322 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5323 return rhs;
5324 } else { // handle "_Complex double, double".
5325 return lhs;
5326 }
5327 }
5328 return lhs; // The domain/size match exactly.
5329 }
5330 // Now handle "real" floating types (i.e. float, double, long double).
5331 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5332 // if we have an integer operand, the result is the real floating type.
5333 if (rhs->isIntegerType()) {
5334 // convert rhs to the lhs floating point type.
5335 return lhs;
5336 }
5337 if (rhs->isComplexIntegerType()) {
5338 // convert rhs to the complex floating point type.
5339 return getComplexType(lhs);
5340 }
5341 if (lhs->isIntegerType()) {
5342 // convert lhs to the rhs floating point type.
5343 return rhs;
5344 }
Mike Stump1eb44332009-09-09 15:08:12 +00005345 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005346 // convert lhs to the complex floating point type.
5347 return getComplexType(rhs);
5348 }
5349 // We have two real floating types, float/complex combos were handled above.
5350 // Convert the smaller operand to the bigger result.
5351 int result = getFloatingTypeOrder(lhs, rhs);
5352 if (result > 0) // convert the rhs
5353 return lhs;
5354 assert(result < 0 && "illegal float comparison");
5355 return rhs; // convert the lhs
5356 }
5357 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5358 // Handle GCC complex int extension.
5359 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5360 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5361
5362 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005363 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005364 rhsComplexInt->getElementType()) >= 0)
5365 return lhs; // convert the rhs
5366 return rhs;
5367 } else if (lhsComplexInt && rhs->isIntegerType()) {
5368 // convert the rhs to the lhs complex type.
5369 return lhs;
5370 } else if (rhsComplexInt && lhs->isIntegerType()) {
5371 // convert the lhs to the rhs complex type.
5372 return rhs;
5373 }
5374 }
5375 // Finally, we have two differing integer types.
5376 // The rules for this case are in C99 6.3.1.8
5377 int compare = getIntegerTypeOrder(lhs, rhs);
5378 bool lhsSigned = lhs->isSignedIntegerType(),
5379 rhsSigned = rhs->isSignedIntegerType();
5380 QualType destType;
5381 if (lhsSigned == rhsSigned) {
5382 // Same signedness; use the higher-ranked type
5383 destType = compare >= 0 ? lhs : rhs;
5384 } else if (compare != (lhsSigned ? 1 : -1)) {
5385 // The unsigned type has greater than or equal rank to the
5386 // signed type, so use the unsigned type
5387 destType = lhsSigned ? rhs : lhs;
5388 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5389 // The two types are different widths; if we are here, that
5390 // means the signed type is larger than the unsigned type, so
5391 // use the signed type.
5392 destType = lhsSigned ? lhs : rhs;
5393 } else {
5394 // The signed type is higher-ranked than the unsigned type,
5395 // but isn't actually any bigger (like unsigned int and long
5396 // on most 32-bit systems). Use the unsigned type corresponding
5397 // to the signed type.
5398 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5399 }
5400 return destType;
5401}