blob: 03e91f101ed78b823640b3981f27f5efe937568e [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 Gregored8abf12010-07-08 06:14:04 +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 Gregor34724302010-07-07 16:40:34 +0000278 if (!FreeMemory)
279 BumpAlloc.PrintStats();
280
Douglas Gregor2cf26342009-04-09 22:27:44 +0000281 if (ExternalSource.get()) {
282 fprintf(stderr, "\n");
283 ExternalSource->PrintStats();
284 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000285
286 if (!FreeMemory)
287 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000288}
289
290
John McCalle27ec8a2009-10-23 23:03:21 +0000291void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000292 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000293 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000294 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000295}
296
Reid Spencer5f016e22007-07-11 17:01:13 +0000297void ASTContext::InitBuiltinTypes() {
298 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 // C99 6.2.5p19.
301 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 // C99 6.2.5p2.
304 InitBuiltinType(BoolTy, BuiltinType::Bool);
305 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000306 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 InitBuiltinType(CharTy, BuiltinType::Char_S);
308 else
309 InitBuiltinType(CharTy, BuiltinType::Char_U);
310 // C99 6.2.5p4.
311 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
312 InitBuiltinType(ShortTy, BuiltinType::Short);
313 InitBuiltinType(IntTy, BuiltinType::Int);
314 InitBuiltinType(LongTy, BuiltinType::Long);
315 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 // C99 6.2.5p6.
318 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
319 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
320 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
321 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
322 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 // C99 6.2.5p10.
325 InitBuiltinType(FloatTy, BuiltinType::Float);
326 InitBuiltinType(DoubleTy, BuiltinType::Double);
327 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000328
Chris Lattner2df9ced2009-04-30 02:43:43 +0000329 // GNU extension, 128-bit integers.
330 InitBuiltinType(Int128Ty, BuiltinType::Int128);
331 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
332
Chris Lattner3a250322009-02-26 23:43:47 +0000333 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
334 InitBuiltinType(WCharTy, BuiltinType::WChar);
335 else // C99
336 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000337
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000338 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
339 InitBuiltinType(Char16Ty, BuiltinType::Char16);
340 else // C99
341 Char16Ty = getFromTargetType(Target.getChar16Type());
342
343 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
344 InitBuiltinType(Char32Ty, BuiltinType::Char32);
345 else // C99
346 Char32Ty = getFromTargetType(Target.getChar32Type());
347
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000348 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000349 InitBuiltinType(OverloadTy, BuiltinType::Overload);
350
351 // Placeholder type for type-dependent expressions whose type is
352 // completely unknown. No code should ever check a type against
353 // DependentTy and users should never see it; however, it is here to
354 // help diagnose failures to properly check for type-dependent
355 // expressions.
356 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000357
Mike Stump1eb44332009-09-09 15:08:12 +0000358 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000359 // not yet been deduced.
360 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 // C99 6.2.5p11.
363 FloatComplexTy = getComplexType(FloatTy);
364 DoubleComplexTy = getComplexType(DoubleTy);
365 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000366
Steve Naroff7e219e42007-10-15 14:41:52 +0000367 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Steve Naroffde2e22d2009-07-15 18:40:39 +0000369 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
370 ObjCIdTypedefType = QualType();
371 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000372 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000374 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000375 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
376 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000377 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000378
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000379 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000381 // void * type
382 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000383
384 // nullptr type (C++0x 2.14.7)
385 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000386}
387
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000388MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000389ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000390 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000391 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000392 = InstantiatedFromStaticDataMember.find(Var);
393 if (Pos == InstantiatedFromStaticDataMember.end())
394 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Douglas Gregor7caa6822009-07-24 20:34:43 +0000396 return Pos->second;
397}
398
Mike Stump1eb44332009-09-09 15:08:12 +0000399void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000400ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000401 TemplateSpecializationKind TSK,
402 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000403 assert(Inst->isStaticDataMember() && "Not a static data member");
404 assert(Tmpl->isStaticDataMember() && "Not a static data member");
405 assert(!InstantiatedFromStaticDataMember[Inst] &&
406 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000407 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000408 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000409}
410
John McCall7ba107a2009-11-18 02:36:19 +0000411NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000412ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000413 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000414 = InstantiatedFromUsingDecl.find(UUD);
415 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000416 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Anders Carlsson0d8df782009-08-29 19:37:28 +0000418 return Pos->second;
419}
420
421void
John McCalled976492009-12-04 22:46:56 +0000422ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
423 assert((isa<UsingDecl>(Pattern) ||
424 isa<UnresolvedUsingValueDecl>(Pattern) ||
425 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
426 "pattern decl is not a using decl");
427 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
428 InstantiatedFromUsingDecl[Inst] = Pattern;
429}
430
431UsingShadowDecl *
432ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
433 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
434 = InstantiatedFromUsingShadowDecl.find(Inst);
435 if (Pos == InstantiatedFromUsingShadowDecl.end())
436 return 0;
437
438 return Pos->second;
439}
440
441void
442ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
443 UsingShadowDecl *Pattern) {
444 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
445 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000446}
447
Anders Carlssond8b285f2009-09-01 04:26:58 +0000448FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
449 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
450 = InstantiatedFromUnnamedFieldDecl.find(Field);
451 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
452 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Anders Carlssond8b285f2009-09-01 04:26:58 +0000454 return Pos->second;
455}
456
457void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
458 FieldDecl *Tmpl) {
459 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
460 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
461 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
462 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Anders Carlssond8b285f2009-09-01 04:26:58 +0000464 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
465}
466
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000467ASTContext::overridden_cxx_method_iterator
468ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
469 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
470 = OverriddenMethods.find(Method);
471 if (Pos == OverriddenMethods.end())
472 return 0;
473
474 return Pos->second.begin();
475}
476
477ASTContext::overridden_cxx_method_iterator
478ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
479 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
480 = OverriddenMethods.find(Method);
481 if (Pos == OverriddenMethods.end())
482 return 0;
483
484 return Pos->second.end();
485}
486
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000487unsigned
488ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
489 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
490 = OverriddenMethods.find(Method);
491 if (Pos == OverriddenMethods.end())
492 return 0;
493
494 return Pos->second.size();
495}
496
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000497void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
498 const CXXMethodDecl *Overridden) {
499 OverriddenMethods[Method].push_back(Overridden);
500}
501
Douglas Gregor2e222532009-07-02 17:08:52 +0000502namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000503 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000504 : std::binary_function<SourceRange, SourceRange, bool> {
505 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Douglas Gregor2e222532009-07-02 17:08:52 +0000507 public:
508 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Douglas Gregor2e222532009-07-02 17:08:52 +0000510 bool operator()(SourceRange X, SourceRange Y) {
511 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
512 }
513 };
514}
515
Chris Lattner464175b2007-07-18 17:52:12 +0000516//===----------------------------------------------------------------------===//
517// Type Sizing and Analysis
518//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000519
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000520/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
521/// scalar floating point type.
522const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000523 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000524 assert(BT && "Not a floating point type!");
525 switch (BT->getKind()) {
526 default: assert(0 && "Not a floating point type!");
527 case BuiltinType::Float: return Target.getFloatFormat();
528 case BuiltinType::Double: return Target.getDoubleFormat();
529 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
530 }
531}
532
Ken Dyck8b752f12010-01-27 17:10:57 +0000533/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000534/// specified decl. Note that bitfields do not have a valid alignment, so
535/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000536/// If @p RefAsPointee, references are treated like their underlying type
537/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000538CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000539 unsigned Align = Target.getCharWidth();
540
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000541 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000542 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000543
Chris Lattneraf707ab2009-01-24 21:53:27 +0000544 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
545 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000546 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000547 if (RefAsPointee)
548 T = RT->getPointeeType();
549 else
550 T = getPointerType(RT->getPointeeType());
551 }
552 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindola6deecb02010-06-04 23:15:27 +0000553 unsigned MinWidth = Target.getLargeArrayMinWidth();
554 unsigned ArrayAlign = Target.getLargeArrayAlign();
555 if (isa<VariableArrayType>(T) && MinWidth != 0)
556 Align = std::max(Align, ArrayAlign);
557 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
558 unsigned Size = getTypeSize(CT);
559 if (MinWidth != 0 && MinWidth <= Size)
560 Align = std::max(Align, ArrayAlign);
561 }
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000562 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000563 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
564 T = cast<ArrayType>(T)->getElementType();
565
566 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
567 }
Charles Davis05f62472010-02-23 04:52:00 +0000568 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
569 // In the case of a field in a packed struct, we want the minimum
570 // of the alignment of the field and the alignment of the struct.
571 Align = std::min(Align,
572 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
573 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000574 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000575
Ken Dyck8b752f12010-01-27 17:10:57 +0000576 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000577}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000578
John McCallea1471e2010-05-20 01:18:31 +0000579std::pair<CharUnits, CharUnits>
580ASTContext::getTypeInfoInChars(const Type *T) {
581 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
582 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
583 CharUnits::fromQuantity(Info.second / getCharWidth()));
584}
585
586std::pair<CharUnits, CharUnits>
587ASTContext::getTypeInfoInChars(QualType T) {
588 return getTypeInfoInChars(T.getTypePtr());
589}
590
Chris Lattnera7674d82007-07-13 22:13:22 +0000591/// getTypeSize - Return the size of the specified type, in bits. This method
592/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000593///
594/// FIXME: Pointers into different addr spaces could have different sizes and
595/// alignment requirements: getPointerInfo should take an AddrSpace, this
596/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000597std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000598ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000599 uint64_t Width=0;
600 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000601 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000602#define TYPE(Class, Base)
603#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000604#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000605#define DEPENDENT_TYPE(Class, Base) case Type::Class:
606#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000607 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000608 break;
609
Chris Lattner692233e2007-07-13 22:27:08 +0000610 case Type::FunctionNoProto:
611 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000612 // GCC extension: alignof(function) = 32 bits
613 Width = 0;
614 Align = 32;
615 break;
616
Douglas Gregor72564e72009-02-26 23:50:07 +0000617 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000618 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000619 Width = 0;
620 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
621 break;
622
Steve Narofffb22d962007-08-30 01:06:46 +0000623 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000624 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Chris Lattner98be4942008-03-05 18:54:05 +0000626 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000627 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000628 Align = EltInfo.second;
629 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000630 }
Nate Begeman213541a2008-04-18 23:10:10 +0000631 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000632 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000633 const VectorType *VT = cast<VectorType>(T);
634 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
635 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000636 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000637 // If the alignment is not a power of 2, round up to the next power of 2.
638 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000639 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000640 Align = llvm::NextPowerOf2(Align);
641 Width = llvm::RoundUpToAlignment(Width, Align);
642 }
Chris Lattner030d8842007-07-19 22:06:24 +0000643 break;
644 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000645
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000646 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000647 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000648 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000649 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000650 // GCC extension: alignof(void) = 8 bits.
651 Width = 0;
652 Align = 8;
653 break;
654
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000655 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000656 Width = Target.getBoolWidth();
657 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000658 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000659 case BuiltinType::Char_S:
660 case BuiltinType::Char_U:
661 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000662 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000663 Width = Target.getCharWidth();
664 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000665 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000666 case BuiltinType::WChar:
667 Width = Target.getWCharWidth();
668 Align = Target.getWCharAlign();
669 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000670 case BuiltinType::Char16:
671 Width = Target.getChar16Width();
672 Align = Target.getChar16Align();
673 break;
674 case BuiltinType::Char32:
675 Width = Target.getChar32Width();
676 Align = Target.getChar32Align();
677 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000678 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000679 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000680 Width = Target.getShortWidth();
681 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000682 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000683 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000684 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000685 Width = Target.getIntWidth();
686 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000687 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000688 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000689 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000690 Width = Target.getLongWidth();
691 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000692 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000693 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000694 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000695 Width = Target.getLongLongWidth();
696 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000697 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000698 case BuiltinType::Int128:
699 case BuiltinType::UInt128:
700 Width = 128;
701 Align = 128; // int128_t is 128-bit aligned on all targets.
702 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000703 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000704 Width = Target.getFloatWidth();
705 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000706 break;
707 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000708 Width = Target.getDoubleWidth();
709 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000710 break;
711 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000712 Width = Target.getLongDoubleWidth();
713 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000714 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000715 case BuiltinType::NullPtr:
716 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
717 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000718 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000719 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000720 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000721 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000722 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000723 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000724 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000725 case Type::BlockPointer: {
726 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
727 Width = Target.getPointerWidth(AS);
728 Align = Target.getPointerAlign(AS);
729 break;
730 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000731 case Type::LValueReference:
732 case Type::RValueReference: {
733 // alignof and sizeof should never enter this code path here, so we go
734 // the pointer route.
735 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
736 Width = Target.getPointerWidth(AS);
737 Align = Target.getPointerAlign(AS);
738 break;
739 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000740 case Type::Pointer: {
741 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000742 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000743 Align = Target.getPointerAlign(AS);
744 break;
745 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000746 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000747 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000748 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000749 getTypeInfo(getPointerDiffType());
750 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000751 if (Pointee->isFunctionType())
752 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000753 Align = PtrDiffInfo.second;
754 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000755 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000756 case Type::Complex: {
757 // Complex types have the same alignment as their elements, but twice the
758 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000759 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000760 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000761 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000762 Align = EltInfo.second;
763 break;
764 }
John McCallc12c5bb2010-05-15 11:32:37 +0000765 case Type::ObjCObject:
766 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000767 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000768 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000769 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
770 Width = Layout.getSize();
771 Align = Layout.getAlignment();
772 break;
773 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000774 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000775 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000776 const TagType *TT = cast<TagType>(T);
777
778 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000779 Width = 1;
780 Align = 1;
781 break;
782 }
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Daniel Dunbar1d751182008-11-08 05:48:37 +0000784 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000785 return getTypeInfo(ET->getDecl()->getIntegerType());
786
Daniel Dunbar1d751182008-11-08 05:48:37 +0000787 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000788 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
789 Width = Layout.getSize();
790 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000791 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000792 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000793
Chris Lattner9fcfe922009-10-22 05:17:15 +0000794 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000795 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
796 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000797
Douglas Gregor18857642009-04-30 17:32:17 +0000798 case Type::Typedef: {
799 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000800 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000801 Align = std::max(Aligned->getMaxAlignment(),
802 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000803 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
804 } else
805 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000806 break;
Chris Lattner71763312008-04-06 22:05:18 +0000807 }
Douglas Gregor18857642009-04-30 17:32:17 +0000808
809 case Type::TypeOfExpr:
810 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
811 .getTypePtr());
812
813 case Type::TypeOf:
814 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
815
Anders Carlsson395b4752009-06-24 19:06:50 +0000816 case Type::Decltype:
817 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
818 .getTypePtr());
819
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000820 case Type::Elaborated:
821 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Douglas Gregor18857642009-04-30 17:32:17 +0000823 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000824 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000825 "Cannot request the size of a dependent type");
826 // FIXME: this is likely to be wrong once we support template
827 // aliases, since a template alias could refer to a typedef that
828 // has an __aligned__ attribute on it.
829 return getTypeInfo(getCanonicalType(T));
830 }
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Chris Lattner464175b2007-07-18 17:52:12 +0000832 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000833 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000834}
835
Ken Dyckbdc601b2009-12-22 14:23:30 +0000836/// getTypeSizeInChars - Return the size of the specified type, in characters.
837/// This method does not work on incomplete types.
838CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000839 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000840}
841CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000842 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000843}
844
Ken Dyck16e20cc2010-01-26 17:25:18 +0000845/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000846/// characters. This method does not work on incomplete types.
847CharUnits ASTContext::getTypeAlignInChars(QualType T) {
848 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
849}
850CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
851 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
852}
853
Chris Lattner34ebde42009-01-27 18:08:34 +0000854/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
855/// type for the current target in bits. This can be different than the ABI
856/// alignment in cases where it is beneficial for performance to overalign
857/// a data type.
858unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
859 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000860
861 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000862 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000863 T = CT->getElementType().getTypePtr();
864 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
865 T->isSpecificBuiltinType(BuiltinType::LongLong))
866 return std::max(ABIAlign, (unsigned)getTypeSize(T));
867
Chris Lattner34ebde42009-01-27 18:08:34 +0000868 return ABIAlign;
869}
870
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000871static void CollectLocalObjCIvars(ASTContext *Ctx,
872 const ObjCInterfaceDecl *OI,
873 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000874 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
875 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000876 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000877 if (!IVDecl->isInvalidDecl())
878 Fields.push_back(cast<FieldDecl>(IVDecl));
879 }
880}
881
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000882void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
883 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
884 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
885 CollectObjCIvars(SuperClass, Fields);
886 CollectLocalObjCIvars(this, OI, Fields);
887}
888
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000889/// ShallowCollectObjCIvars -
890/// Collect all ivars, including those synthesized, in the current class.
891///
892void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000893 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000894 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
895 E = OI->ivar_end(); I != E; ++I) {
896 Ivars.push_back(*I);
897 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000898
899 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000900}
901
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000902/// CollectNonClassIvars -
903/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000904/// This includes synthesized ivars (via @synthesize) and those in
905// class's @implementation.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000906///
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000907void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000908 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000909 // Find ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000910 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
911 CDecl = CDecl->getNextClassExtension()) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000912 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
913 E = CDecl->ivar_end(); I != E; ++I) {
914 Ivars.push_back(*I);
915 }
916 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000917
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000918 // Also add any ivar defined in this class's implementation. This
919 // includes synthesized ivars.
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000920 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
921 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
922 E = ImplDecl->ivar_end(); I != E; ++I)
923 Ivars.push_back(*I);
924 }
Fariborz Jahanian98200742009-05-12 18:14:29 +0000925}
926
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000927/// CollectInheritedProtocols - Collect all protocols in current class and
928/// those inherited by it.
929void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000930 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000931 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
932 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
933 PE = OI->protocol_end(); P != PE; ++P) {
934 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000935 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000936 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000937 PE = Proto->protocol_end(); P != PE; ++P) {
938 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000939 CollectInheritedProtocols(*P, Protocols);
940 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000941 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000942
943 // Categories of this Interface.
944 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
945 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
946 CollectInheritedProtocols(CDeclChain, Protocols);
947 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
948 while (SD) {
949 CollectInheritedProtocols(SD, Protocols);
950 SD = SD->getSuperClass();
951 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000952 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000953 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
954 PE = OC->protocol_end(); P != PE; ++P) {
955 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000956 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000957 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
958 PE = Proto->protocol_end(); P != PE; ++P)
959 CollectInheritedProtocols(*P, Protocols);
960 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000961 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000962 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
963 PE = OP->protocol_end(); P != PE; ++P) {
964 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000965 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000966 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
967 PE = Proto->protocol_end(); P != PE; ++P)
968 CollectInheritedProtocols(*P, Protocols);
969 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000970 }
971}
972
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000973unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
974 unsigned count = 0;
975 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000976 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
977 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000978 count += CDecl->ivar_size();
979
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000980 // Count ivar defined in this class's implementation. This
981 // includes synthesized ivars.
982 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000983 count += ImplDecl->ivar_size();
984
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000985 return count;
986}
987
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000988/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
989ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
990 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
991 I = ObjCImpls.find(D);
992 if (I != ObjCImpls.end())
993 return cast<ObjCImplementationDecl>(I->second);
994 return 0;
995}
996/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
997ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
998 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
999 I = ObjCImpls.find(D);
1000 if (I != ObjCImpls.end())
1001 return cast<ObjCCategoryImplDecl>(I->second);
1002 return 0;
1003}
1004
1005/// \brief Set the implementation of ObjCInterfaceDecl.
1006void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1007 ObjCImplementationDecl *ImplD) {
1008 assert(IFaceD && ImplD && "Passed null params");
1009 ObjCImpls[IFaceD] = ImplD;
1010}
1011/// \brief Set the implementation of ObjCCategoryDecl.
1012void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1013 ObjCCategoryImplDecl *ImplD) {
1014 assert(CatD && ImplD && "Passed null params");
1015 ObjCImpls[CatD] = ImplD;
1016}
1017
John McCalla93c9342009-12-07 02:54:59 +00001018/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001019///
John McCalla93c9342009-12-07 02:54:59 +00001020/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001021/// the TypeLoc wrappers.
1022///
1023/// \param T the type that will be the basis for type source info. This type
1024/// should refer to how the declarator was written in source code, not to
1025/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001026TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001027 unsigned DataSize) {
1028 if (!DataSize)
1029 DataSize = TypeLoc::getFullDataSizeForType(T);
1030 else
1031 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001032 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001033
John McCalla93c9342009-12-07 02:54:59 +00001034 TypeSourceInfo *TInfo =
1035 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1036 new (TInfo) TypeSourceInfo(T);
1037 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001038}
1039
John McCalla93c9342009-12-07 02:54:59 +00001040TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001041 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001042 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001043 DI->getTypeLoc().initialize(L);
1044 return DI;
1045}
1046
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001047const ASTRecordLayout &
1048ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1049 return getObjCLayout(D, 0);
1050}
1051
1052const ASTRecordLayout &
1053ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1054 return getObjCLayout(D->getClassInterface(), D);
1055}
1056
Chris Lattnera7674d82007-07-13 22:13:22 +00001057//===----------------------------------------------------------------------===//
1058// Type creation/memoization methods
1059//===----------------------------------------------------------------------===//
1060
John McCall0953e762009-09-24 19:53:00 +00001061QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1062 unsigned Fast = Quals.getFastQualifiers();
1063 Quals.removeFastQualifiers();
1064
1065 // Check if we've already instantiated this type.
1066 llvm::FoldingSetNodeID ID;
1067 ExtQuals::Profile(ID, TypeNode, Quals);
1068 void *InsertPos = 0;
1069 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1070 assert(EQ->getQualifiers() == Quals);
1071 QualType T = QualType(EQ, Fast);
1072 return T;
1073 }
1074
John McCall6b304a02009-09-24 23:30:46 +00001075 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001076 ExtQualNodes.InsertNode(New, InsertPos);
1077 QualType T = QualType(New, Fast);
1078 return T;
1079}
1080
1081QualType ASTContext::getVolatileType(QualType T) {
1082 QualType CanT = getCanonicalType(T);
1083 if (CanT.isVolatileQualified()) return T;
1084
1085 QualifierCollector Quals;
1086 const Type *TypeNode = Quals.strip(T);
1087 Quals.addVolatile();
1088
1089 return getExtQualType(TypeNode, Quals);
1090}
1091
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001092QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001093 QualType CanT = getCanonicalType(T);
1094 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001095 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001096
John McCall0953e762009-09-24 19:53:00 +00001097 // If we are composing extended qualifiers together, merge together
1098 // into one ExtQuals node.
1099 QualifierCollector Quals;
1100 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001101
John McCall0953e762009-09-24 19:53:00 +00001102 // If this type already has an address space specified, it cannot get
1103 // another one.
1104 assert(!Quals.hasAddressSpace() &&
1105 "Type cannot be in multiple addr spaces!");
1106 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001107
John McCall0953e762009-09-24 19:53:00 +00001108 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001109}
1110
Chris Lattnerb7d25532009-02-18 22:53:11 +00001111QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001112 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001113 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001114 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001115 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001117 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001118 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001119 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001120 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1121 return getPointerType(ResultType);
1122 }
1123 }
Mike Stump1eb44332009-09-09 15:08:12 +00001124
John McCall0953e762009-09-24 19:53:00 +00001125 // If we are composing extended qualifiers together, merge together
1126 // into one ExtQuals node.
1127 QualifierCollector Quals;
1128 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001129
John McCall0953e762009-09-24 19:53:00 +00001130 // If this type already has an ObjCGC specified, it cannot get
1131 // another one.
1132 assert(!Quals.hasObjCGCAttr() &&
1133 "Type cannot have multiple ObjCGCs!");
1134 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001135
John McCall0953e762009-09-24 19:53:00 +00001136 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001137}
Chris Lattnera7674d82007-07-13 22:13:22 +00001138
Rafael Espindola264ba482010-03-30 20:24:48 +00001139static QualType getExtFunctionType(ASTContext& Context, QualType T,
1140 const FunctionType::ExtInfo &Info) {
John McCall0953e762009-09-24 19:53:00 +00001141 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001142 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1143 QualType Pointee = Pointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001144 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001145 if (ResultType == Pointee)
1146 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001147
1148 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001149 } else if (const BlockPointerType *BlockPointer
1150 = T->getAs<BlockPointerType>()) {
1151 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001152 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001153 if (ResultType == Pointee)
1154 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001155
1156 ResultType = Context.getBlockPointerType(ResultType);
1157 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001158 if (F->getExtInfo() == Info)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001159 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001160
Douglas Gregor43c79c22009-12-09 00:47:37 +00001161 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001162 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001163 Info);
John McCall0953e762009-09-24 19:53:00 +00001164 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001165 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001166 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001167 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1168 FPT->getNumArgs(), FPT->isVariadic(),
1169 FPT->getTypeQuals(),
1170 FPT->hasExceptionSpec(),
1171 FPT->hasAnyExceptionSpec(),
1172 FPT->getNumExceptions(),
1173 FPT->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001174 Info);
John McCall0953e762009-09-24 19:53:00 +00001175 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001176 } else
1177 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001178
1179 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1180}
1181
1182QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
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.withNoReturn(AddNoReturn));
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001186}
1187
1188QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola425ef722010-03-30 22:15:11 +00001189 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindola264ba482010-03-30 20:24:48 +00001190 return getExtFunctionType(*this, T,
1191 Info.withCallingConv(CallConv));
Mike Stump24556362009-07-25 21:26:53 +00001192}
1193
Rafael Espindola425ef722010-03-30 22:15:11 +00001194QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1195 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1196 return getExtFunctionType(*this, T,
1197 Info.withRegParm(RegParm));
1198}
1199
Reid Spencer5f016e22007-07-11 17:01:13 +00001200/// getComplexType - Return the uniqued reference to the type for a complex
1201/// number with the specified element type.
1202QualType ASTContext::getComplexType(QualType T) {
1203 // Unique pointers, to guarantee there is only one pointer of a particular
1204 // structure.
1205 llvm::FoldingSetNodeID ID;
1206 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 void *InsertPos = 0;
1209 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1210 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 // If the pointee type isn't canonical, this won't be a canonical type either,
1213 // so fill in the canonical type field.
1214 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001215 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001216 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 // Get the new insert position for the node we care about.
1219 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001220 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001221 }
John McCall6b304a02009-09-24 23:30:46 +00001222 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 Types.push_back(New);
1224 ComplexTypes.InsertNode(New, InsertPos);
1225 return QualType(New, 0);
1226}
1227
Reid Spencer5f016e22007-07-11 17:01:13 +00001228/// getPointerType - Return the uniqued reference to the type for a pointer to
1229/// the specified type.
1230QualType ASTContext::getPointerType(QualType T) {
1231 // Unique pointers, to guarantee there is only one pointer of a particular
1232 // structure.
1233 llvm::FoldingSetNodeID ID;
1234 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 void *InsertPos = 0;
1237 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1238 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 // If the pointee type isn't canonical, this won't be a canonical type either,
1241 // so fill in the canonical type field.
1242 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001243 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001244 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 // Get the new insert position for the node we care about.
1247 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001248 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 }
John McCall6b304a02009-09-24 23:30:46 +00001250 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 Types.push_back(New);
1252 PointerTypes.InsertNode(New, InsertPos);
1253 return QualType(New, 0);
1254}
1255
Mike Stump1eb44332009-09-09 15:08:12 +00001256/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001257/// a pointer to the specified block.
1258QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001259 assert(T->isFunctionType() && "block of function types only");
1260 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001261 // structure.
1262 llvm::FoldingSetNodeID ID;
1263 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001264
Steve Naroff5618bd42008-08-27 16:04:49 +00001265 void *InsertPos = 0;
1266 if (BlockPointerType *PT =
1267 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1268 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001269
1270 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001271 // type either so fill in the canonical type field.
1272 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001273 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001274 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Steve Naroff5618bd42008-08-27 16:04:49 +00001276 // Get the new insert position for the node we care about.
1277 BlockPointerType *NewIP =
1278 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001279 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001280 }
John McCall6b304a02009-09-24 23:30:46 +00001281 BlockPointerType *New
1282 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001283 Types.push_back(New);
1284 BlockPointerTypes.InsertNode(New, InsertPos);
1285 return QualType(New, 0);
1286}
1287
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001288/// getLValueReferenceType - Return the uniqued reference to the type for an
1289/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001290QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 // Unique pointers, to guarantee there is only one pointer of a particular
1292 // structure.
1293 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001294 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001295
1296 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001297 if (LValueReferenceType *RT =
1298 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001299 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001300
John McCall54e14c42009-10-22 22:37:11 +00001301 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1302
Reid Spencer5f016e22007-07-11 17:01:13 +00001303 // If the referencee type isn't canonical, this won't be a canonical type
1304 // either, so fill in the canonical type field.
1305 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001306 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1307 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1308 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001309
Reid Spencer5f016e22007-07-11 17:01:13 +00001310 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001311 LValueReferenceType *NewIP =
1312 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001313 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 }
1315
John McCall6b304a02009-09-24 23:30:46 +00001316 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001317 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1318 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001320 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001321
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001322 return QualType(New, 0);
1323}
1324
1325/// getRValueReferenceType - Return the uniqued reference to the type for an
1326/// rvalue reference to the specified type.
1327QualType ASTContext::getRValueReferenceType(QualType T) {
1328 // Unique pointers, to guarantee there is only one pointer of a particular
1329 // structure.
1330 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001331 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001332
1333 void *InsertPos = 0;
1334 if (RValueReferenceType *RT =
1335 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1336 return QualType(RT, 0);
1337
John McCall54e14c42009-10-22 22:37:11 +00001338 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1339
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001340 // If the referencee type isn't canonical, this won't be a canonical type
1341 // either, so fill in the canonical type field.
1342 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001343 if (InnerRef || !T.isCanonical()) {
1344 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1345 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001346
1347 // Get the new insert position for the node we care about.
1348 RValueReferenceType *NewIP =
1349 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1350 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1351 }
1352
John McCall6b304a02009-09-24 23:30:46 +00001353 RValueReferenceType *New
1354 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001355 Types.push_back(New);
1356 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 return QualType(New, 0);
1358}
1359
Sebastian Redlf30208a2009-01-24 21:16:55 +00001360/// getMemberPointerType - Return the uniqued reference to the type for a
1361/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001362QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001363 // Unique pointers, to guarantee there is only one pointer of a particular
1364 // structure.
1365 llvm::FoldingSetNodeID ID;
1366 MemberPointerType::Profile(ID, T, Cls);
1367
1368 void *InsertPos = 0;
1369 if (MemberPointerType *PT =
1370 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1371 return QualType(PT, 0);
1372
1373 // If the pointee or class type isn't canonical, this won't be a canonical
1374 // type either, so fill in the canonical type field.
1375 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001376 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001377 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1378
1379 // Get the new insert position for the node we care about.
1380 MemberPointerType *NewIP =
1381 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1382 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1383 }
John McCall6b304a02009-09-24 23:30:46 +00001384 MemberPointerType *New
1385 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001386 Types.push_back(New);
1387 MemberPointerTypes.InsertNode(New, InsertPos);
1388 return QualType(New, 0);
1389}
1390
Mike Stump1eb44332009-09-09 15:08:12 +00001391/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001392/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001393QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001394 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001395 ArrayType::ArraySizeModifier ASM,
1396 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001397 assert((EltTy->isDependentType() ||
1398 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001399 "Constant array of VLAs is illegal!");
1400
Chris Lattner38aeec72009-05-13 04:12:56 +00001401 // Convert the array size into a canonical width matching the pointer size for
1402 // the target.
1403 llvm::APInt ArySize(ArySizeIn);
1404 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001407 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001410 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001411 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 // If the element type isn't canonical, this won't be a canonical type either,
1415 // so fill in the canonical type field.
1416 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001417 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001418 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001419 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001420 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001421 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001422 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001423 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 }
Mike Stump1eb44332009-09-09 15:08:12 +00001425
John McCall6b304a02009-09-24 23:30:46 +00001426 ConstantArrayType *New = new(*this,TypeAlignment)
1427 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001428 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001429 Types.push_back(New);
1430 return QualType(New, 0);
1431}
1432
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001433/// getVariableArrayType - Returns a non-unique reference to the type for a
1434/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001435QualType ASTContext::getVariableArrayType(QualType EltTy,
1436 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001437 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001438 unsigned EltTypeQuals,
1439 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001440 // Since we don't unique expressions, it isn't possible to unique VLA's
1441 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001442 QualType CanonType;
1443
1444 if (!EltTy.isCanonical()) {
1445 if (NumElts)
1446 NumElts->Retain();
1447 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1448 EltTypeQuals, Brackets);
1449 }
1450
John McCall6b304a02009-09-24 23:30:46 +00001451 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001452 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001453
1454 VariableArrayTypes.push_back(New);
1455 Types.push_back(New);
1456 return QualType(New, 0);
1457}
1458
Douglas Gregor898574e2008-12-05 23:32:09 +00001459/// getDependentSizedArrayType - Returns a non-unique reference to
1460/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001461/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001462QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1463 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001464 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001465 unsigned EltTypeQuals,
1466 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001467 assert((!NumElts || NumElts->isTypeDependent() ||
1468 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001469 "Size must be type- or value-dependent!");
1470
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001471 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001472 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001473 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001474
1475 if (NumElts) {
1476 // Dependently-sized array types that do not have a specified
1477 // number of elements will have their sizes deduced from an
1478 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001479 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1480 EltTypeQuals, NumElts);
1481
1482 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1483 }
1484
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001485 DependentSizedArrayType *New;
1486 if (Canon) {
1487 // We already have a canonical version of this array type; use it as
1488 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001489 New = new (*this, TypeAlignment)
1490 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1491 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001492 } else {
1493 QualType CanonEltTy = getCanonicalType(EltTy);
1494 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001495 New = new (*this, TypeAlignment)
1496 DependentSizedArrayType(*this, EltTy, QualType(),
1497 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001498
Douglas Gregor789b1f62010-02-04 18:10:26 +00001499 if (NumElts) {
1500 DependentSizedArrayType *CanonCheck
1501 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1502 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1503 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001504 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001505 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001506 } else {
1507 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1508 ASM, EltTypeQuals,
1509 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001510 New = new (*this, TypeAlignment)
1511 DependentSizedArrayType(*this, EltTy, Canon,
1512 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001513 }
1514 }
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Douglas Gregor898574e2008-12-05 23:32:09 +00001516 Types.push_back(New);
1517 return QualType(New, 0);
1518}
1519
Eli Friedmanc5773c42008-02-15 18:16:39 +00001520QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1521 ArrayType::ArraySizeModifier ASM,
1522 unsigned EltTypeQuals) {
1523 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001524 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001525
1526 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001527 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001528 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1529 return QualType(ATP, 0);
1530
1531 // If the element type isn't canonical, this won't be a canonical type
1532 // either, so fill in the canonical type field.
1533 QualType Canonical;
1534
John McCall467b27b2009-10-22 20:10:53 +00001535 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001536 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001537 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001538
1539 // Get the new insert position for the node we care about.
1540 IncompleteArrayType *NewIP =
1541 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001542 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001543 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001544
John McCall6b304a02009-09-24 23:30:46 +00001545 IncompleteArrayType *New = new (*this, TypeAlignment)
1546 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001547
1548 IncompleteArrayTypes.InsertNode(New, InsertPos);
1549 Types.push_back(New);
1550 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001551}
1552
Steve Naroff73322922007-07-18 18:00:27 +00001553/// getVectorType - Return the unique reference to a vector type of
1554/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001555QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner788b0fd2010-06-23 06:00:24 +00001556 VectorType::AltiVecSpecific AltiVecSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Chris Lattnerf52ab252008-04-06 22:59:24 +00001559 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001560 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 // Check if we've already instantiated a vector of this type.
1563 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001564 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1565
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 void *InsertPos = 0;
1567 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1568 return QualType(VTP, 0);
1569
1570 // If the element type isn't canonical, this won't be a canonical type either,
1571 // so fill in the canonical type field.
1572 QualType Canonical;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001573 if (!vecType.isCanonical() || (AltiVecSpec == VectorType::AltiVec)) {
1574 // pass VectorType::NotAltiVec for AltiVecSpec to make AltiVec canonical
1575 // vector type (except 'vector bool ...' and 'vector Pixel') the same as
1576 // the equivalent GCC vector types
1577 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1578 VectorType::NotAltiVec);
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 // Get the new insert position for the node we care about.
1581 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001582 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 }
John McCall6b304a02009-09-24 23:30:46 +00001584 VectorType *New = new (*this, TypeAlignment)
Chris Lattner788b0fd2010-06-23 06:00:24 +00001585 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 VectorTypes.InsertNode(New, InsertPos);
1587 Types.push_back(New);
1588 return QualType(New, 0);
1589}
1590
Nate Begeman213541a2008-04-18 23:10:10 +00001591/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001592/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001593QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001594 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Chris Lattnerf52ab252008-04-06 22:59:24 +00001596 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001597 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001598
Steve Naroff73322922007-07-18 18:00:27 +00001599 // Check if we've already instantiated a vector of this type.
1600 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001601 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1602 VectorType::NotAltiVec);
Steve Naroff73322922007-07-18 18:00:27 +00001603 void *InsertPos = 0;
1604 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1605 return QualType(VTP, 0);
1606
1607 // If the element type isn't canonical, this won't be a canonical type either,
1608 // so fill in the canonical type field.
1609 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001610 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001611 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Steve Naroff73322922007-07-18 18:00:27 +00001613 // Get the new insert position for the node we care about.
1614 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001615 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001616 }
John McCall6b304a02009-09-24 23:30:46 +00001617 ExtVectorType *New = new (*this, TypeAlignment)
1618 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001619 VectorTypes.InsertNode(New, InsertPos);
1620 Types.push_back(New);
1621 return QualType(New, 0);
1622}
1623
Mike Stump1eb44332009-09-09 15:08:12 +00001624QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001625 Expr *SizeExpr,
1626 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001627 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001628 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001629 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001631 void *InsertPos = 0;
1632 DependentSizedExtVectorType *Canon
1633 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1634 DependentSizedExtVectorType *New;
1635 if (Canon) {
1636 // We already have a canonical version of this array type; use it as
1637 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001638 New = new (*this, TypeAlignment)
1639 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1640 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001641 } else {
1642 QualType CanonVecTy = getCanonicalType(vecType);
1643 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001644 New = new (*this, TypeAlignment)
1645 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1646 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001647
1648 DependentSizedExtVectorType *CanonCheck
1649 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1650 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1651 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001652 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1653 } else {
1654 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1655 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001656 New = new (*this, TypeAlignment)
1657 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001658 }
1659 }
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001661 Types.push_back(New);
1662 return QualType(New, 0);
1663}
1664
Douglas Gregor72564e72009-02-26 23:50:07 +00001665/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001666///
Rafael Espindola264ba482010-03-30 20:24:48 +00001667QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1668 const FunctionType::ExtInfo &Info) {
1669 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 // Unique functions, to guarantee there is only one function of a particular
1671 // structure.
1672 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001673 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001676 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001677 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001678 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001681 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001682 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001683 Canonical =
1684 getFunctionNoProtoType(getCanonicalType(ResultTy),
1685 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Reid Spencer5f016e22007-07-11 17:01:13 +00001687 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001688 FunctionNoProtoType *NewIP =
1689 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001690 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 }
Mike Stump1eb44332009-09-09 15:08:12 +00001692
John McCall6b304a02009-09-24 23:30:46 +00001693 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001694 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001695 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001696 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 return QualType(New, 0);
1698}
1699
1700/// getFunctionType - Return a normal function type with a typed argument
1701/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001702QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001703 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001704 unsigned TypeQuals, bool hasExceptionSpec,
1705 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001706 const QualType *ExArray,
1707 const FunctionType::ExtInfo &Info) {
1708 const CallingConv CallConv= Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001709 // Unique functions, to guarantee there is only one function of a particular
1710 // structure.
1711 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001712 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001713 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001714 NumExs, ExArray, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001715
1716 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001717 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001718 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001719 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001720
1721 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001722 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001724 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 isCanonical = false;
1726
1727 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001728 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001729 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001730 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 llvm::SmallVector<QualType, 16> CanonicalArgs;
1732 CanonicalArgs.reserve(NumArgs);
1733 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001734 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001735
Chris Lattnerf52ab252008-04-06 22:59:24 +00001736 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001737 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001738 isVariadic, TypeQuals, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00001739 false, 0, 0,
1740 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl465226e2009-05-27 22:11:52 +00001741
Reid Spencer5f016e22007-07-11 17:01:13 +00001742 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001743 FunctionProtoType *NewIP =
1744 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001745 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001746 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001747
Douglas Gregor72564e72009-02-26 23:50:07 +00001748 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001749 // for two variable size arrays (for parameter and exception types) at the
1750 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001751 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001752 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1753 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001754 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001755 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001756 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001757 ExArray, NumExs, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001759 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 return QualType(FTP, 0);
1761}
1762
John McCall3cb0ebd2010-03-10 03:28:59 +00001763#ifndef NDEBUG
1764static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1765 if (!isa<CXXRecordDecl>(D)) return false;
1766 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1767 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1768 return true;
1769 if (RD->getDescribedClassTemplate() &&
1770 !isa<ClassTemplateSpecializationDecl>(RD))
1771 return true;
1772 return false;
1773}
1774#endif
1775
1776/// getInjectedClassNameType - Return the unique reference to the
1777/// injected class name type for the specified templated declaration.
1778QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1779 QualType TST) {
1780 assert(NeedsInjectedClassNameType(Decl));
1781 if (Decl->TypeForDecl) {
1782 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001783 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001784 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1785 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1786 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1787 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001788 Decl->TypeForDecl =
1789 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001790 Types.push_back(Decl->TypeForDecl);
1791 }
1792 return QualType(Decl->TypeForDecl, 0);
1793}
1794
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001795/// getTypeDeclType - Return the unique reference to the type for the
1796/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001797QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001798 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001799 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001800
John McCall19c85762010-02-16 03:57:14 +00001801 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001802 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001803
John McCallbecb8d52010-03-10 06:48:02 +00001804 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1805 "Template type parameter types are always available.");
1806
John McCall19c85762010-02-16 03:57:14 +00001807 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001808 assert(!Record->getPreviousDeclaration() &&
1809 "struct/union has previous declaration");
1810 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001811 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001812 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001813 assert(!Enum->getPreviousDeclaration() &&
1814 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001815 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001816 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001817 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1818 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001819 } else
John McCallbecb8d52010-03-10 06:48:02 +00001820 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001821
John McCallbecb8d52010-03-10 06:48:02 +00001822 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001823 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001824}
1825
Reid Spencer5f016e22007-07-11 17:01:13 +00001826/// getTypedefType - Return the unique reference to the type for the
1827/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001828QualType
1829ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001830 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001832 if (Canonical.isNull())
1833 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001834 Decl->TypeForDecl = new(*this, TypeAlignment)
1835 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 Types.push_back(Decl->TypeForDecl);
1837 return QualType(Decl->TypeForDecl, 0);
1838}
1839
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001840QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1841 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1842
1843 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1844 if (PrevDecl->TypeForDecl)
1845 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1846
1847 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1848 Types.push_back(Decl->TypeForDecl);
1849 return QualType(Decl->TypeForDecl, 0);
1850}
1851
1852QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1853 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1854
1855 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1856 if (PrevDecl->TypeForDecl)
1857 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1858
1859 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1860 Types.push_back(Decl->TypeForDecl);
1861 return QualType(Decl->TypeForDecl, 0);
1862}
1863
John McCall49a832b2009-10-18 09:09:24 +00001864/// \brief Retrieve a substitution-result type.
1865QualType
1866ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1867 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001868 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001869 && "replacement types must always be canonical");
1870
1871 llvm::FoldingSetNodeID ID;
1872 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1873 void *InsertPos = 0;
1874 SubstTemplateTypeParmType *SubstParm
1875 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1876
1877 if (!SubstParm) {
1878 SubstParm = new (*this, TypeAlignment)
1879 SubstTemplateTypeParmType(Parm, Replacement);
1880 Types.push_back(SubstParm);
1881 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1882 }
1883
1884 return QualType(SubstParm, 0);
1885}
1886
Douglas Gregorfab9d672009-02-05 23:33:38 +00001887/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001888/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001889/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001890QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001891 bool ParameterPack,
Douglas Gregorefed5c82010-06-16 15:23:05 +00001892 IdentifierInfo *Name) {
Douglas Gregorfab9d672009-02-05 23:33:38 +00001893 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00001894 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001895 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001896 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001897 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1898
1899 if (TypeParm)
1900 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Douglas Gregorefed5c82010-06-16 15:23:05 +00001902 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001903 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00001904 TypeParm = new (*this, TypeAlignment)
1905 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001906
1907 TemplateTypeParmType *TypeCheck
1908 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1909 assert(!TypeCheck && "Template type parameter canonical type broken");
1910 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001911 } else
John McCall6b304a02009-09-24 23:30:46 +00001912 TypeParm = new (*this, TypeAlignment)
1913 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001914
1915 Types.push_back(TypeParm);
1916 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1917
1918 return QualType(TypeParm, 0);
1919}
1920
John McCall3cb0ebd2010-03-10 03:28:59 +00001921TypeSourceInfo *
1922ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1923 SourceLocation NameLoc,
1924 const TemplateArgumentListInfo &Args,
1925 QualType CanonType) {
1926 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1927
1928 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1929 TemplateSpecializationTypeLoc TL
1930 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1931 TL.setTemplateNameLoc(NameLoc);
1932 TL.setLAngleLoc(Args.getLAngleLoc());
1933 TL.setRAngleLoc(Args.getRAngleLoc());
1934 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1935 TL.setArgLocInfo(i, Args[i].getLocInfo());
1936 return DI;
1937}
1938
Mike Stump1eb44332009-09-09 15:08:12 +00001939QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001940ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001941 const TemplateArgumentListInfo &Args,
John McCall71d74bc2010-06-13 09:25:03 +00001942 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001943 unsigned NumArgs = Args.size();
1944
John McCall833ca992009-10-29 08:12:44 +00001945 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1946 ArgVec.reserve(NumArgs);
1947 for (unsigned i = 0; i != NumArgs; ++i)
1948 ArgVec.push_back(Args[i].getArgument());
1949
John McCall31f17ec2010-04-27 00:57:59 +00001950 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001951 Canon);
John McCall833ca992009-10-29 08:12:44 +00001952}
1953
1954QualType
1955ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001956 const TemplateArgument *Args,
1957 unsigned NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001958 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001959 if (!Canon.isNull())
1960 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001961 else
1962 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001963
Douglas Gregor1275ae02009-07-28 23:00:59 +00001964 // Allocate the (non-canonical) template specialization type, but don't
1965 // try to unique it: these types typically have location information that
1966 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001967 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001968 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001969 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001970 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00001971 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00001972 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001973 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Douglas Gregor55f6b142009-02-09 18:46:07 +00001975 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001976 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001977}
1978
Mike Stump1eb44332009-09-09 15:08:12 +00001979QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001980ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1981 const TemplateArgument *Args,
1982 unsigned NumArgs) {
1983 // Build the canonical template specialization type.
1984 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1985 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1986 CanonArgs.reserve(NumArgs);
1987 for (unsigned I = 0; I != NumArgs; ++I)
1988 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1989
1990 // Determine whether this canonical template specialization type already
1991 // exists.
1992 llvm::FoldingSetNodeID ID;
1993 TemplateSpecializationType::Profile(ID, CanonTemplate,
1994 CanonArgs.data(), NumArgs, *this);
1995
1996 void *InsertPos = 0;
1997 TemplateSpecializationType *Spec
1998 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1999
2000 if (!Spec) {
2001 // Allocate a new canonical template specialization type.
2002 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2003 sizeof(TemplateArgument) * NumArgs),
2004 TypeAlignment);
2005 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2006 CanonArgs.data(), NumArgs,
2007 QualType());
2008 Types.push_back(Spec);
2009 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2010 }
2011
2012 assert(Spec->isDependentType() &&
2013 "Non-dependent template-id type must have a canonical type");
2014 return QualType(Spec, 0);
2015}
2016
2017QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002018ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2019 NestedNameSpecifier *NNS,
2020 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002021 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002022 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002023
2024 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002025 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002026 if (T)
2027 return QualType(T, 0);
2028
Douglas Gregor789b1f62010-02-04 18:10:26 +00002029 QualType Canon = NamedType;
2030 if (!Canon.isCanonical()) {
2031 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002032 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2033 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002034 (void)CheckT;
2035 }
2036
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002037 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002038 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002039 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002040 return QualType(T, 0);
2041}
2042
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002043QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2044 NestedNameSpecifier *NNS,
2045 const IdentifierInfo *Name,
2046 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00002047 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2048
2049 if (Canon.isNull()) {
2050 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002051 ElaboratedTypeKeyword CanonKeyword = Keyword;
2052 if (Keyword == ETK_None)
2053 CanonKeyword = ETK_Typename;
2054
2055 if (CanonNNS != NNS || CanonKeyword != Keyword)
2056 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002057 }
2058
2059 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002060 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002061
2062 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002063 DependentNameType *T
2064 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002065 if (T)
2066 return QualType(T, 0);
2067
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002068 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002069 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002070 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002071 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002072}
2073
Mike Stump1eb44332009-09-09 15:08:12 +00002074QualType
John McCall33500952010-06-11 00:33:02 +00002075ASTContext::getDependentTemplateSpecializationType(
2076 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002077 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002078 const IdentifierInfo *Name,
2079 const TemplateArgumentListInfo &Args) {
2080 // TODO: avoid this copy
2081 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2082 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2083 ArgCopy.push_back(Args[I].getArgument());
2084 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2085 ArgCopy.size(),
2086 ArgCopy.data());
2087}
2088
2089QualType
2090ASTContext::getDependentTemplateSpecializationType(
2091 ElaboratedTypeKeyword Keyword,
2092 NestedNameSpecifier *NNS,
2093 const IdentifierInfo *Name,
2094 unsigned NumArgs,
2095 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00002096 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2097
Douglas Gregor789b1f62010-02-04 18:10:26 +00002098 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002099 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2100 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002101
2102 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002103 DependentTemplateSpecializationType *T
2104 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002105 if (T)
2106 return QualType(T, 0);
2107
John McCall33500952010-06-11 00:33:02 +00002108 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002109
John McCall33500952010-06-11 00:33:02 +00002110 ElaboratedTypeKeyword CanonKeyword = Keyword;
2111 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2112
2113 bool AnyNonCanonArgs = false;
2114 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2115 for (unsigned I = 0; I != NumArgs; ++I) {
2116 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2117 if (!CanonArgs[I].structurallyEquals(Args[I]))
2118 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002119 }
2120
John McCall33500952010-06-11 00:33:02 +00002121 QualType Canon;
2122 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2123 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2124 Name, NumArgs,
2125 CanonArgs.data());
2126
2127 // Find the insert position again.
2128 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2129 }
2130
2131 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2132 sizeof(TemplateArgument) * NumArgs),
2133 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002134 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002135 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002136 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002137 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002138 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002139}
2140
Chris Lattner88cb27a2008-04-07 04:56:42 +00002141/// CmpProtocolNames - Comparison predicate for sorting protocols
2142/// alphabetically.
2143static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2144 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002145 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002146}
2147
John McCallc12c5bb2010-05-15 11:32:37 +00002148static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002149 unsigned NumProtocols) {
2150 if (NumProtocols == 0) return true;
2151
2152 for (unsigned i = 1; i != NumProtocols; ++i)
2153 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2154 return false;
2155 return true;
2156}
2157
2158static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002159 unsigned &NumProtocols) {
2160 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Chris Lattner88cb27a2008-04-07 04:56:42 +00002162 // Sort protocols, keyed by name.
2163 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2164
2165 // Remove duplicates.
2166 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2167 NumProtocols = ProtocolsEnd-Protocols;
2168}
2169
John McCallc12c5bb2010-05-15 11:32:37 +00002170QualType ASTContext::getObjCObjectType(QualType BaseType,
2171 ObjCProtocolDecl * const *Protocols,
2172 unsigned NumProtocols) {
2173 // If the base type is an interface and there aren't any protocols
2174 // to add, then the interface type will do just fine.
2175 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2176 return BaseType;
2177
2178 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002179 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002180 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002181 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002182 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2183 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002184
John McCallc12c5bb2010-05-15 11:32:37 +00002185 // Build the canonical type, which has the canonical base type and
2186 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002187 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002188 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2189 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2190 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002191 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2192 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002193 unsigned UniqueCount = NumProtocols;
2194
John McCall54e14c42009-10-22 22:37:11 +00002195 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002196 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2197 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002198 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002199 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2200 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002201 }
2202
2203 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002204 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2205 }
2206
2207 unsigned Size = sizeof(ObjCObjectTypeImpl);
2208 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2209 void *Mem = Allocate(Size, TypeAlignment);
2210 ObjCObjectTypeImpl *T =
2211 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2212
2213 Types.push_back(T);
2214 ObjCObjectTypes.InsertNode(T, InsertPos);
2215 return QualType(T, 0);
2216}
2217
2218/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2219/// the given object type.
2220QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2221 llvm::FoldingSetNodeID ID;
2222 ObjCObjectPointerType::Profile(ID, ObjectT);
2223
2224 void *InsertPos = 0;
2225 if (ObjCObjectPointerType *QT =
2226 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2227 return QualType(QT, 0);
2228
2229 // Find the canonical object type.
2230 QualType Canonical;
2231 if (!ObjectT.isCanonical()) {
2232 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2233
2234 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002235 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2236 }
2237
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002238 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002239 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2240 ObjCObjectPointerType *QType =
2241 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002242
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002243 Types.push_back(QType);
2244 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002245 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002246}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002247
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002248/// getObjCInterfaceType - Return the unique reference to the type for the
2249/// specified ObjC interface decl. The list of protocols is optional.
John McCallc12c5bb2010-05-15 11:32:37 +00002250QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2251 if (Decl->TypeForDecl)
2252 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002253
John McCallc12c5bb2010-05-15 11:32:37 +00002254 // FIXME: redeclarations?
2255 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2256 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2257 Decl->TypeForDecl = T;
2258 Types.push_back(T);
2259 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002260}
2261
Douglas Gregor72564e72009-02-26 23:50:07 +00002262/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2263/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002264/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002265/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002266/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002267QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002268 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002269 if (tofExpr->isTypeDependent()) {
2270 llvm::FoldingSetNodeID ID;
2271 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Douglas Gregorb1975722009-07-30 23:18:24 +00002273 void *InsertPos = 0;
2274 DependentTypeOfExprType *Canon
2275 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2276 if (Canon) {
2277 // We already have a "canonical" version of an identical, dependent
2278 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002279 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002280 QualType((TypeOfExprType*)Canon, 0));
2281 }
2282 else {
2283 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002284 Canon
2285 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002286 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2287 toe = Canon;
2288 }
2289 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002290 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002291 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002292 }
Steve Naroff9752f252007-08-01 18:02:17 +00002293 Types.push_back(toe);
2294 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002295}
2296
Steve Naroff9752f252007-08-01 18:02:17 +00002297/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2298/// TypeOfType AST's. The only motivation to unique these nodes would be
2299/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002300/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002301/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002302QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002303 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002304 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002305 Types.push_back(tot);
2306 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002307}
2308
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002309/// getDecltypeForExpr - Given an expr, will return the decltype for that
2310/// expression, according to the rules in C++0x [dcl.type.simple]p4
2311static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002312 if (e->isTypeDependent())
2313 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002315 // If e is an id expression or a class member access, decltype(e) is defined
2316 // as the type of the entity named by e.
2317 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2318 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2319 return VD->getType();
2320 }
2321 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2322 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2323 return FD->getType();
2324 }
2325 // If e is a function call or an invocation of an overloaded operator,
2326 // (parentheses around e are ignored), decltype(e) is defined as the
2327 // return type of that function.
2328 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2329 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002330
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002331 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002332
2333 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002334 // defined as T&, otherwise decltype(e) is defined as T.
2335 if (e->isLvalue(Context) == Expr::LV_Valid)
2336 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002337
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002338 return T;
2339}
2340
Anders Carlsson395b4752009-06-24 19:06:50 +00002341/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2342/// DecltypeType AST's. The only motivation to unique these nodes would be
2343/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002344/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002345/// on canonical type's (which are always unique).
2346QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002347 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002348 if (e->isTypeDependent()) {
2349 llvm::FoldingSetNodeID ID;
2350 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002351
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002352 void *InsertPos = 0;
2353 DependentDecltypeType *Canon
2354 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2355 if (Canon) {
2356 // We already have a "canonical" version of an equivalent, dependent
2357 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002358 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002359 QualType((DecltypeType*)Canon, 0));
2360 }
2361 else {
2362 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002363 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002364 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2365 dt = Canon;
2366 }
2367 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002368 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002369 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002370 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002371 Types.push_back(dt);
2372 return QualType(dt, 0);
2373}
2374
Reid Spencer5f016e22007-07-11 17:01:13 +00002375/// getTagDeclType - Return the unique reference to the type for the
2376/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002377QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002378 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002379 // FIXME: What is the design on getTagDeclType when it requires casting
2380 // away const? mutable?
2381 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002382}
2383
Mike Stump1eb44332009-09-09 15:08:12 +00002384/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2385/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2386/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002387CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002388 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002389}
2390
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002391/// getSignedWCharType - Return the type of "signed wchar_t".
2392/// Used when in C++, as a GCC extension.
2393QualType ASTContext::getSignedWCharType() const {
2394 // FIXME: derive from "Target" ?
2395 return WCharTy;
2396}
2397
2398/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2399/// Used when in C++, as a GCC extension.
2400QualType ASTContext::getUnsignedWCharType() const {
2401 // FIXME: derive from "Target" ?
2402 return UnsignedIntTy;
2403}
2404
Chris Lattner8b9023b2007-07-13 03:05:23 +00002405/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2406/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2407QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002408 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002409}
2410
Chris Lattnere6327742008-04-02 05:18:44 +00002411//===----------------------------------------------------------------------===//
2412// Type Operators
2413//===----------------------------------------------------------------------===//
2414
John McCall54e14c42009-10-22 22:37:11 +00002415CanQualType ASTContext::getCanonicalParamType(QualType T) {
2416 // Push qualifiers into arrays, and then discard any remaining
2417 // qualifiers.
2418 T = getCanonicalType(T);
2419 const Type *Ty = T.getTypePtr();
2420
2421 QualType Result;
2422 if (isa<ArrayType>(Ty)) {
2423 Result = getArrayDecayedType(QualType(Ty,0));
2424 } else if (isa<FunctionType>(Ty)) {
2425 Result = getPointerType(QualType(Ty, 0));
2426 } else {
2427 Result = QualType(Ty, 0);
2428 }
2429
2430 return CanQualType::CreateUnsafe(Result);
2431}
2432
Chris Lattner77c96472008-04-06 22:41:35 +00002433/// getCanonicalType - Return the canonical (structural) type corresponding to
2434/// the specified potentially non-canonical type. The non-canonical version
2435/// of a type may have many "decorated" versions of types. Decorators can
2436/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2437/// to be free of any of these, allowing two canonical types to be compared
2438/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002439CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002440 QualifierCollector Quals;
2441 const Type *Ptr = Quals.strip(T);
2442 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002443
John McCall0953e762009-09-24 19:53:00 +00002444 // The canonical internal type will be the canonical type *except*
2445 // that we push type qualifiers down through array types.
2446
2447 // If there are no new qualifiers to push down, stop here.
2448 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002449 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002450
John McCall0953e762009-09-24 19:53:00 +00002451 // If the type qualifiers are on an array type, get the canonical
2452 // type of the array with the qualifiers applied to the element
2453 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002454 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2455 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002456 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002457
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002458 // Get the canonical version of the element with the extra qualifiers on it.
2459 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002460 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002461 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002462
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002463 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002464 return CanQualType::CreateUnsafe(
2465 getConstantArrayType(NewEltTy, CAT->getSize(),
2466 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002467 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002468 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002469 return CanQualType::CreateUnsafe(
2470 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002471 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002472
Douglas Gregor898574e2008-12-05 23:32:09 +00002473 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002474 return CanQualType::CreateUnsafe(
2475 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002476 DSAT->getSizeExpr() ?
2477 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002478 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002479 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002480 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002481
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002482 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002483 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002484 VAT->getSizeExpr() ?
2485 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002486 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002487 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002488 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002489}
2490
Chandler Carruth28e318c2009-12-29 07:16:59 +00002491QualType ASTContext::getUnqualifiedArrayType(QualType T,
2492 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002493 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002494 const ArrayType *AT = getAsArrayType(T);
2495 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002496 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002497 }
2498
Chandler Carruth28e318c2009-12-29 07:16:59 +00002499 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002500 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002501 if (Elt == UnqualElt)
2502 return T;
2503
Douglas Gregor9dadd942010-05-17 18:45:21 +00002504 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002505 return getConstantArrayType(UnqualElt, CAT->getSize(),
2506 CAT->getSizeModifier(), 0);
2507 }
2508
Douglas Gregor9dadd942010-05-17 18:45:21 +00002509 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002510 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2511 }
2512
Douglas Gregor9dadd942010-05-17 18:45:21 +00002513 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2514 return getVariableArrayType(UnqualElt,
2515 VAT->getSizeExpr() ?
2516 VAT->getSizeExpr()->Retain() : 0,
2517 VAT->getSizeModifier(),
2518 VAT->getIndexTypeCVRQualifiers(),
2519 VAT->getBracketsRange());
2520 }
2521
2522 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002523 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2524 DSAT->getSizeModifier(), 0,
2525 SourceRange());
2526}
2527
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002528/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2529/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2530/// they point to and return true. If T1 and T2 aren't pointer types
2531/// or pointer-to-member types, or if they are not similar at this
2532/// level, returns false and leaves T1 and T2 unchanged. Top-level
2533/// qualifiers on T1 and T2 are ignored. This function will typically
2534/// be called in a loop that successively "unwraps" pointer and
2535/// pointer-to-member types to compare them at each level.
2536bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2537 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2538 *T2PtrType = T2->getAs<PointerType>();
2539 if (T1PtrType && T2PtrType) {
2540 T1 = T1PtrType->getPointeeType();
2541 T2 = T2PtrType->getPointeeType();
2542 return true;
2543 }
2544
2545 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2546 *T2MPType = T2->getAs<MemberPointerType>();
2547 if (T1MPType && T2MPType &&
2548 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2549 QualType(T2MPType->getClass(), 0))) {
2550 T1 = T1MPType->getPointeeType();
2551 T2 = T2MPType->getPointeeType();
2552 return true;
2553 }
2554
2555 if (getLangOptions().ObjC1) {
2556 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2557 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2558 if (T1OPType && T2OPType) {
2559 T1 = T1OPType->getPointeeType();
2560 T2 = T2OPType->getPointeeType();
2561 return true;
2562 }
2563 }
2564
2565 // FIXME: Block pointers, too?
2566
2567 return false;
2568}
2569
John McCall80ad16f2009-11-24 18:42:40 +00002570DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2571 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2572 return TD->getDeclName();
2573
2574 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2575 if (DTN->isIdentifier()) {
2576 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2577 } else {
2578 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2579 }
2580 }
2581
John McCall0bd6feb2009-12-02 08:04:21 +00002582 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2583 assert(Storage);
2584 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002585}
2586
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002587TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002588 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2589 if (TemplateTemplateParmDecl *TTP
2590 = dyn_cast<TemplateTemplateParmDecl>(Template))
2591 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2592
2593 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002594 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002595 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002596
John McCall0bd6feb2009-12-02 08:04:21 +00002597 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002598
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002599 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2600 assert(DTN && "Non-dependent template names must refer to template decls.");
2601 return DTN->CanonicalTemplateName;
2602}
2603
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002604bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2605 X = getCanonicalTemplateName(X);
2606 Y = getCanonicalTemplateName(Y);
2607 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2608}
2609
Mike Stump1eb44332009-09-09 15:08:12 +00002610TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002611ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2612 switch (Arg.getKind()) {
2613 case TemplateArgument::Null:
2614 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Douglas Gregor1275ae02009-07-28 23:00:59 +00002616 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002617 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002618
Douglas Gregor1275ae02009-07-28 23:00:59 +00002619 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002620 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002621
Douglas Gregor788cd062009-11-11 01:00:40 +00002622 case TemplateArgument::Template:
2623 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2624
Douglas Gregor1275ae02009-07-28 23:00:59 +00002625 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002626 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002627 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002628
Douglas Gregor1275ae02009-07-28 23:00:59 +00002629 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002630 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002631
Douglas Gregor1275ae02009-07-28 23:00:59 +00002632 case TemplateArgument::Pack: {
2633 // FIXME: Allocate in ASTContext
2634 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2635 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002636 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002637 AEnd = Arg.pack_end();
2638 A != AEnd; (void)++A, ++Idx)
2639 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002640
Douglas Gregor1275ae02009-07-28 23:00:59 +00002641 TemplateArgument Result;
2642 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2643 return Result;
2644 }
2645 }
2646
2647 // Silence GCC warning
2648 assert(false && "Unhandled template argument kind");
2649 return TemplateArgument();
2650}
2651
Douglas Gregord57959a2009-03-27 23:10:48 +00002652NestedNameSpecifier *
2653ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002654 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002655 return 0;
2656
2657 switch (NNS->getKind()) {
2658 case NestedNameSpecifier::Identifier:
2659 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002660 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002661 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2662 NNS->getAsIdentifier());
2663
2664 case NestedNameSpecifier::Namespace:
2665 // A namespace is canonical; build a nested-name-specifier with
2666 // this namespace and no prefix.
2667 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2668
2669 case NestedNameSpecifier::TypeSpec:
2670 case NestedNameSpecifier::TypeSpecWithTemplate: {
2671 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002672 return NestedNameSpecifier::Create(*this, 0,
2673 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002674 T.getTypePtr());
2675 }
2676
2677 case NestedNameSpecifier::Global:
2678 // The global specifier is canonical and unique.
2679 return NNS;
2680 }
2681
2682 // Required to silence a GCC warning
2683 return 0;
2684}
2685
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002686
2687const ArrayType *ASTContext::getAsArrayType(QualType T) {
2688 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002689 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002690 // Handle the common positive case fast.
2691 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2692 return AT;
2693 }
Mike Stump1eb44332009-09-09 15:08:12 +00002694
John McCall0953e762009-09-24 19:53:00 +00002695 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002696 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002697 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002698 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002699
John McCall0953e762009-09-24 19:53:00 +00002700 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002701 // implements C99 6.7.3p8: "If the specification of an array type includes
2702 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002703
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002704 // If we get here, we either have type qualifiers on the type, or we have
2705 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002706 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002707
John McCall0953e762009-09-24 19:53:00 +00002708 QualifierCollector Qs;
2709 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002710
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002711 // If we have a simple case, just return now.
2712 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002713 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002714 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002716 // Otherwise, we have an array and we have qualifiers on it. Push the
2717 // qualifiers into the array element type and return a new array type.
2718 // Get the canonical version of the element with the extra qualifiers on it.
2719 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002720 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002721
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002722 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2723 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2724 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002725 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002726 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2727 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2728 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002729 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002730
Mike Stump1eb44332009-09-09 15:08:12 +00002731 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002732 = dyn_cast<DependentSizedArrayType>(ATy))
2733 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002734 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002735 DSAT->getSizeExpr() ?
2736 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002737 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002738 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002739 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002741 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002742 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002743 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002744 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002745 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002746 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002747 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002748}
2749
2750
Chris Lattnere6327742008-04-02 05:18:44 +00002751/// getArrayDecayedType - Return the properly qualified result of decaying the
2752/// specified array type to a pointer. This operation is non-trivial when
2753/// handling typedefs etc. The canonical type of "T" must be an array type,
2754/// this returns a pointer to a properly qualified element of the array.
2755///
2756/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2757QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002758 // Get the element type with 'getAsArrayType' so that we don't lose any
2759 // typedefs in the element type of the array. This also handles propagation
2760 // of type qualifiers from the array type into the element type if present
2761 // (C99 6.7.3p8).
2762 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2763 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002764
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002765 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002766
2767 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002768 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002769}
2770
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002771QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002772 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002773 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2774 QT = AT->getElementType();
2775 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002776}
2777
Anders Carlssonfbbce492009-09-25 01:23:32 +00002778QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2779 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002780
Anders Carlssonfbbce492009-09-25 01:23:32 +00002781 if (const ArrayType *AT = getAsArrayType(ElemTy))
2782 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002783
Anders Carlsson6183a992008-12-21 03:44:36 +00002784 return ElemTy;
2785}
2786
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002787/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002788uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002789ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2790 uint64_t ElementCount = 1;
2791 do {
2792 ElementCount *= CA->getSize().getZExtValue();
2793 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2794 } while (CA);
2795 return ElementCount;
2796}
2797
Reid Spencer5f016e22007-07-11 17:01:13 +00002798/// getFloatingRank - Return a relative rank for floating point types.
2799/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002800static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002801 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002802 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002803
John McCall183700f2009-09-21 23:43:11 +00002804 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2805 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002806 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002807 case BuiltinType::Float: return FloatRank;
2808 case BuiltinType::Double: return DoubleRank;
2809 case BuiltinType::LongDouble: return LongDoubleRank;
2810 }
2811}
2812
Mike Stump1eb44332009-09-09 15:08:12 +00002813/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2814/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002815/// 'typeDomain' is a real floating point or complex type.
2816/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002817QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2818 QualType Domain) const {
2819 FloatingRank EltRank = getFloatingRank(Size);
2820 if (Domain->isComplexType()) {
2821 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002822 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002823 case FloatRank: return FloatComplexTy;
2824 case DoubleRank: return DoubleComplexTy;
2825 case LongDoubleRank: return LongDoubleComplexTy;
2826 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002827 }
Chris Lattner1361b112008-04-06 23:58:54 +00002828
2829 assert(Domain->isRealFloatingType() && "Unknown domain!");
2830 switch (EltRank) {
2831 default: assert(0 && "getFloatingRank(): illegal value for rank");
2832 case FloatRank: return FloatTy;
2833 case DoubleRank: return DoubleTy;
2834 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002835 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002836}
2837
Chris Lattner7cfeb082008-04-06 23:55:33 +00002838/// getFloatingTypeOrder - Compare the rank of the two specified floating
2839/// point types, ignoring the domain of the type (i.e. 'double' ==
2840/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002841/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002842int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2843 FloatingRank LHSR = getFloatingRank(LHS);
2844 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002845
Chris Lattnera75cea32008-04-06 23:38:49 +00002846 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002847 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002848 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002849 return 1;
2850 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002851}
2852
Chris Lattnerf52ab252008-04-06 22:59:24 +00002853/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2854/// routine will assert if passed a built-in type that isn't an integer or enum,
2855/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002856unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002857 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002858 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002859 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002860
Eli Friedmana3426752009-07-05 23:44:27 +00002861 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2862 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2863
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002864 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2865 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2866
2867 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2868 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2869
Chris Lattnerf52ab252008-04-06 22:59:24 +00002870 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002871 default: assert(0 && "getIntegerRank(): not a built-in integer");
2872 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002873 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002874 case BuiltinType::Char_S:
2875 case BuiltinType::Char_U:
2876 case BuiltinType::SChar:
2877 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002878 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002879 case BuiltinType::Short:
2880 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002881 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002882 case BuiltinType::Int:
2883 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002884 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002885 case BuiltinType::Long:
2886 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002887 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002888 case BuiltinType::LongLong:
2889 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002890 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002891 case BuiltinType::Int128:
2892 case BuiltinType::UInt128:
2893 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002894 }
2895}
2896
Eli Friedman04e83572009-08-20 04:21:42 +00002897/// \brief Whether this is a promotable bitfield reference according
2898/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2899///
2900/// \returns the type this bit-field will promote to, or NULL if no
2901/// promotion occurs.
2902QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002903 if (E->isTypeDependent() || E->isValueDependent())
2904 return QualType();
2905
Eli Friedman04e83572009-08-20 04:21:42 +00002906 FieldDecl *Field = E->getBitField();
2907 if (!Field)
2908 return QualType();
2909
2910 QualType FT = Field->getType();
2911
2912 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2913 uint64_t BitWidth = BitWidthAP.getZExtValue();
2914 uint64_t IntSize = getTypeSize(IntTy);
2915 // GCC extension compatibility: if the bit-field size is less than or equal
2916 // to the size of int, it gets promoted no matter what its type is.
2917 // For instance, unsigned long bf : 4 gets promoted to signed int.
2918 if (BitWidth < IntSize)
2919 return IntTy;
2920
2921 if (BitWidth == IntSize)
2922 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2923
2924 // Types bigger than int are not subject to promotions, and therefore act
2925 // like the base type.
2926 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2927 // is ridiculous.
2928 return QualType();
2929}
2930
Eli Friedmana95d7572009-08-19 07:44:53 +00002931/// getPromotedIntegerType - Returns the type that Promotable will
2932/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2933/// integer type.
2934QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2935 assert(!Promotable.isNull());
2936 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002937 if (const EnumType *ET = Promotable->getAs<EnumType>())
2938 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002939 if (Promotable->isSignedIntegerType())
2940 return IntTy;
2941 uint64_t PromotableSize = getTypeSize(Promotable);
2942 uint64_t IntSize = getTypeSize(IntTy);
2943 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2944 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2945}
2946
Mike Stump1eb44332009-09-09 15:08:12 +00002947/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002948/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002949/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002950int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002951 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2952 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002953 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002954
Chris Lattnerf52ab252008-04-06 22:59:24 +00002955 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2956 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002957
Chris Lattner7cfeb082008-04-06 23:55:33 +00002958 unsigned LHSRank = getIntegerRank(LHSC);
2959 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002960
Chris Lattner7cfeb082008-04-06 23:55:33 +00002961 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2962 if (LHSRank == RHSRank) return 0;
2963 return LHSRank > RHSRank ? 1 : -1;
2964 }
Mike Stump1eb44332009-09-09 15:08:12 +00002965
Chris Lattner7cfeb082008-04-06 23:55:33 +00002966 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2967 if (LHSUnsigned) {
2968 // If the unsigned [LHS] type is larger, return it.
2969 if (LHSRank >= RHSRank)
2970 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002971
Chris Lattner7cfeb082008-04-06 23:55:33 +00002972 // If the signed type can represent all values of the unsigned type, it
2973 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002974 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002975 return -1;
2976 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002977
Chris Lattner7cfeb082008-04-06 23:55:33 +00002978 // If the unsigned [RHS] type is larger, return it.
2979 if (RHSRank >= LHSRank)
2980 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002981
Chris Lattner7cfeb082008-04-06 23:55:33 +00002982 // If the signed type can represent all values of the unsigned type, it
2983 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002984 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002985 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002986}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002987
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002988static RecordDecl *
2989CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2990 SourceLocation L, IdentifierInfo *Id) {
2991 if (Ctx.getLangOptions().CPlusPlus)
2992 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2993 else
2994 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2995}
2996
Mike Stump1eb44332009-09-09 15:08:12 +00002997// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002998QualType ASTContext::getCFConstantStringType() {
2999 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003000 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003001 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003002 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003003 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003004
Anders Carlssonf06273f2007-11-19 00:25:30 +00003005 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003006
Anders Carlsson71993dd2007-08-17 05:31:46 +00003007 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003008 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003009 // int flags;
3010 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003011 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003012 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003013 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003014 FieldTypes[3] = LongTy;
3015
Anders Carlsson71993dd2007-08-17 05:31:46 +00003016 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003017 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003018 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003019 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003020 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003021 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003022 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003023 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003024 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003025 }
3026
Douglas Gregor838db382010-02-11 01:19:42 +00003027 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003028 }
Mike Stump1eb44332009-09-09 15:08:12 +00003029
Anders Carlsson71993dd2007-08-17 05:31:46 +00003030 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003031}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003032
Douglas Gregor319ac892009-04-23 22:29:11 +00003033void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003034 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003035 assert(Rec && "Invalid CFConstantStringType");
3036 CFConstantStringTypeDecl = Rec->getDecl();
3037}
3038
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003039// getNSConstantStringType - Return the type used for constant NSStrings.
3040QualType ASTContext::getNSConstantStringType() {
3041 if (!NSConstantStringTypeDecl) {
3042 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003043 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003044 &Idents.get("__builtin_NSString"));
3045 NSConstantStringTypeDecl->startDefinition();
3046
3047 QualType FieldTypes[3];
3048
3049 // const int *isa;
3050 FieldTypes[0] = getPointerType(IntTy.withConst());
3051 // const char *str;
3052 FieldTypes[1] = getPointerType(CharTy.withConst());
3053 // unsigned int length;
3054 FieldTypes[2] = UnsignedIntTy;
3055
3056 // Create fields
3057 for (unsigned i = 0; i < 3; ++i) {
3058 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3059 SourceLocation(), 0,
3060 FieldTypes[i], /*TInfo=*/0,
3061 /*BitWidth=*/0,
3062 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003063 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003064 NSConstantStringTypeDecl->addDecl(Field);
3065 }
3066
3067 NSConstantStringTypeDecl->completeDefinition();
3068 }
3069
3070 return getTagDeclType(NSConstantStringTypeDecl);
3071}
3072
3073void ASTContext::setNSConstantStringType(QualType T) {
3074 const RecordType *Rec = T->getAs<RecordType>();
3075 assert(Rec && "Invalid NSConstantStringType");
3076 NSConstantStringTypeDecl = Rec->getDecl();
3077}
3078
Mike Stump1eb44332009-09-09 15:08:12 +00003079QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003080 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003081 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003082 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003083 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003084 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003085
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003086 QualType FieldTypes[] = {
3087 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003088 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003089 getPointerType(UnsignedLongTy),
3090 getConstantArrayType(UnsignedLongTy,
3091 llvm::APInt(32, 5), ArrayType::Normal, 0)
3092 };
Mike Stump1eb44332009-09-09 15:08:12 +00003093
Douglas Gregor44b43212008-12-11 16:49:14 +00003094 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003095 FieldDecl *Field = FieldDecl::Create(*this,
3096 ObjCFastEnumerationStateTypeDecl,
3097 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003098 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003099 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003100 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003101 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003102 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003103 }
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003104 if (getLangOptions().CPlusPlus)
Fariborz Jahanian81148e92010-05-27 16:35:00 +00003105 if (CXXRecordDecl *CXXRD =
3106 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian38c9ab82010-05-27 16:05:06 +00003107 CXXRD->setEmpty(false);
Mike Stump1eb44332009-09-09 15:08:12 +00003108
Douglas Gregor838db382010-02-11 01:19:42 +00003109 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003110 }
Mike Stump1eb44332009-09-09 15:08:12 +00003111
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003112 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3113}
3114
Mike Stumpadaaad32009-10-20 02:12:22 +00003115QualType ASTContext::getBlockDescriptorType() {
3116 if (BlockDescriptorType)
3117 return getTagDeclType(BlockDescriptorType);
3118
3119 RecordDecl *T;
3120 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003121 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003122 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003123 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003124
3125 QualType FieldTypes[] = {
3126 UnsignedLongTy,
3127 UnsignedLongTy,
3128 };
3129
3130 const char *FieldNames[] = {
3131 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003132 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003133 };
3134
3135 for (size_t i = 0; i < 2; ++i) {
3136 FieldDecl *Field = FieldDecl::Create(*this,
3137 T,
3138 SourceLocation(),
3139 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003140 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003141 /*BitWidth=*/0,
3142 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003143 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003144 T->addDecl(Field);
3145 }
3146
Douglas Gregor838db382010-02-11 01:19:42 +00003147 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003148
3149 BlockDescriptorType = T;
3150
3151 return getTagDeclType(BlockDescriptorType);
3152}
3153
3154void ASTContext::setBlockDescriptorType(QualType T) {
3155 const RecordType *Rec = T->getAs<RecordType>();
3156 assert(Rec && "Invalid BlockDescriptorType");
3157 BlockDescriptorType = Rec->getDecl();
3158}
3159
Mike Stump083c25e2009-10-22 00:49:09 +00003160QualType ASTContext::getBlockDescriptorExtendedType() {
3161 if (BlockDescriptorExtendedType)
3162 return getTagDeclType(BlockDescriptorExtendedType);
3163
3164 RecordDecl *T;
3165 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003166 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003167 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003168 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003169
3170 QualType FieldTypes[] = {
3171 UnsignedLongTy,
3172 UnsignedLongTy,
3173 getPointerType(VoidPtrTy),
3174 getPointerType(VoidPtrTy)
3175 };
3176
3177 const char *FieldNames[] = {
3178 "reserved",
3179 "Size",
3180 "CopyFuncPtr",
3181 "DestroyFuncPtr"
3182 };
3183
3184 for (size_t i = 0; i < 4; ++i) {
3185 FieldDecl *Field = FieldDecl::Create(*this,
3186 T,
3187 SourceLocation(),
3188 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003189 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003190 /*BitWidth=*/0,
3191 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003192 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003193 T->addDecl(Field);
3194 }
3195
Douglas Gregor838db382010-02-11 01:19:42 +00003196 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003197
3198 BlockDescriptorExtendedType = T;
3199
3200 return getTagDeclType(BlockDescriptorExtendedType);
3201}
3202
3203void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3204 const RecordType *Rec = T->getAs<RecordType>();
3205 assert(Rec && "Invalid BlockDescriptorType");
3206 BlockDescriptorExtendedType = Rec->getDecl();
3207}
3208
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003209bool ASTContext::BlockRequiresCopying(QualType Ty) {
3210 if (Ty->isBlockPointerType())
3211 return true;
3212 if (isObjCNSObjectType(Ty))
3213 return true;
3214 if (Ty->isObjCObjectPointerType())
3215 return true;
3216 return false;
3217}
3218
3219QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3220 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003221 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003222 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003223 // unsigned int __flags;
3224 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003225 // void *__copy_helper; // as needed
3226 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003227 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003228 // } *
3229
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003230 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3231
3232 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003233 llvm::SmallString<36> Name;
3234 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3235 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003236 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003237 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003238 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003239 T->startDefinition();
3240 QualType Int32Ty = IntTy;
3241 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3242 QualType FieldTypes[] = {
3243 getPointerType(VoidPtrTy),
3244 getPointerType(getTagDeclType(T)),
3245 Int32Ty,
3246 Int32Ty,
3247 getPointerType(VoidPtrTy),
3248 getPointerType(VoidPtrTy),
3249 Ty
3250 };
3251
3252 const char *FieldNames[] = {
3253 "__isa",
3254 "__forwarding",
3255 "__flags",
3256 "__size",
3257 "__copy_helper",
3258 "__destroy_helper",
3259 DeclName,
3260 };
3261
3262 for (size_t i = 0; i < 7; ++i) {
3263 if (!HasCopyAndDispose && i >=4 && i <= 5)
3264 continue;
3265 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3266 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003267 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003268 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003269 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003270 T->addDecl(Field);
3271 }
3272
Douglas Gregor838db382010-02-11 01:19:42 +00003273 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003274
3275 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003276}
3277
3278
3279QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003280 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003281 llvm::SmallVectorImpl<const Expr *> &Layout) {
3282
Mike Stumpadaaad32009-10-20 02:12:22 +00003283 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003284 llvm::SmallString<36> Name;
3285 llvm::raw_svector_ostream(Name) << "__block_literal_"
3286 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003287 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003288 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003289 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003290 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003291 QualType FieldTypes[] = {
3292 getPointerType(VoidPtrTy),
3293 IntTy,
3294 IntTy,
3295 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003296 (BlockHasCopyDispose ?
3297 getPointerType(getBlockDescriptorExtendedType()) :
3298 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003299 };
3300
3301 const char *FieldNames[] = {
3302 "__isa",
3303 "__flags",
3304 "__reserved",
3305 "__FuncPtr",
3306 "__descriptor"
3307 };
3308
3309 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003310 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003311 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003312 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003313 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003314 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003315 T->addDecl(Field);
3316 }
3317
John McCallea1471e2010-05-20 01:18:31 +00003318 for (unsigned i = 0; i < Layout.size(); ++i) {
3319 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003320
John McCallea1471e2010-05-20 01:18:31 +00003321 QualType FieldType = E->getType();
3322 IdentifierInfo *FieldName = 0;
3323 if (isa<CXXThisExpr>(E)) {
3324 FieldName = &Idents.get("this");
3325 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3326 const ValueDecl *D = BDRE->getDecl();
3327 FieldName = D->getIdentifier();
3328 if (BDRE->isByRef())
3329 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3330 } else {
3331 // Padding.
3332 assert(isa<ConstantArrayType>(FieldType) &&
3333 isa<DeclRefExpr>(E) &&
3334 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3335 "doesn't match characteristics of padding decl");
3336 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003337
3338 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003339 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003340 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003341 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003342 T->addDecl(Field);
3343 }
3344
Douglas Gregor838db382010-02-11 01:19:42 +00003345 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003346
3347 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003348}
3349
Douglas Gregor319ac892009-04-23 22:29:11 +00003350void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003351 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003352 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3353 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3354}
3355
Anders Carlssone8c49532007-10-29 06:33:42 +00003356// This returns true if a type has been typedefed to BOOL:
3357// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003358static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003359 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003360 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3361 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003362
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003363 return false;
3364}
3365
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003366/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003367/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003368CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003369 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003370
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003371 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003372 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003373 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003374 // Treat arrays as pointers, since that's how they're passed in.
3375 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003376 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003377 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003378}
3379
3380static inline
3381std::string charUnitsToString(const CharUnits &CU) {
3382 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003383}
3384
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003385/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003386/// declaration.
3387void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3388 std::string& S) {
3389 const BlockDecl *Decl = Expr->getBlockDecl();
3390 QualType BlockTy =
3391 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3392 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003393 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003394 // Compute size of all parameters.
3395 // Start with computing size of a pointer in number of bytes.
3396 // FIXME: There might(should) be a better way of doing this computation!
3397 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003398 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3399 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003400 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003401 E = Decl->param_end(); PI != E; ++PI) {
3402 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003403 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003404 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003405 ParmOffset += sz;
3406 }
3407 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003408 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003409 // Block pointer and offset.
3410 S += "@?0";
3411 ParmOffset = PtrSize;
3412
3413 // Argument types.
3414 ParmOffset = PtrSize;
3415 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3416 Decl->param_end(); PI != E; ++PI) {
3417 ParmVarDecl *PVDecl = *PI;
3418 QualType PType = PVDecl->getOriginalType();
3419 if (const ArrayType *AT =
3420 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3421 // Use array's original type only if it has known number of
3422 // elements.
3423 if (!isa<ConstantArrayType>(AT))
3424 PType = PVDecl->getType();
3425 } else if (PType->isFunctionType())
3426 PType = PVDecl->getType();
3427 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003428 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003429 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003430 }
3431}
3432
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003433/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003434/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003435void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003436 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003437 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003438 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003439 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003440 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003441 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003442 // Compute size of all parameters.
3443 // Start with computing size of a pointer in number of bytes.
3444 // FIXME: There might(should) be a better way of doing this computation!
3445 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003446 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003447 // The first two arguments (self and _cmd) are pointers; account for
3448 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003449 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003450 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003451 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003452 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003453 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003454 assert (sz.isPositive() &&
3455 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003456 ParmOffset += sz;
3457 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003458 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003459 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003460 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003461
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003462 // Argument types.
3463 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003464 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003465 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003466 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003467 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003468 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003469 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3470 // Use array's original type only if it has known number of
3471 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003472 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003473 PType = PVDecl->getType();
3474 } else if (PType->isFunctionType())
3475 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003476 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003477 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003478 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003479 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003480 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003481 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003482 }
3483}
3484
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003485/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003486/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003487/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3488/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003489/// Property attributes are stored as a comma-delimited C string. The simple
3490/// attributes readonly and bycopy are encoded as single characters. The
3491/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3492/// encoded as single characters, followed by an identifier. Property types
3493/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003494/// these attributes are defined by the following enumeration:
3495/// @code
3496/// enum PropertyAttributes {
3497/// kPropertyReadOnly = 'R', // property is read-only.
3498/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3499/// kPropertyByref = '&', // property is a reference to the value last assigned
3500/// kPropertyDynamic = 'D', // property is dynamic
3501/// kPropertyGetter = 'G', // followed by getter selector name
3502/// kPropertySetter = 'S', // followed by setter selector name
3503/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3504/// kPropertyType = 't' // followed by old-style type encoding.
3505/// kPropertyWeak = 'W' // 'weak' property
3506/// kPropertyStrong = 'P' // property GC'able
3507/// kPropertyNonAtomic = 'N' // property non-atomic
3508/// };
3509/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003510void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003511 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003512 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003513 // Collect information from the property implementation decl(s).
3514 bool Dynamic = false;
3515 ObjCPropertyImplDecl *SynthesizePID = 0;
3516
3517 // FIXME: Duplicated code due to poor abstraction.
3518 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003519 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003520 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3521 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003522 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003523 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003524 ObjCPropertyImplDecl *PID = *i;
3525 if (PID->getPropertyDecl() == PD) {
3526 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3527 Dynamic = true;
3528 } else {
3529 SynthesizePID = PID;
3530 }
3531 }
3532 }
3533 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003534 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003535 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003536 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003537 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003538 ObjCPropertyImplDecl *PID = *i;
3539 if (PID->getPropertyDecl() == PD) {
3540 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3541 Dynamic = true;
3542 } else {
3543 SynthesizePID = PID;
3544 }
3545 }
Mike Stump1eb44332009-09-09 15:08:12 +00003546 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003547 }
3548 }
3549
3550 // FIXME: This is not very efficient.
3551 S = "T";
3552
3553 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003554 // GCC has some special rules regarding encoding of properties which
3555 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003556 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003557 true /* outermost type */,
3558 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003559
3560 if (PD->isReadOnly()) {
3561 S += ",R";
3562 } else {
3563 switch (PD->getSetterKind()) {
3564 case ObjCPropertyDecl::Assign: break;
3565 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003566 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003567 }
3568 }
3569
3570 // It really isn't clear at all what this means, since properties
3571 // are "dynamic by default".
3572 if (Dynamic)
3573 S += ",D";
3574
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003575 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3576 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003577
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003578 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3579 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003580 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003581 }
3582
3583 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3584 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003585 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003586 }
3587
3588 if (SynthesizePID) {
3589 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3590 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003591 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003592 }
3593
3594 // FIXME: OBJCGC: weak & strong
3595}
3596
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003597/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003598/// Another legacy compatibility encoding: 32-bit longs are encoded as
3599/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003600/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3601///
3602void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003603 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003604 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003605 if (BT->getKind() == BuiltinType::ULong &&
3606 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003607 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003608 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003609 if (BT->getKind() == BuiltinType::Long &&
3610 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003611 PointeeTy = IntTy;
3612 }
3613 }
3614}
3615
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003616void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003617 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003618 // We follow the behavior of gcc, expanding structures which are
3619 // directly pointed to, and expanding embedded structures. Note that
3620 // these rules are sufficient to prevent recursive encoding of the
3621 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003622 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003623 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003624}
3625
David Chisnall64fd7e82010-06-04 01:10:52 +00003626static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3627 switch (T->getAs<BuiltinType>()->getKind()) {
3628 default: assert(0 && "Unhandled builtin type kind");
3629 case BuiltinType::Void: return 'v';
3630 case BuiltinType::Bool: return 'B';
3631 case BuiltinType::Char_U:
3632 case BuiltinType::UChar: return 'C';
3633 case BuiltinType::UShort: return 'S';
3634 case BuiltinType::UInt: return 'I';
3635 case BuiltinType::ULong:
3636 return
3637 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3638 case BuiltinType::UInt128: return 'T';
3639 case BuiltinType::ULongLong: return 'Q';
3640 case BuiltinType::Char_S:
3641 case BuiltinType::SChar: return 'c';
3642 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003643 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003644 case BuiltinType::Int: return 'i';
3645 case BuiltinType::Long:
3646 return
3647 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3648 case BuiltinType::LongLong: return 'q';
3649 case BuiltinType::Int128: return 't';
3650 case BuiltinType::Float: return 'f';
3651 case BuiltinType::Double: return 'd';
3652 case BuiltinType::LongDouble: return 'd';
3653 }
3654}
3655
Mike Stump1eb44332009-09-09 15:08:12 +00003656static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003657 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003658 const Expr *E = FD->getBitWidth();
3659 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3660 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003661 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003662 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3663 // The GNU runtime requires more information; bitfields are encoded as b,
3664 // then the offset (in bits) of the first element, then the type of the
3665 // bitfield, then the size in bits. For example, in this structure:
3666 //
3667 // struct
3668 // {
3669 // int integer;
3670 // int flags:2;
3671 // };
3672 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3673 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3674 // information is not especially sensible, but we're stuck with it for
3675 // compatibility with GCC, although providing it breaks anything that
3676 // actually uses runtime introspection and wants to work on both runtimes...
3677 if (!Ctx->getLangOptions().NeXTRuntime) {
3678 const RecordDecl *RD = FD->getParent();
3679 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3680 // FIXME: This same linear search is also used in ExprConstant - it might
3681 // be better if the FieldDecl stored its offset. We'd be increasing the
3682 // size of the object slightly, but saving some time every time it is used.
3683 unsigned i = 0;
3684 for (RecordDecl::field_iterator Field = RD->field_begin(),
3685 FieldEnd = RD->field_end();
3686 Field != FieldEnd; (void)++Field, ++i) {
3687 if (*Field == FD)
3688 break;
3689 }
3690 S += llvm::utostr(RL.getFieldOffset(i));
3691 S += ObjCEncodingForPrimitiveKind(Context, T);
3692 }
3693 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003694 S += llvm::utostr(N);
3695}
3696
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003697// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003698void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3699 bool ExpandPointedToStructures,
3700 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003701 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003702 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003703 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003704 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003705 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003706 return EncodeBitField(this, S, T, FD);
3707 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003708 return;
3709 }
Mike Stump1eb44332009-09-09 15:08:12 +00003710
John McCall183700f2009-09-21 23:43:11 +00003711 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003712 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003713 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003714 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003715 return;
3716 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003717
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003718 // encoding for pointer or r3eference types.
3719 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003720 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003721 if (PT->isObjCSelType()) {
3722 S += ':';
3723 return;
3724 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003725 PointeeTy = PT->getPointeeType();
3726 }
3727 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3728 PointeeTy = RT->getPointeeType();
3729 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003730 bool isReadOnly = false;
3731 // For historical/compatibility reasons, the read-only qualifier of the
3732 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3733 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003734 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003735 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003736 if (OutermostType && T.isConstQualified()) {
3737 isReadOnly = true;
3738 S += 'r';
3739 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003740 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003741 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003742 while (P->getAs<PointerType>())
3743 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003744 if (P.isConstQualified()) {
3745 isReadOnly = true;
3746 S += 'r';
3747 }
3748 }
3749 if (isReadOnly) {
3750 // Another legacy compatibility encoding. Some ObjC qualifier and type
3751 // combinations need to be rearranged.
3752 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003753 if (llvm::StringRef(S).endswith("nr"))
3754 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003755 }
Mike Stump1eb44332009-09-09 15:08:12 +00003756
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003757 if (PointeeTy->isCharType()) {
3758 // char pointer types should be encoded as '*' unless it is a
3759 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003760 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003761 S += '*';
3762 return;
3763 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003764 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003765 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3766 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3767 S += '#';
3768 return;
3769 }
3770 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3771 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3772 S += '@';
3773 return;
3774 }
3775 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003776 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003777 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003778 getLegacyIntegralTypeEncoding(PointeeTy);
3779
Mike Stump1eb44332009-09-09 15:08:12 +00003780 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003781 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003782 return;
3783 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003784
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003785 if (const ArrayType *AT =
3786 // Ignore type qualifiers etc.
3787 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003788 if (isa<IncompleteArrayType>(AT)) {
3789 // Incomplete arrays are encoded as a pointer to the array element.
3790 S += '^';
3791
Mike Stump1eb44332009-09-09 15:08:12 +00003792 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003793 false, ExpandStructures, FD);
3794 } else {
3795 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003796
Anders Carlsson559a8332009-02-22 01:38:57 +00003797 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3798 S += llvm::utostr(CAT->getSize().getZExtValue());
3799 else {
3800 //Variable length arrays are encoded as a regular array with 0 elements.
3801 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3802 S += '0';
3803 }
Mike Stump1eb44332009-09-09 15:08:12 +00003804
3805 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003806 false, ExpandStructures, FD);
3807 S += ']';
3808 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003809 return;
3810 }
Mike Stump1eb44332009-09-09 15:08:12 +00003811
John McCall183700f2009-09-21 23:43:11 +00003812 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003813 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003814 return;
3815 }
Mike Stump1eb44332009-09-09 15:08:12 +00003816
Ted Kremenek6217b802009-07-29 21:53:49 +00003817 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003818 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003819 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003820 // Anonymous structures print as '?'
3821 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3822 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003823 if (ClassTemplateSpecializationDecl *Spec
3824 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3825 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3826 std::string TemplateArgsStr
3827 = TemplateSpecializationType::PrintTemplateArgumentList(
3828 TemplateArgs.getFlatArgumentList(),
3829 TemplateArgs.flat_size(),
3830 (*this).PrintingPolicy);
3831
3832 S += TemplateArgsStr;
3833 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003834 } else {
3835 S += '?';
3836 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003837 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003838 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003839 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3840 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003841 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003842 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003843 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003844 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003845 S += '"';
3846 }
Mike Stump1eb44332009-09-09 15:08:12 +00003847
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003848 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003849 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003850 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003851 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003852 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003853 QualType qt = Field->getType();
3854 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003855 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003856 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003857 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003858 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003859 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003860 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003861 return;
3862 }
Mike Stump1eb44332009-09-09 15:08:12 +00003863
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003864 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003865 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003866 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003867 else
3868 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003869 return;
3870 }
Mike Stump1eb44332009-09-09 15:08:12 +00003871
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003872 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003873 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003874 return;
3875 }
Mike Stump1eb44332009-09-09 15:08:12 +00003876
John McCallc12c5bb2010-05-15 11:32:37 +00003877 // Ignore protocol qualifiers when mangling at this level.
3878 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3879 T = OT->getBaseType();
3880
John McCall0953e762009-09-24 19:53:00 +00003881 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003882 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003883 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003884 S += '{';
3885 const IdentifierInfo *II = OI->getIdentifier();
3886 S += II->getName();
3887 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003888 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003889 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003890 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003891 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003892 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003893 RecFields[i]);
3894 else
Mike Stump1eb44332009-09-09 15:08:12 +00003895 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003896 FD);
3897 }
3898 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003899 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003900 }
Mike Stump1eb44332009-09-09 15:08:12 +00003901
John McCall183700f2009-09-21 23:43:11 +00003902 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003903 if (OPT->isObjCIdType()) {
3904 S += '@';
3905 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003906 }
Mike Stump1eb44332009-09-09 15:08:12 +00003907
Steve Naroff27d20a22009-10-28 22:03:49 +00003908 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3909 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3910 // Since this is a binary compatibility issue, need to consult with runtime
3911 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003912 S += '#';
3913 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003914 }
Mike Stump1eb44332009-09-09 15:08:12 +00003915
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003916 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003917 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003918 ExpandPointedToStructures,
3919 ExpandStructures, FD);
3920 if (FD || EncodingProperty) {
3921 // Note that we do extended encoding of protocol qualifer list
3922 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003923 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003924 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3925 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003926 S += '<';
3927 S += (*I)->getNameAsString();
3928 S += '>';
3929 }
3930 S += '"';
3931 }
3932 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003933 }
Mike Stump1eb44332009-09-09 15:08:12 +00003934
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003935 QualType PointeeTy = OPT->getPointeeType();
3936 if (!EncodingProperty &&
3937 isa<TypedefType>(PointeeTy.getTypePtr())) {
3938 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003939 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003940 // {...};
3941 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003942 getObjCEncodingForTypeImpl(PointeeTy, S,
3943 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003944 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003945 return;
3946 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003947
3948 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003949 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003950 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003951 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003952 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3953 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003954 S += '<';
3955 S += (*I)->getNameAsString();
3956 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003957 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003958 S += '"';
3959 }
3960 return;
3961 }
Mike Stump1eb44332009-09-09 15:08:12 +00003962
John McCall532ec7b2010-05-17 23:56:34 +00003963 // gcc just blithely ignores member pointers.
3964 // TODO: maybe there should be a mangling for these
3965 if (T->getAs<MemberPointerType>())
3966 return;
3967
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003968 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003969}
3970
Mike Stump1eb44332009-09-09 15:08:12 +00003971void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003972 std::string& S) const {
3973 if (QT & Decl::OBJC_TQ_In)
3974 S += 'n';
3975 if (QT & Decl::OBJC_TQ_Inout)
3976 S += 'N';
3977 if (QT & Decl::OBJC_TQ_Out)
3978 S += 'o';
3979 if (QT & Decl::OBJC_TQ_Bycopy)
3980 S += 'O';
3981 if (QT & Decl::OBJC_TQ_Byref)
3982 S += 'R';
3983 if (QT & Decl::OBJC_TQ_Oneway)
3984 S += 'V';
3985}
3986
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003987void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003988 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003989
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003990 BuiltinVaListType = T;
3991}
3992
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003993void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003994 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003995}
3996
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003997void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003998 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003999}
4000
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004001void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004002 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004003}
4004
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004005void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004006 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004007}
4008
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004009void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004010 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004011 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004012
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004013 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004014}
4015
John McCall0bd6feb2009-12-02 08:04:21 +00004016/// \brief Retrieve the template name that corresponds to a non-empty
4017/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00004018TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4019 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00004020 unsigned size = End - Begin;
4021 assert(size > 1 && "set is not overloaded!");
4022
4023 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4024 size * sizeof(FunctionTemplateDecl*));
4025 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4026
4027 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004028 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004029 NamedDecl *D = *I;
4030 assert(isa<FunctionTemplateDecl>(D) ||
4031 (isa<UsingShadowDecl>(D) &&
4032 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4033 *Storage++ = D;
4034 }
4035
4036 return TemplateName(OT);
4037}
4038
Douglas Gregor7532dc62009-03-30 22:58:21 +00004039/// \brief Retrieve the template name that represents a qualified
4040/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00004041TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004042 bool TemplateKeyword,
4043 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004044 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004045 llvm::FoldingSetNodeID ID;
4046 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4047
4048 void *InsertPos = 0;
4049 QualifiedTemplateName *QTN =
4050 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4051 if (!QTN) {
4052 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4053 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4054 }
4055
4056 return TemplateName(QTN);
4057}
4058
4059/// \brief Retrieve the template name that represents a dependent
4060/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00004061TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004062 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004063 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004064 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004065
4066 llvm::FoldingSetNodeID ID;
4067 DependentTemplateName::Profile(ID, NNS, Name);
4068
4069 void *InsertPos = 0;
4070 DependentTemplateName *QTN =
4071 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4072
4073 if (QTN)
4074 return TemplateName(QTN);
4075
4076 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4077 if (CanonNNS == NNS) {
4078 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4079 } else {
4080 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4081 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004082 DependentTemplateName *CheckQTN =
4083 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4084 assert(!CheckQTN && "Dependent type name canonicalization broken");
4085 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004086 }
4087
4088 DependentTemplateNames.InsertNode(QTN, InsertPos);
4089 return TemplateName(QTN);
4090}
4091
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004092/// \brief Retrieve the template name that represents a dependent
4093/// template name such as \c MetaFun::template operator+.
4094TemplateName
4095ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4096 OverloadedOperatorKind Operator) {
4097 assert((!NNS || NNS->isDependent()) &&
4098 "Nested name specifier must be dependent");
4099
4100 llvm::FoldingSetNodeID ID;
4101 DependentTemplateName::Profile(ID, NNS, Operator);
4102
4103 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004104 DependentTemplateName *QTN
4105 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004106
4107 if (QTN)
4108 return TemplateName(QTN);
4109
4110 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4111 if (CanonNNS == NNS) {
4112 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4113 } else {
4114 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4115 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004116
4117 DependentTemplateName *CheckQTN
4118 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4119 assert(!CheckQTN && "Dependent template name canonicalization broken");
4120 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004121 }
4122
4123 DependentTemplateNames.InsertNode(QTN, InsertPos);
4124 return TemplateName(QTN);
4125}
4126
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004127/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004128/// TargetInfo, produce the corresponding type. The unsigned @p Type
4129/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004130CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004131 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004132 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004133 case TargetInfo::SignedShort: return ShortTy;
4134 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4135 case TargetInfo::SignedInt: return IntTy;
4136 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4137 case TargetInfo::SignedLong: return LongTy;
4138 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4139 case TargetInfo::SignedLongLong: return LongLongTy;
4140 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4141 }
4142
4143 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004144 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004145}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004146
4147//===----------------------------------------------------------------------===//
4148// Type Predicates.
4149//===----------------------------------------------------------------------===//
4150
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004151/// isObjCNSObjectType - Return true if this is an NSObject object using
4152/// NSObject attribute on a c-style pointer type.
4153/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004154/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004155///
4156bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4157 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4158 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004159 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004160 return true;
4161 }
Mike Stump1eb44332009-09-09 15:08:12 +00004162 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004163}
4164
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004165/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4166/// garbage collection attribute.
4167///
John McCall0953e762009-09-24 19:53:00 +00004168Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4169 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004170 if (getLangOptions().ObjC1 &&
4171 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004172 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004173 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004174 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004175 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004176 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004177 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004178 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004179 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004180 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004181 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004182 // Non-pointers have none gc'able attribute regardless of the attribute
4183 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004184 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004185 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004186 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004187 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004188}
4189
Chris Lattner6ac46a42008-04-07 06:51:04 +00004190//===----------------------------------------------------------------------===//
4191// Type Compatibility Testing
4192//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004193
Mike Stump1eb44332009-09-09 15:08:12 +00004194/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004195/// compatible.
4196static bool areCompatVectorTypes(const VectorType *LHS,
4197 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004198 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004199 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004200 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004201}
4202
Steve Naroff4084c302009-07-23 01:01:38 +00004203//===----------------------------------------------------------------------===//
4204// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4205//===----------------------------------------------------------------------===//
4206
4207/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4208/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004209bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4210 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004211 if (lProto == rProto)
4212 return true;
4213 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4214 E = rProto->protocol_end(); PI != E; ++PI)
4215 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4216 return true;
4217 return false;
4218}
4219
Steve Naroff4084c302009-07-23 01:01:38 +00004220/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4221/// return true if lhs's protocols conform to rhs's protocol; false
4222/// otherwise.
4223bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4224 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4225 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4226 return false;
4227}
4228
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004229/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4230/// Class<p1, ...>.
4231bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4232 QualType rhs) {
4233 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4234 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4235 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4236
4237 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4238 E = lhsQID->qual_end(); I != E; ++I) {
4239 bool match = false;
4240 ObjCProtocolDecl *lhsProto = *I;
4241 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4242 E = rhsOPT->qual_end(); J != E; ++J) {
4243 ObjCProtocolDecl *rhsProto = *J;
4244 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4245 match = true;
4246 break;
4247 }
4248 }
4249 if (!match)
4250 return false;
4251 }
4252 return true;
4253}
4254
Steve Naroff4084c302009-07-23 01:01:38 +00004255/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4256/// ObjCQualifiedIDType.
4257bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4258 bool compare) {
4259 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004260 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004261 lhs->isObjCIdType() || lhs->isObjCClassType())
4262 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004263 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004264 rhs->isObjCIdType() || rhs->isObjCClassType())
4265 return true;
4266
4267 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004268 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004269
Steve Naroff4084c302009-07-23 01:01:38 +00004270 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004271
Steve Naroff4084c302009-07-23 01:01:38 +00004272 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004273 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004274 // make sure we check the class hierarchy.
4275 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4276 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4277 E = lhsQID->qual_end(); I != E; ++I) {
4278 // when comparing an id<P> on lhs with a static type on rhs,
4279 // see if static class implements all of id's protocols, directly or
4280 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004281 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004282 return false;
4283 }
4284 }
4285 // If there are no qualifiers and no interface, we have an 'id'.
4286 return true;
4287 }
Mike Stump1eb44332009-09-09 15:08:12 +00004288 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004289 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4290 E = lhsQID->qual_end(); I != E; ++I) {
4291 ObjCProtocolDecl *lhsProto = *I;
4292 bool match = false;
4293
4294 // when comparing an id<P> on lhs with a static type on rhs,
4295 // see if static class implements all of id's protocols, directly or
4296 // through its super class and categories.
4297 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4298 E = rhsOPT->qual_end(); J != E; ++J) {
4299 ObjCProtocolDecl *rhsProto = *J;
4300 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4301 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4302 match = true;
4303 break;
4304 }
4305 }
Mike Stump1eb44332009-09-09 15:08:12 +00004306 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004307 // make sure we check the class hierarchy.
4308 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4309 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4310 E = lhsQID->qual_end(); I != E; ++I) {
4311 // when comparing an id<P> on lhs with a static type on rhs,
4312 // see if static class implements all of id's protocols, directly or
4313 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004314 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004315 match = true;
4316 break;
4317 }
4318 }
4319 }
4320 if (!match)
4321 return false;
4322 }
Mike Stump1eb44332009-09-09 15:08:12 +00004323
Steve Naroff4084c302009-07-23 01:01:38 +00004324 return true;
4325 }
Mike Stump1eb44332009-09-09 15:08:12 +00004326
Steve Naroff4084c302009-07-23 01:01:38 +00004327 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4328 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4329
Mike Stump1eb44332009-09-09 15:08:12 +00004330 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004331 lhs->getAsObjCInterfacePointerType()) {
4332 if (lhsOPT->qual_empty()) {
4333 bool match = false;
4334 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4335 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4336 E = rhsQID->qual_end(); I != E; ++I) {
4337 // when comparing an id<P> on lhs with a static type on rhs,
4338 // see if static class implements all of id's protocols, directly or
4339 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004340 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004341 match = true;
4342 break;
4343 }
4344 }
4345 if (!match)
4346 return false;
4347 }
4348 return true;
4349 }
Mike Stump1eb44332009-09-09 15:08:12 +00004350 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004351 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4352 E = lhsOPT->qual_end(); I != E; ++I) {
4353 ObjCProtocolDecl *lhsProto = *I;
4354 bool match = false;
4355
4356 // when comparing an id<P> on lhs with a static type on rhs,
4357 // see if static class implements all of id's protocols, directly or
4358 // through its super class and categories.
4359 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4360 E = rhsQID->qual_end(); J != E; ++J) {
4361 ObjCProtocolDecl *rhsProto = *J;
4362 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4363 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4364 match = true;
4365 break;
4366 }
4367 }
4368 if (!match)
4369 return false;
4370 }
4371 return true;
4372 }
4373 return false;
4374}
4375
Eli Friedman3d815e72008-08-22 00:56:42 +00004376/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004377/// compatible for assignment from RHS to LHS. This handles validation of any
4378/// protocol qualifiers on the LHS or RHS.
4379///
Steve Naroff14108da2009-07-10 23:34:53 +00004380bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4381 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004382 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4383 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4384
Steve Naroffde2e22d2009-07-15 18:40:39 +00004385 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004386 if (LHS->isObjCUnqualifiedIdOrClass() ||
4387 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004388 return true;
4389
John McCallc12c5bb2010-05-15 11:32:37 +00004390 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004391 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4392 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004393 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004394
4395 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4396 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4397 QualType(RHSOPT,0));
4398
John McCallc12c5bb2010-05-15 11:32:37 +00004399 // If we have 2 user-defined types, fall into that path.
4400 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004401 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004402
Steve Naroff4084c302009-07-23 01:01:38 +00004403 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004404}
4405
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004406/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4407/// for providing type-safty for objective-c pointers used to pass/return
4408/// arguments in block literals. When passed as arguments, passing 'A*' where
4409/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4410/// not OK. For the return type, the opposite is not OK.
4411bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4412 const ObjCObjectPointerType *LHSOPT,
4413 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004414 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004415 return true;
4416
4417 if (LHSOPT->isObjCBuiltinType()) {
4418 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4419 }
4420
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004421 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004422 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4423 QualType(RHSOPT,0),
4424 false);
4425
4426 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4427 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4428 if (LHS && RHS) { // We have 2 user-defined types.
4429 if (LHS != RHS) {
4430 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4431 return false;
4432 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4433 return true;
4434 }
4435 else
4436 return true;
4437 }
4438 return false;
4439}
4440
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004441/// getIntersectionOfProtocols - This routine finds the intersection of set
4442/// of protocols inherited from two distinct objective-c pointer objects.
4443/// It is used to build composite qualifier list of the composite type of
4444/// the conditional expression involving two objective-c pointer objects.
4445static
4446void getIntersectionOfProtocols(ASTContext &Context,
4447 const ObjCObjectPointerType *LHSOPT,
4448 const ObjCObjectPointerType *RHSOPT,
4449 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4450
John McCallc12c5bb2010-05-15 11:32:37 +00004451 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4452 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4453 assert(LHS->getInterface() && "LHS must have an interface base");
4454 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004455
4456 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4457 unsigned LHSNumProtocols = LHS->getNumProtocols();
4458 if (LHSNumProtocols > 0)
4459 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4460 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004461 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004462 Context.CollectInheritedProtocols(LHS->getInterface(),
4463 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004464 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4465 LHSInheritedProtocols.end());
4466 }
4467
4468 unsigned RHSNumProtocols = RHS->getNumProtocols();
4469 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004470 ObjCProtocolDecl **RHSProtocols =
4471 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004472 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4473 if (InheritedProtocolSet.count(RHSProtocols[i]))
4474 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4475 }
4476 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004477 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004478 Context.CollectInheritedProtocols(RHS->getInterface(),
4479 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004480 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4481 RHSInheritedProtocols.begin(),
4482 E = RHSInheritedProtocols.end(); I != E; ++I)
4483 if (InheritedProtocolSet.count((*I)))
4484 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004485 }
4486}
4487
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004488/// areCommonBaseCompatible - Returns common base class of the two classes if
4489/// one found. Note that this is O'2 algorithm. But it will be called as the
4490/// last type comparison in a ?-exp of ObjC pointer types before a
4491/// warning is issued. So, its invokation is extremely rare.
4492QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004493 const ObjCObjectPointerType *Lptr,
4494 const ObjCObjectPointerType *Rptr) {
4495 const ObjCObjectType *LHS = Lptr->getObjectType();
4496 const ObjCObjectType *RHS = Rptr->getObjectType();
4497 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4498 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4499 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004500 return QualType();
4501
John McCallc12c5bb2010-05-15 11:32:37 +00004502 while ((LDecl = LDecl->getSuperClass())) {
4503 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004504 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004505 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4506 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4507
4508 QualType Result = QualType(LHS, 0);
4509 if (!Protocols.empty())
4510 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4511 Result = getObjCObjectPointerType(Result);
4512 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004513 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004514 }
4515
4516 return QualType();
4517}
4518
John McCallc12c5bb2010-05-15 11:32:37 +00004519bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4520 const ObjCObjectType *RHS) {
4521 assert(LHS->getInterface() && "LHS is not an interface type");
4522 assert(RHS->getInterface() && "RHS is not an interface type");
4523
Chris Lattner6ac46a42008-04-07 06:51:04 +00004524 // Verify that the base decls are compatible: the RHS must be a subclass of
4525 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004526 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004527 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004528
Chris Lattner6ac46a42008-04-07 06:51:04 +00004529 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4530 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004531 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004532 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004533
Chris Lattner6ac46a42008-04-07 06:51:04 +00004534 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4535 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004536 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004537 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004538
John McCallc12c5bb2010-05-15 11:32:37 +00004539 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4540 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004541 LHSPI != LHSPE; LHSPI++) {
4542 bool RHSImplementsProtocol = false;
4543
4544 // If the RHS doesn't implement the protocol on the left, the types
4545 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004546 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4547 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004548 RHSPI != RHSPE; RHSPI++) {
4549 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004550 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004551 break;
4552 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004553 }
4554 // FIXME: For better diagnostics, consider passing back the protocol name.
4555 if (!RHSImplementsProtocol)
4556 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004557 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004558 // The RHS implements all protocols listed on the LHS.
4559 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004560}
4561
Steve Naroff389bf462009-02-12 17:52:19 +00004562bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4563 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004564 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4565 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004566
Steve Naroff14108da2009-07-10 23:34:53 +00004567 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004568 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004569
4570 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4571 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004572}
4573
Mike Stump1eb44332009-09-09 15:08:12 +00004574/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004575/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004576/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004577/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004578bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004579 if (getLangOptions().CPlusPlus)
4580 return hasSameType(LHS, RHS);
4581
Eli Friedman3d815e72008-08-22 00:56:42 +00004582 return !mergeTypes(LHS, RHS).isNull();
4583}
4584
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004585bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4586 return !mergeTypes(LHS, RHS, true).isNull();
4587}
4588
4589QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4590 bool OfBlockPointer) {
John McCall183700f2009-09-21 23:43:11 +00004591 const FunctionType *lbase = lhs->getAs<FunctionType>();
4592 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004593 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4594 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004595 bool allLTypes = true;
4596 bool allRTypes = true;
4597
4598 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004599 QualType retType;
4600 if (OfBlockPointer)
4601 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4602 else
4603 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman3d815e72008-08-22 00:56:42 +00004604 if (retType.isNull()) return QualType();
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004605 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004606 allLTypes = false;
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004607 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004608 allRTypes = false;
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004609 // FIXME: double check this
4610 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4611 // rbase->getRegParmAttr() != 0 &&
4612 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004613 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4614 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004615 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4616 lbaseInfo.getRegParm();
4617 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4618 if (NoReturn != lbaseInfo.getNoReturn() ||
4619 RegParm != lbaseInfo.getRegParm())
4620 allLTypes = false;
4621 if (NoReturn != rbaseInfo.getNoReturn() ||
4622 RegParm != rbaseInfo.getRegParm())
4623 allRTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004624 CallingConv lcc = lbaseInfo.getCC();
4625 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004626 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004627 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004628 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004629
Eli Friedman3d815e72008-08-22 00:56:42 +00004630 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004631 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4632 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004633 unsigned lproto_nargs = lproto->getNumArgs();
4634 unsigned rproto_nargs = rproto->getNumArgs();
4635
4636 // Compatible functions must have the same number of arguments
4637 if (lproto_nargs != rproto_nargs)
4638 return QualType();
4639
4640 // Variadic and non-variadic functions aren't compatible
4641 if (lproto->isVariadic() != rproto->isVariadic())
4642 return QualType();
4643
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004644 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4645 return QualType();
4646
Eli Friedman3d815e72008-08-22 00:56:42 +00004647 // Check argument compatibility
4648 llvm::SmallVector<QualType, 10> types;
4649 for (unsigned i = 0; i < lproto_nargs; i++) {
4650 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4651 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004652 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman3d815e72008-08-22 00:56:42 +00004653 if (argtype.isNull()) return QualType();
4654 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004655 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4656 allLTypes = false;
4657 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4658 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004659 }
4660 if (allLTypes) return lhs;
4661 if (allRTypes) return rhs;
4662 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004663 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004664 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004665 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004666 }
4667
4668 if (lproto) allRTypes = false;
4669 if (rproto) allLTypes = false;
4670
Douglas Gregor72564e72009-02-26 23:50:07 +00004671 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004672 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004673 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004674 if (proto->isVariadic()) return QualType();
4675 // Check that the types are compatible with the types that
4676 // would result from default argument promotions (C99 6.7.5.3p15).
4677 // The only types actually affected are promotable integer
4678 // types and floats, which would be passed as a different
4679 // type depending on whether the prototype is visible.
4680 unsigned proto_nargs = proto->getNumArgs();
4681 for (unsigned i = 0; i < proto_nargs; ++i) {
4682 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004683
4684 // Look at the promotion type of enum types, since that is the type used
4685 // to pass enum values.
4686 if (const EnumType *Enum = argTy->getAs<EnumType>())
4687 argTy = Enum->getDecl()->getPromotionType();
4688
Eli Friedman3d815e72008-08-22 00:56:42 +00004689 if (argTy->isPromotableIntegerType() ||
4690 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4691 return QualType();
4692 }
4693
4694 if (allLTypes) return lhs;
4695 if (allRTypes) return rhs;
4696 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004697 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004698 proto->getTypeQuals(),
4699 false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00004700 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004701 }
4702
4703 if (allLTypes) return lhs;
4704 if (allRTypes) return rhs;
Rafael Espindola425ef722010-03-30 22:15:11 +00004705 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindola264ba482010-03-30 20:24:48 +00004706 return getFunctionNoProtoType(retType, Info);
Eli Friedman3d815e72008-08-22 00:56:42 +00004707}
4708
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004709QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4710 bool OfBlockPointer) {
Bill Wendling43d69752007-12-03 07:33:35 +00004711 // C++ [expr]: If an expression initially has the type "reference to T", the
4712 // type is adjusted to "T" prior to any further analysis, the expression
4713 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004714 // expression is an lvalue unless the reference is an rvalue reference and
4715 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004716 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4717 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4718
Eli Friedman3d815e72008-08-22 00:56:42 +00004719 QualType LHSCan = getCanonicalType(LHS),
4720 RHSCan = getCanonicalType(RHS);
4721
4722 // If two types are identical, they are compatible.
4723 if (LHSCan == RHSCan)
4724 return LHS;
4725
John McCall0953e762009-09-24 19:53:00 +00004726 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004727 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4728 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004729 if (LQuals != RQuals) {
4730 // If any of these qualifiers are different, we have a type
4731 // mismatch.
4732 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4733 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4734 return QualType();
4735
4736 // Exactly one GC qualifier difference is allowed: __strong is
4737 // okay if the other type has no GC qualifier but is an Objective
4738 // C object pointer (i.e. implicitly strong by default). We fix
4739 // this by pretending that the unqualified type was actually
4740 // qualified __strong.
4741 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4742 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4743 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4744
4745 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4746 return QualType();
4747
4748 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4749 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4750 }
4751 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4752 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4753 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004754 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004755 }
4756
4757 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004758
Eli Friedman852d63b2009-06-01 01:22:52 +00004759 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4760 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004761
Chris Lattner1adb8832008-01-14 05:45:46 +00004762 // We want to consider the two function types to be the same for these
4763 // comparisons, just force one to the other.
4764 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4765 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004766
4767 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004768 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4769 LHSClass = Type::ConstantArray;
4770 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4771 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004772
John McCallc12c5bb2010-05-15 11:32:37 +00004773 // ObjCInterfaces are just specialized ObjCObjects.
4774 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4775 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4776
Nate Begeman213541a2008-04-18 23:10:10 +00004777 // Canonicalize ExtVector -> Vector.
4778 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4779 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004780
Chris Lattnera36a61f2008-04-07 05:43:21 +00004781 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004782 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004783 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004784 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004785 // Compatibility is based on the underlying type, not the promotion
4786 // type.
John McCall183700f2009-09-21 23:43:11 +00004787 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004788 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4789 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004790 }
John McCall183700f2009-09-21 23:43:11 +00004791 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004792 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4793 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004794 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004795
Eli Friedman3d815e72008-08-22 00:56:42 +00004796 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004797 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004798
Steve Naroff4a746782008-01-09 22:43:08 +00004799 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004800 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004801#define TYPE(Class, Base)
4802#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004803#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004804#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4805#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4806#include "clang/AST/TypeNodes.def"
4807 assert(false && "Non-canonical and dependent types shouldn't get here");
4808 return QualType();
4809
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004810 case Type::LValueReference:
4811 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004812 case Type::MemberPointer:
4813 assert(false && "C++ should never be in mergeTypes");
4814 return QualType();
4815
John McCallc12c5bb2010-05-15 11:32:37 +00004816 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00004817 case Type::IncompleteArray:
4818 case Type::VariableArray:
4819 case Type::FunctionProto:
4820 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004821 assert(false && "Types are eliminated above");
4822 return QualType();
4823
Chris Lattner1adb8832008-01-14 05:45:46 +00004824 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004825 {
4826 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004827 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4828 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004829 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4830 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004831 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004832 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004833 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004834 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004835 return getPointerType(ResultType);
4836 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004837 case Type::BlockPointer:
4838 {
4839 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004840 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4841 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004842 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroffc0febd52008-12-10 17:49:55 +00004843 if (ResultType.isNull()) return QualType();
4844 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4845 return LHS;
4846 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4847 return RHS;
4848 return getBlockPointerType(ResultType);
4849 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004850 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004851 {
4852 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4853 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4854 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4855 return QualType();
4856
4857 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4858 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4859 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4860 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004861 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4862 return LHS;
4863 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4864 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004865 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4866 ArrayType::ArraySizeModifier(), 0);
4867 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4868 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004869 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4870 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004871 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4872 return LHS;
4873 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4874 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004875 if (LVAT) {
4876 // FIXME: This isn't correct! But tricky to implement because
4877 // the array's size has to be the size of LHS, but the type
4878 // has to be different.
4879 return LHS;
4880 }
4881 if (RVAT) {
4882 // FIXME: This isn't correct! But tricky to implement because
4883 // the array's size has to be the size of RHS, but the type
4884 // has to be different.
4885 return RHS;
4886 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004887 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4888 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004889 return getIncompleteArrayType(ResultType,
4890 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004891 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004892 case Type::FunctionNoProto:
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004893 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregor72564e72009-02-26 23:50:07 +00004894 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004895 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004896 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004897 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004898 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004899 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004900 case Type::Complex:
4901 // Distinct complex types are incompatible.
4902 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004903 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004904 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00004905 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4906 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004907 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004908 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00004909 case Type::ObjCObject: {
4910 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004911 // FIXME: This should be type compatibility, e.g. whether
4912 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00004913 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4914 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4915 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00004916 return LHS;
4917
Eli Friedman3d815e72008-08-22 00:56:42 +00004918 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004919 }
Steve Naroff14108da2009-07-10 23:34:53 +00004920 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004921 if (OfBlockPointer) {
4922 if (canAssignObjCInterfacesInBlockPointer(
4923 LHS->getAs<ObjCObjectPointerType>(),
4924 RHS->getAs<ObjCObjectPointerType>()))
4925 return LHS;
4926 return QualType();
4927 }
John McCall183700f2009-09-21 23:43:11 +00004928 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4929 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004930 return LHS;
4931
Steve Naroffbc76dd02008-12-10 22:14:21 +00004932 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004933 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004934 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004935
4936 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004937}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004938
Fariborz Jahanian2390a722010-05-19 21:37:30 +00004939/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4940/// 'RHS' attributes and returns the merged version; including for function
4941/// return types.
4942QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4943 QualType LHSCan = getCanonicalType(LHS),
4944 RHSCan = getCanonicalType(RHS);
4945 // If two types are identical, they are compatible.
4946 if (LHSCan == RHSCan)
4947 return LHS;
4948 if (RHSCan->isFunctionType()) {
4949 if (!LHSCan->isFunctionType())
4950 return QualType();
4951 QualType OldReturnType =
4952 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4953 QualType NewReturnType =
4954 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4955 QualType ResReturnType =
4956 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4957 if (ResReturnType.isNull())
4958 return QualType();
4959 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4960 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4961 // In either case, use OldReturnType to build the new function type.
4962 const FunctionType *F = LHS->getAs<FunctionType>();
4963 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4964 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4965 QualType ResultType
4966 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4967 FPT->getNumArgs(), FPT->isVariadic(),
4968 FPT->getTypeQuals(),
4969 FPT->hasExceptionSpec(),
4970 FPT->hasAnyExceptionSpec(),
4971 FPT->getNumExceptions(),
4972 FPT->exception_begin(),
4973 Info);
4974 return ResultType;
4975 }
4976 }
4977 return QualType();
4978 }
4979
4980 // If the qualifiers are different, the types can still be merged.
4981 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4982 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4983 if (LQuals != RQuals) {
4984 // If any of these qualifiers are different, we have a type mismatch.
4985 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4986 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4987 return QualType();
4988
4989 // Exactly one GC qualifier difference is allowed: __strong is
4990 // okay if the other type has no GC qualifier but is an Objective
4991 // C object pointer (i.e. implicitly strong by default). We fix
4992 // this by pretending that the unqualified type was actually
4993 // qualified __strong.
4994 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4995 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4996 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4997
4998 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4999 return QualType();
5000
5001 if (GC_L == Qualifiers::Strong)
5002 return LHS;
5003 if (GC_R == Qualifiers::Strong)
5004 return RHS;
5005 return QualType();
5006 }
5007
5008 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5009 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5010 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5011 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5012 if (ResQT == LHSBaseQT)
5013 return LHS;
5014 if (ResQT == RHSBaseQT)
5015 return RHS;
5016 }
5017 return QualType();
5018}
5019
Chris Lattner5426bf62008-04-07 07:01:58 +00005020//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005021// Integer Predicates
5022//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005023
Eli Friedmanad74a752008-06-28 06:23:08 +00005024unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00005025 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00005026 return 1;
John McCall842aef82009-12-09 09:09:27 +00005027 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005028 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00005029 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005030 return (unsigned)getTypeSize(T);
5031}
5032
5033QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
5034 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005035
5036 // Turn <4 x signed int> -> <4 x unsigned int>
5037 if (const VectorType *VTy = T->getAs<VectorType>())
5038 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner788b0fd2010-06-23 06:00:24 +00005039 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005040
5041 // For enums, we return the unsigned version of the base type.
5042 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005043 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005044
5045 const BuiltinType *BTy = T->getAs<BuiltinType>();
5046 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005047 switch (BTy->getKind()) {
5048 case BuiltinType::Char_S:
5049 case BuiltinType::SChar:
5050 return UnsignedCharTy;
5051 case BuiltinType::Short:
5052 return UnsignedShortTy;
5053 case BuiltinType::Int:
5054 return UnsignedIntTy;
5055 case BuiltinType::Long:
5056 return UnsignedLongTy;
5057 case BuiltinType::LongLong:
5058 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005059 case BuiltinType::Int128:
5060 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005061 default:
5062 assert(0 && "Unexpected signed integer type");
5063 return QualType();
5064 }
5065}
5066
Douglas Gregor2cf26342009-04-09 22:27:44 +00005067ExternalASTSource::~ExternalASTSource() { }
5068
5069void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005070
5071
5072//===----------------------------------------------------------------------===//
5073// Builtin Type Computation
5074//===----------------------------------------------------------------------===//
5075
5076/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5077/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00005078static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005079 ASTContext::GetBuiltinTypeError &Error,
5080 bool AllowTypeModifiers = true) {
5081 // Modifiers.
5082 int HowLong = 0;
5083 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005084
Chris Lattner86df27b2009-06-14 00:45:47 +00005085 // Read the modifiers first.
5086 bool Done = false;
5087 while (!Done) {
5088 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005089 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005090 case 'S':
5091 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5092 assert(!Signed && "Can't use 'S' modifier multiple times!");
5093 Signed = true;
5094 break;
5095 case 'U':
5096 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5097 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5098 Unsigned = true;
5099 break;
5100 case 'L':
5101 assert(HowLong <= 2 && "Can't have LLLL modifier");
5102 ++HowLong;
5103 break;
5104 }
5105 }
5106
5107 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005108
Chris Lattner86df27b2009-06-14 00:45:47 +00005109 // Read the base type.
5110 switch (*Str++) {
5111 default: assert(0 && "Unknown builtin type letter!");
5112 case 'v':
5113 assert(HowLong == 0 && !Signed && !Unsigned &&
5114 "Bad modifiers used with 'v'!");
5115 Type = Context.VoidTy;
5116 break;
5117 case 'f':
5118 assert(HowLong == 0 && !Signed && !Unsigned &&
5119 "Bad modifiers used with 'f'!");
5120 Type = Context.FloatTy;
5121 break;
5122 case 'd':
5123 assert(HowLong < 2 && !Signed && !Unsigned &&
5124 "Bad modifiers used with 'd'!");
5125 if (HowLong)
5126 Type = Context.LongDoubleTy;
5127 else
5128 Type = Context.DoubleTy;
5129 break;
5130 case 's':
5131 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5132 if (Unsigned)
5133 Type = Context.UnsignedShortTy;
5134 else
5135 Type = Context.ShortTy;
5136 break;
5137 case 'i':
5138 if (HowLong == 3)
5139 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5140 else if (HowLong == 2)
5141 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5142 else if (HowLong == 1)
5143 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5144 else
5145 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5146 break;
5147 case 'c':
5148 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5149 if (Signed)
5150 Type = Context.SignedCharTy;
5151 else if (Unsigned)
5152 Type = Context.UnsignedCharTy;
5153 else
5154 Type = Context.CharTy;
5155 break;
5156 case 'b': // boolean
5157 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5158 Type = Context.BoolTy;
5159 break;
5160 case 'z': // size_t.
5161 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5162 Type = Context.getSizeType();
5163 break;
5164 case 'F':
5165 Type = Context.getCFConstantStringType();
5166 break;
5167 case 'a':
5168 Type = Context.getBuiltinVaListType();
5169 assert(!Type.isNull() && "builtin va list type not initialized!");
5170 break;
5171 case 'A':
5172 // This is a "reference" to a va_list; however, what exactly
5173 // this means depends on how va_list is defined. There are two
5174 // different kinds of va_list: ones passed by value, and ones
5175 // passed by reference. An example of a by-value va_list is
5176 // x86, where va_list is a char*. An example of by-ref va_list
5177 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5178 // we want this argument to be a char*&; for x86-64, we want
5179 // it to be a __va_list_tag*.
5180 Type = Context.getBuiltinVaListType();
5181 assert(!Type.isNull() && "builtin va list type not initialized!");
5182 if (Type->isArrayType()) {
5183 Type = Context.getArrayDecayedType(Type);
5184 } else {
5185 Type = Context.getLValueReferenceType(Type);
5186 }
5187 break;
5188 case 'V': {
5189 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005190 unsigned NumElements = strtoul(Str, &End, 10);
5191 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00005192
Chris Lattner86df27b2009-06-14 00:45:47 +00005193 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005194
Chris Lattner86df27b2009-06-14 00:45:47 +00005195 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00005196 // FIXME: Don't know what to do about AltiVec.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005197 Type = Context.getVectorType(ElementType, NumElements,
5198 VectorType::NotAltiVec);
Chris Lattner86df27b2009-06-14 00:45:47 +00005199 break;
5200 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005201 case 'X': {
5202 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5203 Type = Context.getComplexType(ElementType);
5204 break;
5205 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005206 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005207 Type = Context.getFILEType();
5208 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005209 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005210 return QualType();
5211 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005212 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005213 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005214 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005215 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005216 else
5217 Type = Context.getjmp_bufType();
5218
Mike Stumpfd612db2009-07-28 23:47:15 +00005219 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005220 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005221 return QualType();
5222 }
5223 break;
Mike Stump782fa302009-07-28 02:25:19 +00005224 }
Mike Stump1eb44332009-09-09 15:08:12 +00005225
Chris Lattner86df27b2009-06-14 00:45:47 +00005226 if (!AllowTypeModifiers)
5227 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005228
Chris Lattner86df27b2009-06-14 00:45:47 +00005229 Done = false;
5230 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005231 switch (char c = *Str++) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005232 default: Done = true; --Str; break;
5233 case '*':
Chris Lattner86df27b2009-06-14 00:45:47 +00005234 case '&':
John McCall187ab372010-03-12 04:21:28 +00005235 {
5236 // Both pointers and references can have their pointee types
5237 // qualified with an address space.
5238 char *End;
5239 unsigned AddrSpace = strtoul(Str, &End, 10);
5240 if (End != Str && AddrSpace != 0) {
5241 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5242 Str = End;
5243 }
5244 }
5245 if (c == '*')
5246 Type = Context.getPointerType(Type);
5247 else
5248 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005249 break;
5250 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5251 case 'C':
John McCall0953e762009-09-24 19:53:00 +00005252 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00005253 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00005254 case 'D':
5255 Type = Context.getVolatileType(Type);
5256 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005257 }
5258 }
Mike Stump1eb44332009-09-09 15:08:12 +00005259
Chris Lattner86df27b2009-06-14 00:45:47 +00005260 return Type;
5261}
5262
5263/// GetBuiltinType - Return the type for the specified builtin.
5264QualType ASTContext::GetBuiltinType(unsigned id,
5265 GetBuiltinTypeError &Error) {
5266 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005267
Chris Lattner86df27b2009-06-14 00:45:47 +00005268 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005269
Chris Lattner86df27b2009-06-14 00:45:47 +00005270 Error = GE_None;
5271 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5272 if (Error != GE_None)
5273 return QualType();
5274 while (TypeStr[0] && TypeStr[0] != '.') {
5275 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5276 if (Error != GE_None)
5277 return QualType();
5278
5279 // Do array -> pointer decay. The builtin should use the decayed type.
5280 if (Ty->isArrayType())
5281 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005282
Chris Lattner86df27b2009-06-14 00:45:47 +00005283 ArgTypes.push_back(Ty);
5284 }
5285
5286 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5287 "'.' should only occur at end of builtin type list!");
5288
5289 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5290 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5291 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005292
5293 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005294 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005295 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00005296 FunctionType::ExtInfo());
Chris Lattner86df27b2009-06-14 00:45:47 +00005297}
Eli Friedmana95d7572009-08-19 07:44:53 +00005298
5299QualType
5300ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5301 // Perform the usual unary conversions. We do this early so that
5302 // integral promotions to "int" can allow us to exit early, in the
5303 // lhs == rhs check. Also, for conversion purposes, we ignore any
5304 // qualifiers. For example, "const float" and "float" are
5305 // equivalent.
5306 if (lhs->isPromotableIntegerType())
5307 lhs = getPromotedIntegerType(lhs);
5308 else
5309 lhs = lhs.getUnqualifiedType();
5310 if (rhs->isPromotableIntegerType())
5311 rhs = getPromotedIntegerType(rhs);
5312 else
5313 rhs = rhs.getUnqualifiedType();
5314
5315 // If both types are identical, no conversion is needed.
5316 if (lhs == rhs)
5317 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005318
Eli Friedmana95d7572009-08-19 07:44:53 +00005319 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5320 // The caller can deal with this (e.g. pointer + int).
5321 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5322 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005323
5324 // At this point, we have two different arithmetic types.
5325
Eli Friedmana95d7572009-08-19 07:44:53 +00005326 // Handle complex types first (C99 6.3.1.8p1).
5327 if (lhs->isComplexType() || rhs->isComplexType()) {
5328 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005329 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005330 // convert the rhs to the lhs complex type.
5331 return lhs;
5332 }
Mike Stump1eb44332009-09-09 15:08:12 +00005333 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005334 // convert the lhs to the rhs complex type.
5335 return rhs;
5336 }
5337 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005338 // When both operands are complex, the shorter operand is converted to the
5339 // type of the longer, and that is the type of the result. This corresponds
5340 // to what is done when combining two real floating-point operands.
5341 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005342 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005343 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005344 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005345 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005346 // "double _Complex" is promoted to "long double _Complex".
5347 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005348
5349 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005350 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005351 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005352 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005353 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005354 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5355 // domains match. This is a requirement for our implementation, C99
5356 // does not require this promotion.
5357 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5358 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5359 return rhs;
5360 } else { // handle "_Complex double, double".
5361 return lhs;
5362 }
5363 }
5364 return lhs; // The domain/size match exactly.
5365 }
5366 // Now handle "real" floating types (i.e. float, double, long double).
5367 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5368 // if we have an integer operand, the result is the real floating type.
5369 if (rhs->isIntegerType()) {
5370 // convert rhs to the lhs floating point type.
5371 return lhs;
5372 }
5373 if (rhs->isComplexIntegerType()) {
5374 // convert rhs to the complex floating point type.
5375 return getComplexType(lhs);
5376 }
5377 if (lhs->isIntegerType()) {
5378 // convert lhs to the rhs floating point type.
5379 return rhs;
5380 }
Mike Stump1eb44332009-09-09 15:08:12 +00005381 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005382 // convert lhs to the complex floating point type.
5383 return getComplexType(rhs);
5384 }
5385 // We have two real floating types, float/complex combos were handled above.
5386 // Convert the smaller operand to the bigger result.
5387 int result = getFloatingTypeOrder(lhs, rhs);
5388 if (result > 0) // convert the rhs
5389 return lhs;
5390 assert(result < 0 && "illegal float comparison");
5391 return rhs; // convert the lhs
5392 }
5393 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5394 // Handle GCC complex int extension.
5395 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5396 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5397
5398 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005399 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005400 rhsComplexInt->getElementType()) >= 0)
5401 return lhs; // convert the rhs
5402 return rhs;
5403 } else if (lhsComplexInt && rhs->isIntegerType()) {
5404 // convert the rhs to the lhs complex type.
5405 return lhs;
5406 } else if (rhsComplexInt && lhs->isIntegerType()) {
5407 // convert the lhs to the rhs complex type.
5408 return rhs;
5409 }
5410 }
5411 // Finally, we have two differing integer types.
5412 // The rules for this case are in C99 6.3.1.8
5413 int compare = getIntegerTypeOrder(lhs, rhs);
5414 bool lhsSigned = lhs->isSignedIntegerType(),
5415 rhsSigned = rhs->isSignedIntegerType();
5416 QualType destType;
5417 if (lhsSigned == rhsSigned) {
5418 // Same signedness; use the higher-ranked type
5419 destType = compare >= 0 ? lhs : rhs;
5420 } else if (compare != (lhsSigned ? 1 : -1)) {
5421 // The unsigned type has greater than or equal rank to the
5422 // signed type, so use the unsigned type
5423 destType = lhsSigned ? rhs : lhs;
5424 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5425 // The two types are different widths; if we are here, that
5426 // means the signed type is larger than the unsigned type, so
5427 // use the signed type.
5428 destType = lhsSigned ? lhs : rhs;
5429 } else {
5430 // The signed type is higher-ranked than the unsigned type,
5431 // but isn't actually any bigger (like unsigned int and long
5432 // on most 32-bit systems). Use the unsigned type corresponding
5433 // to the signed type.
5434 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5435 }
5436 return destType;
5437}