blob: fd5fd0e54b2d9b40352bcca8d2032e08e18f557e [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Charles Davis53c59df2010-08-16 03:33:14 +000033#include "CXXABI.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000034
Chris Lattnerddc135e2006-11-10 06:34:16 +000035using namespace clang;
36
Douglas Gregor9672f922010-07-03 00:47:00 +000037unsigned ASTContext::NumImplicitDefaultConstructors;
38unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000039unsigned ASTContext::NumImplicitCopyConstructors;
40unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000041unsigned ASTContext::NumImplicitCopyAssignmentOperators;
42unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000043unsigned ASTContext::NumImplicitDestructors;
44unsigned ASTContext::NumImplicitDestructorsDeclared;
45
Steve Naroff0af91202007-04-27 21:51:21 +000046enum FloatingRank {
47 FloatRank, DoubleRank, LongDoubleRank
48};
49
Douglas Gregor7dbfb462010-06-16 21:09:37 +000050void
51ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
52 TemplateTemplateParmDecl *Parm) {
53 ID.AddInteger(Parm->getDepth());
54 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000055 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000056
57 TemplateParameterList *Params = Parm->getTemplateParameters();
58 ID.AddInteger(Params->size());
59 for (TemplateParameterList::const_iterator P = Params->begin(),
60 PEnd = Params->end();
61 P != PEnd; ++P) {
62 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
63 ID.AddInteger(0);
64 ID.AddBoolean(TTP->isParameterPack());
65 continue;
66 }
67
68 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
69 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000070 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000071 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +000072 if (NTTP->isExpandedParameterPack()) {
73 ID.AddBoolean(true);
74 ID.AddInteger(NTTP->getNumExpansionTypes());
75 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
76 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
77 } else
78 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +000079 continue;
80 }
81
82 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
83 ID.AddInteger(2);
84 Profile(ID, TTP);
85 }
86}
87
88TemplateTemplateParmDecl *
89ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000090 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000091 // Check if we already have a canonical template template parameter.
92 llvm::FoldingSetNodeID ID;
93 CanonicalTemplateTemplateParm::Profile(ID, TTP);
94 void *InsertPos = 0;
95 CanonicalTemplateTemplateParm *Canonical
96 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
97 if (Canonical)
98 return Canonical->getParam();
99
100 // Build a canonical template parameter list.
101 TemplateParameterList *Params = TTP->getTemplateParameters();
102 llvm::SmallVector<NamedDecl *, 4> CanonParams;
103 CanonParams.reserve(Params->size());
104 for (TemplateParameterList::const_iterator P = Params->begin(),
105 PEnd = Params->end();
106 P != PEnd; ++P) {
107 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
108 CanonParams.push_back(
109 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000110 SourceLocation(),
111 SourceLocation(),
112 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000113 TTP->getIndex(), 0, false,
114 TTP->isParameterPack()));
115 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000116 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
117 QualType T = getCanonicalType(NTTP->getType());
118 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
119 NonTypeTemplateParmDecl *Param;
120 if (NTTP->isExpandedParameterPack()) {
121 llvm::SmallVector<QualType, 2> ExpandedTypes;
122 llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
123 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
124 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
125 ExpandedTInfos.push_back(
126 getTrivialTypeSourceInfo(ExpandedTypes.back()));
127 }
128
129 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000130 SourceLocation(),
131 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000132 NTTP->getDepth(),
133 NTTP->getPosition(), 0,
134 T,
135 TInfo,
136 ExpandedTypes.data(),
137 ExpandedTypes.size(),
138 ExpandedTInfos.data());
139 } else {
140 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000141 SourceLocation(),
142 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000143 NTTP->getDepth(),
144 NTTP->getPosition(), 0,
145 T,
146 NTTP->isParameterPack(),
147 TInfo);
148 }
149 CanonParams.push_back(Param);
150
151 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000152 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
153 cast<TemplateTemplateParmDecl>(*P)));
154 }
155
156 TemplateTemplateParmDecl *CanonTTP
157 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
158 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000159 TTP->getPosition(),
160 TTP->isParameterPack(),
161 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000162 TemplateParameterList::Create(*this, SourceLocation(),
163 SourceLocation(),
164 CanonParams.data(),
165 CanonParams.size(),
166 SourceLocation()));
167
168 // Get the new insert position for the node we care about.
169 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
170 assert(Canonical == 0 && "Shouldn't be in the map!");
171 (void)Canonical;
172
173 // Create the canonical template template parameter entry.
174 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
175 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
176 return CanonTTP;
177}
178
Charles Davis53c59df2010-08-16 03:33:14 +0000179CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000180 if (!LangOpts.CPlusPlus) return 0;
181
Charles Davis6bcb07a2010-08-19 02:18:14 +0000182 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000183 case CXXABI_ARM:
184 return CreateARMCXXABI(*this);
185 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000186 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000187 case CXXABI_Microsoft:
188 return CreateMicrosoftCXXABI(*this);
189 }
John McCall86353412010-08-21 22:46:04 +0000190 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000191}
192
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000193static const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
194 const LangOptions &LOpts) {
195 if (LOpts.FakeAddressSpaceMap) {
196 // The fake address space map must have a distinct entry for each
197 // language-specific address space.
198 static const unsigned FakeAddrSpaceMap[] = {
199 1, // opencl_global
200 2, // opencl_local
201 3 // opencl_constant
202 };
203 return FakeAddrSpaceMap;
204 } else {
205 return T.getAddressSpaceMap();
206 }
207}
208
Chris Lattner465fa322008-10-05 17:34:18 +0000209ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000210 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000211 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000212 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000213 unsigned size_reserve) :
Sebastian Redl31ad7542011-03-13 17:09:40 +0000214 FunctionProtoTypes(this_()),
John McCall773cc982010-06-11 11:07:21 +0000215 TemplateSpecializationTypes(this_()),
216 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000217 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
218 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000219 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000220 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +0000221 cudaConfigureCallDecl(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000222 NullTypeSourceInfo(QualType()),
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000223 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
224 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000225 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000226 BuiltinInfo(builtins),
227 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000228 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000229 LastSDM(0, 0),
John McCall147d0212011-02-22 22:38:33 +0000230 UniqueBlockByRefTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000231 ObjCIdRedefinitionType = QualType();
232 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000233 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000234 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000235 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000236 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000237}
238
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000239ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000240 // Release the DenseMaps associated with DeclContext objects.
241 // FIXME: Is this the ideal solution?
242 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000243
Douglas Gregor5b11d492010-07-25 17:53:33 +0000244 // Call all of the deallocation functions.
245 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
246 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000247
Douglas Gregor832940b2010-03-02 23:58:15 +0000248 // Release all of the memory associated with overridden C++ methods.
249 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
250 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
251 OM != OMEnd; ++OM)
252 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000253
Ted Kremenek076baeb2010-06-08 23:00:58 +0000254 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000255 // because they can contain DenseMaps.
256 for (llvm::DenseMap<const ObjCContainerDecl*,
257 const ASTRecordLayout*>::iterator
258 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
259 // Increment in loop to prevent using deallocated memory.
260 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
261 R->Destroy(*this);
262
Ted Kremenek076baeb2010-06-08 23:00:58 +0000263 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
264 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
265 // Increment in loop to prevent using deallocated memory.
266 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
267 R->Destroy(*this);
268 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000269
270 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
271 AEnd = DeclAttrs.end();
272 A != AEnd; ++A)
273 A->second->~AttrVec();
274}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000275
Douglas Gregor1a809332010-05-23 18:26:36 +0000276void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
277 Deallocations.push_back(std::make_pair(Callback, Data));
278}
279
Mike Stump11289f42009-09-09 15:08:12 +0000280void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000281ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
282 ExternalSource.reset(Source.take());
283}
284
Chris Lattner4eb445d2007-01-26 01:27:23 +0000285void ASTContext::PrintStats() const {
286 fprintf(stderr, "*** AST Context Stats:\n");
287 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000288
Douglas Gregora30d0462009-05-26 14:40:08 +0000289 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000290#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000291#define ABSTRACT_TYPE(Name, Parent)
292#include "clang/AST/TypeNodes.def"
293 0 // Extra
294 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000295
Chris Lattner4eb445d2007-01-26 01:27:23 +0000296 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
297 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000298 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000299 }
300
Douglas Gregora30d0462009-05-26 14:40:08 +0000301 unsigned Idx = 0;
302 unsigned TotalBytes = 0;
303#define TYPE(Name, Parent) \
304 if (counts[Idx]) \
305 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
306 TotalBytes += counts[Idx] * sizeof(Name##Type); \
307 ++Idx;
308#define ABSTRACT_TYPE(Name, Parent)
309#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000310
Douglas Gregora30d0462009-05-26 14:40:08 +0000311 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000312
Douglas Gregor7454c562010-07-02 20:37:36 +0000313 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000314 fprintf(stderr, " %u/%u implicit default constructors created\n",
315 NumImplicitDefaultConstructorsDeclared,
316 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000317 fprintf(stderr, " %u/%u implicit copy constructors created\n",
318 NumImplicitCopyConstructorsDeclared,
319 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000320 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
321 NumImplicitCopyAssignmentOperatorsDeclared,
322 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000323 fprintf(stderr, " %u/%u implicit destructors created\n",
324 NumImplicitDestructorsDeclared, NumImplicitDestructors);
325
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000326 if (ExternalSource.get()) {
327 fprintf(stderr, "\n");
328 ExternalSource->PrintStats();
329 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000330
Douglas Gregor5b11d492010-07-25 17:53:33 +0000331 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000332}
333
334
John McCall48f2d582009-10-23 23:03:21 +0000335void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000336 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000337 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000338 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000339}
340
Chris Lattner970e54e2006-11-12 00:37:36 +0000341void ASTContext::InitBuiltinTypes() {
342 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000343
Chris Lattner970e54e2006-11-12 00:37:36 +0000344 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000345 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000346
Chris Lattner970e54e2006-11-12 00:37:36 +0000347 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000348 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000349 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000350 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000351 InitBuiltinType(CharTy, BuiltinType::Char_S);
352 else
353 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000354 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000355 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
356 InitBuiltinType(ShortTy, BuiltinType::Short);
357 InitBuiltinType(IntTy, BuiltinType::Int);
358 InitBuiltinType(LongTy, BuiltinType::Long);
359 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000360
Chris Lattner970e54e2006-11-12 00:37:36 +0000361 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000362 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
363 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
364 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
365 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
366 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000367
Chris Lattner970e54e2006-11-12 00:37:36 +0000368 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000369 InitBuiltinType(FloatTy, BuiltinType::Float);
370 InitBuiltinType(DoubleTy, BuiltinType::Double);
371 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000372
Chris Lattnerf122cef2009-04-30 02:43:43 +0000373 // GNU extension, 128-bit integers.
374 InitBuiltinType(Int128Ty, BuiltinType::Int128);
375 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
376
Chris Lattnerad3467e2010-12-25 23:25:43 +0000377 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
378 if (!LangOpts.ShortWChar)
379 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
380 else // -fshort-wchar makes wchar_t be unsigned.
381 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
382 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000383 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000384
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000385 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
386 InitBuiltinType(Char16Ty, BuiltinType::Char16);
387 else // C99
388 Char16Ty = getFromTargetType(Target.getChar16Type());
389
390 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
391 InitBuiltinType(Char32Ty, BuiltinType::Char32);
392 else // C99
393 Char32Ty = getFromTargetType(Target.getChar32Type());
394
Douglas Gregor4619e432008-12-05 23:32:09 +0000395 // Placeholder type for type-dependent expressions whose type is
396 // completely unknown. No code should ever check a type against
397 // DependentTy and users should never see it; however, it is here to
398 // help diagnose failures to properly check for type-dependent
399 // expressions.
400 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000401
John McCall36e7fe32010-10-12 00:20:44 +0000402 // Placeholder type for functions.
403 InitBuiltinType(OverloadTy, BuiltinType::Overload);
404
Chris Lattner970e54e2006-11-12 00:37:36 +0000405 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000406 FloatComplexTy = getComplexType(FloatTy);
407 DoubleComplexTy = getComplexType(DoubleTy);
408 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000409
Steve Naroff66e9f332007-10-15 14:41:52 +0000410 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000411
Steve Naroff1329fa02009-07-15 18:40:39 +0000412 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
413 ObjCIdTypedefType = QualType();
414 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000415 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000416
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000417 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000418 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
419 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000420 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000421
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000422 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000423
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000424 // void * type
425 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000426
427 // nullptr type (C++0x 2.14.7)
428 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000429}
430
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000431Diagnostic &ASTContext::getDiagnostics() const {
432 return SourceMgr.getDiagnostics();
433}
434
Douglas Gregor561eceb2010-08-30 16:49:28 +0000435AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
436 AttrVec *&Result = DeclAttrs[D];
437 if (!Result) {
438 void *Mem = Allocate(sizeof(AttrVec));
439 Result = new (Mem) AttrVec;
440 }
441
442 return *Result;
443}
444
445/// \brief Erase the attributes corresponding to the given declaration.
446void ASTContext::eraseDeclAttrs(const Decl *D) {
447 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
448 if (Pos != DeclAttrs.end()) {
449 Pos->second->~AttrVec();
450 DeclAttrs.erase(Pos);
451 }
452}
453
454
Douglas Gregor86d142a2009-10-08 07:24:58 +0000455MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000456ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000457 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000458 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000459 = InstantiatedFromStaticDataMember.find(Var);
460 if (Pos == InstantiatedFromStaticDataMember.end())
461 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000462
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000463 return Pos->second;
464}
465
Mike Stump11289f42009-09-09 15:08:12 +0000466void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000467ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000468 TemplateSpecializationKind TSK,
469 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000470 assert(Inst->isStaticDataMember() && "Not a static data member");
471 assert(Tmpl->isStaticDataMember() && "Not a static data member");
472 assert(!InstantiatedFromStaticDataMember[Inst] &&
473 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000474 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000475 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000476}
477
John McCalle61f2ba2009-11-18 02:36:19 +0000478NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000479ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000480 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000481 = InstantiatedFromUsingDecl.find(UUD);
482 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000483 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000484
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000485 return Pos->second;
486}
487
488void
John McCallb96ec562009-12-04 22:46:56 +0000489ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
490 assert((isa<UsingDecl>(Pattern) ||
491 isa<UnresolvedUsingValueDecl>(Pattern) ||
492 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
493 "pattern decl is not a using decl");
494 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
495 InstantiatedFromUsingDecl[Inst] = Pattern;
496}
497
498UsingShadowDecl *
499ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
500 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
501 = InstantiatedFromUsingShadowDecl.find(Inst);
502 if (Pos == InstantiatedFromUsingShadowDecl.end())
503 return 0;
504
505 return Pos->second;
506}
507
508void
509ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
510 UsingShadowDecl *Pattern) {
511 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
512 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000513}
514
Anders Carlsson5da84842009-09-01 04:26:58 +0000515FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
516 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
517 = InstantiatedFromUnnamedFieldDecl.find(Field);
518 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
519 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000520
Anders Carlsson5da84842009-09-01 04:26:58 +0000521 return Pos->second;
522}
523
524void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
525 FieldDecl *Tmpl) {
526 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
527 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
528 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
529 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000530
Anders Carlsson5da84842009-09-01 04:26:58 +0000531 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
532}
533
Douglas Gregor832940b2010-03-02 23:58:15 +0000534ASTContext::overridden_cxx_method_iterator
535ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
536 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
537 = OverriddenMethods.find(Method);
538 if (Pos == OverriddenMethods.end())
539 return 0;
540
541 return Pos->second.begin();
542}
543
544ASTContext::overridden_cxx_method_iterator
545ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
546 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
547 = OverriddenMethods.find(Method);
548 if (Pos == OverriddenMethods.end())
549 return 0;
550
551 return Pos->second.end();
552}
553
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000554unsigned
555ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
556 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
557 = OverriddenMethods.find(Method);
558 if (Pos == OverriddenMethods.end())
559 return 0;
560
561 return Pos->second.size();
562}
563
Douglas Gregor832940b2010-03-02 23:58:15 +0000564void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
565 const CXXMethodDecl *Overridden) {
566 OverriddenMethods[Method].push_back(Overridden);
567}
568
Chris Lattner53cfe802007-07-18 17:52:12 +0000569//===----------------------------------------------------------------------===//
570// Type Sizing and Analysis
571//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000572
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000573/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
574/// scalar floating point type.
575const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000576 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000577 assert(BT && "Not a floating point type!");
578 switch (BT->getKind()) {
579 default: assert(0 && "Not a floating point type!");
580 case BuiltinType::Float: return Target.getFloatFormat();
581 case BuiltinType::Double: return Target.getDoubleFormat();
582 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
583 }
584}
585
Ken Dyck160146e2010-01-27 17:10:57 +0000586/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000587/// specified decl. Note that bitfields do not have a valid alignment, so
588/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000589/// If @p RefAsPointee, references are treated like their underlying type
590/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000591CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000592 unsigned Align = Target.getCharWidth();
593
John McCall94268702010-10-08 18:24:19 +0000594 bool UseAlignAttrOnly = false;
595 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
596 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000597
John McCall94268702010-10-08 18:24:19 +0000598 // __attribute__((aligned)) can increase or decrease alignment
599 // *except* on a struct or struct member, where it only increases
600 // alignment unless 'packed' is also specified.
601 //
602 // It is an error for [[align]] to decrease alignment, so we can
603 // ignore that possibility; Sema should diagnose it.
604 if (isa<FieldDecl>(D)) {
605 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
606 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
607 } else {
608 UseAlignAttrOnly = true;
609 }
610 }
611
John McCall4e819612011-01-20 07:57:12 +0000612 // If we're using the align attribute only, just ignore everything
613 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000614 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000615 // do nothing
616
John McCall94268702010-10-08 18:24:19 +0000617 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000618 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000619 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000620 if (RefAsPointee)
621 T = RT->getPointeeType();
622 else
623 T = getPointerType(RT->getPointeeType());
624 }
625 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000626 // Adjust alignments of declarations with array type by the
627 // large-array alignment on the target.
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000628 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000629 const ArrayType *arrayType;
630 if (MinWidth && (arrayType = getAsArrayType(T))) {
631 if (isa<VariableArrayType>(arrayType))
632 Align = std::max(Align, Target.getLargeArrayAlign());
633 else if (isa<ConstantArrayType>(arrayType) &&
634 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
635 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000636
John McCall33ddac02011-01-19 10:06:00 +0000637 // Walk through any array types while we're at it.
638 T = getBaseElementType(arrayType);
639 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000640 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
641 }
John McCall4e819612011-01-20 07:57:12 +0000642
643 // Fields can be subject to extra alignment constraints, like if
644 // the field is packed, the struct is packed, or the struct has a
645 // a max-field-alignment constraint (#pragma pack). So calculate
646 // the actual alignment of the field within the struct, and then
647 // (as we're expected to) constrain that by the alignment of the type.
648 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
649 // So calculate the alignment of the field.
650 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
651
652 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000653 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000654
655 // Use the GCD of that and the offset within the record.
656 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
657 if (offset > 0) {
658 // Alignment is always a power of 2, so the GCD will be a power of 2,
659 // which means we get to do this crazy thing instead of Euclid's.
660 uint64_t lowBitOfOffset = offset & (~offset + 1);
661 if (lowBitOfOffset < fieldAlign)
662 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
663 }
664
665 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000666 }
Chris Lattner68061312009-01-24 21:53:27 +0000667 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000668
Ken Dyckcc56c542011-01-15 18:38:59 +0000669 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000670}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000671
John McCall87fe5d52010-05-20 01:18:31 +0000672std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000673ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000674 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000675 return std::make_pair(toCharUnitsFromBits(Info.first),
676 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000677}
678
679std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000680ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000681 return getTypeInfoInChars(T.getTypePtr());
682}
683
Chris Lattner983a8bb2007-07-13 22:13:22 +0000684/// getTypeSize - Return the size of the specified type, in bits. This method
685/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000686///
687/// FIXME: Pointers into different addr spaces could have different sizes and
688/// alignment requirements: getPointerInfo should take an AddrSpace, this
689/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000690std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000691ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000692 uint64_t Width=0;
693 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000694 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000695#define TYPE(Class, Base)
696#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000697#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000698#define DEPENDENT_TYPE(Class, Base) case Type::Class:
699#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000700 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000701 break;
702
Chris Lattner355332d2007-07-13 22:27:08 +0000703 case Type::FunctionNoProto:
704 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000705 // GCC extension: alignof(function) = 32 bits
706 Width = 0;
707 Align = 32;
708 break;
709
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000710 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000711 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000712 Width = 0;
713 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
714 break;
715
Steve Naroff5c131802007-08-30 01:06:46 +0000716 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000717 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000718
Chris Lattner37e05872008-03-05 18:54:05 +0000719 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000720 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000721 Align = EltInfo.second;
722 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000723 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000724 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000725 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000726 const VectorType *VT = cast<VectorType>(T);
727 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
728 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000729 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000730 // If the alignment is not a power of 2, round up to the next power of 2.
731 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000732 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000733 Align = llvm::NextPowerOf2(Align);
734 Width = llvm::RoundUpToAlignment(Width, Align);
735 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000736 break;
737 }
Chris Lattner647fb222007-07-18 18:26:58 +0000738
Chris Lattner7570e9c2008-03-08 08:52:55 +0000739 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000740 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000741 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000742 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000743 // GCC extension: alignof(void) = 8 bits.
744 Width = 0;
745 Align = 8;
746 break;
747
Chris Lattner6a4f7452007-12-19 19:23:28 +0000748 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000749 Width = Target.getBoolWidth();
750 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000751 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000752 case BuiltinType::Char_S:
753 case BuiltinType::Char_U:
754 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000755 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000756 Width = Target.getCharWidth();
757 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000758 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000759 case BuiltinType::WChar_S:
760 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000761 Width = Target.getWCharWidth();
762 Align = Target.getWCharAlign();
763 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000764 case BuiltinType::Char16:
765 Width = Target.getChar16Width();
766 Align = Target.getChar16Align();
767 break;
768 case BuiltinType::Char32:
769 Width = Target.getChar32Width();
770 Align = Target.getChar32Align();
771 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000772 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000773 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000774 Width = Target.getShortWidth();
775 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000776 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000777 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000778 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000779 Width = Target.getIntWidth();
780 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000781 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000782 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000783 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000784 Width = Target.getLongWidth();
785 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000786 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000787 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000788 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000789 Width = Target.getLongLongWidth();
790 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000791 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000792 case BuiltinType::Int128:
793 case BuiltinType::UInt128:
794 Width = 128;
795 Align = 128; // int128_t is 128-bit aligned on all targets.
796 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000797 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000798 Width = Target.getFloatWidth();
799 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000800 break;
801 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000802 Width = Target.getDoubleWidth();
803 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000804 break;
805 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000806 Width = Target.getLongDoubleWidth();
807 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000808 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000809 case BuiltinType::NullPtr:
810 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
811 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000812 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000813 case BuiltinType::ObjCId:
814 case BuiltinType::ObjCClass:
815 case BuiltinType::ObjCSel:
816 Width = Target.getPointerWidth(0);
817 Align = Target.getPointerAlign(0);
818 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000819 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000820 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000821 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000822 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000823 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000824 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000825 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000826 unsigned AS = getTargetAddressSpace(
827 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff921a45c2008-09-24 15:05:44 +0000828 Width = Target.getPointerWidth(AS);
829 Align = Target.getPointerAlign(AS);
830 break;
831 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000832 case Type::LValueReference:
833 case Type::RValueReference: {
834 // alignof and sizeof should never enter this code path here, so we go
835 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000836 unsigned AS = getTargetAddressSpace(
837 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000838 Width = Target.getPointerWidth(AS);
839 Align = Target.getPointerAlign(AS);
840 break;
841 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000842 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000843 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000844 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000845 Align = Target.getPointerAlign(AS);
846 break;
847 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000848 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000849 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000850 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000851 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000852 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000853 Align = PtrDiffInfo.second;
854 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000855 }
Chris Lattner647fb222007-07-18 18:26:58 +0000856 case Type::Complex: {
857 // Complex types have the same alignment as their elements, but twice the
858 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000859 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000860 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000861 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000862 Align = EltInfo.second;
863 break;
864 }
John McCall8b07ec22010-05-15 11:32:37 +0000865 case Type::ObjCObject:
866 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000867 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000868 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000869 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000870 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000871 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000872 break;
873 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000874 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000875 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000876 const TagType *TT = cast<TagType>(T);
877
878 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000879 Width = 1;
880 Align = 1;
881 break;
882 }
Mike Stump11289f42009-09-09 15:08:12 +0000883
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000884 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000885 return getTypeInfo(ET->getDecl()->getIntegerType());
886
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000887 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000888 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000889 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000890 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +0000891 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000892 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000893
Chris Lattner63d2b362009-10-22 05:17:15 +0000894 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000895 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
896 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000897
Richard Smith30482bc2011-02-20 03:19:35 +0000898 case Type::Auto: {
899 const AutoType *A = cast<AutoType>(T);
900 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +0000901 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +0000902 }
903
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000904 case Type::Paren:
905 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
906
Douglas Gregoref462e62009-04-30 17:32:17 +0000907 case Type::Typedef: {
908 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000909 std::pair<uint64_t, unsigned> Info
910 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +0000911 // If the typedef has an aligned attribute on it, it overrides any computed
912 // alignment we have. This violates the GCC documentation (which says that
913 // attribute(aligned) can only round up) but matches its implementation.
914 if (unsigned AttrAlign = Typedef->getMaxAlignment())
915 Align = AttrAlign;
916 else
917 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +0000918 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000919 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000920 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000921
922 case Type::TypeOfExpr:
923 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
924 .getTypePtr());
925
926 case Type::TypeOf:
927 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
928
Anders Carlsson81df7b82009-06-24 19:06:50 +0000929 case Type::Decltype:
930 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
931 .getTypePtr());
932
Abramo Bagnara6150c882010-05-11 21:36:43 +0000933 case Type::Elaborated:
934 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000935
John McCall81904512011-01-06 01:58:22 +0000936 case Type::Attributed:
937 return getTypeInfo(
938 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
939
Douglas Gregoref462e62009-04-30 17:32:17 +0000940 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000941 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000942 "Cannot request the size of a dependent type");
943 // FIXME: this is likely to be wrong once we support template
944 // aliases, since a template alias could refer to a typedef that
945 // has an __aligned__ attribute on it.
946 return getTypeInfo(getCanonicalType(T));
947 }
Mike Stump11289f42009-09-09 15:08:12 +0000948
Chris Lattner53cfe802007-07-18 17:52:12 +0000949 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000950 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000951}
952
Ken Dyckcc56c542011-01-15 18:38:59 +0000953/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
954CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
955 return CharUnits::fromQuantity(BitSize / getCharWidth());
956}
957
Ken Dyckb0fcc592011-02-11 01:54:29 +0000958/// toBits - Convert a size in characters to a size in characters.
959int64_t ASTContext::toBits(CharUnits CharSize) const {
960 return CharSize.getQuantity() * getCharWidth();
961}
962
Ken Dyck8c89d592009-12-22 14:23:30 +0000963/// getTypeSizeInChars - Return the size of the specified type, in characters.
964/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000965CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000966 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000967}
Jay Foad39c79802011-01-12 09:06:06 +0000968CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000969 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000970}
971
Ken Dycka6046ab2010-01-26 17:25:18 +0000972/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000973/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000974CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000975 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000976}
Jay Foad39c79802011-01-12 09:06:06 +0000977CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000978 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000979}
980
Chris Lattnera3402cd2009-01-27 18:08:34 +0000981/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
982/// type for the current target in bits. This can be different than the ABI
983/// alignment in cases where it is beneficial for performance to overalign
984/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +0000985unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +0000986 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000987
988 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000989 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000990 T = CT->getElementType().getTypePtr();
991 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
992 T->isSpecificBuiltinType(BuiltinType::LongLong))
993 return std::max(ABIAlign, (unsigned)getTypeSize(T));
994
Chris Lattnera3402cd2009-01-27 18:08:34 +0000995 return ABIAlign;
996}
997
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000998/// ShallowCollectObjCIvars -
999/// Collect all ivars, including those synthesized, in the current class.
1000///
1001void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +00001002 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001003 // FIXME. This need be removed but there are two many places which
1004 // assume const-ness of ObjCInterfaceDecl
1005 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1006 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1007 Iv= Iv->getNextIvar())
1008 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001009}
1010
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001011/// DeepCollectObjCIvars -
1012/// This routine first collects all declared, but not synthesized, ivars in
1013/// super class and then collects all ivars, including those synthesized for
1014/// current class. This routine is used for implementation of current class
1015/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001016///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001017void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1018 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +00001019 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001020 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1021 DeepCollectObjCIvars(SuperClass, false, Ivars);
1022 if (!leafClass) {
1023 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1024 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001025 Ivars.push_back(*I);
1026 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001027 else
1028 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001029}
1030
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001031/// CollectInheritedProtocols - Collect all protocols in current class and
1032/// those inherited by it.
1033void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001034 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001035 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001036 // We can use protocol_iterator here instead of
1037 // all_referenced_protocol_iterator since we are walking all categories.
1038 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1039 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001040 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001041 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001042 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001043 PE = Proto->protocol_end(); P != PE; ++P) {
1044 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001045 CollectInheritedProtocols(*P, Protocols);
1046 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001047 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001048
1049 // Categories of this Interface.
1050 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1051 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1052 CollectInheritedProtocols(CDeclChain, Protocols);
1053 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1054 while (SD) {
1055 CollectInheritedProtocols(SD, Protocols);
1056 SD = SD->getSuperClass();
1057 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001058 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001059 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001060 PE = OC->protocol_end(); P != PE; ++P) {
1061 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001062 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001063 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1064 PE = Proto->protocol_end(); P != PE; ++P)
1065 CollectInheritedProtocols(*P, Protocols);
1066 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001067 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001068 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1069 PE = OP->protocol_end(); P != PE; ++P) {
1070 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001071 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001072 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1073 PE = Proto->protocol_end(); P != PE; ++P)
1074 CollectInheritedProtocols(*P, Protocols);
1075 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001076 }
1077}
1078
Jay Foad39c79802011-01-12 09:06:06 +00001079unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001080 unsigned count = 0;
1081 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001082 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1083 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001084 count += CDecl->ivar_size();
1085
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001086 // Count ivar defined in this class's implementation. This
1087 // includes synthesized ivars.
1088 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001089 count += ImplDecl->ivar_size();
1090
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001091 return count;
1092}
1093
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001094/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1095ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1096 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1097 I = ObjCImpls.find(D);
1098 if (I != ObjCImpls.end())
1099 return cast<ObjCImplementationDecl>(I->second);
1100 return 0;
1101}
1102/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1103ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1104 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1105 I = ObjCImpls.find(D);
1106 if (I != ObjCImpls.end())
1107 return cast<ObjCCategoryImplDecl>(I->second);
1108 return 0;
1109}
1110
1111/// \brief Set the implementation of ObjCInterfaceDecl.
1112void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1113 ObjCImplementationDecl *ImplD) {
1114 assert(IFaceD && ImplD && "Passed null params");
1115 ObjCImpls[IFaceD] = ImplD;
1116}
1117/// \brief Set the implementation of ObjCCategoryDecl.
1118void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1119 ObjCCategoryImplDecl *ImplD) {
1120 assert(CatD && ImplD && "Passed null params");
1121 ObjCImpls[CatD] = ImplD;
1122}
1123
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001124/// \brief Get the copy initialization expression of VarDecl,or NULL if
1125/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001126Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001127 assert(VD && "Passed null params");
1128 assert(VD->hasAttr<BlocksAttr>() &&
1129 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001130 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001131 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001132 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1133}
1134
1135/// \brief Set the copy inialization expression of a block var decl.
1136void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1137 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001138 assert(VD->hasAttr<BlocksAttr>() &&
1139 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001140 BlockVarCopyInits[VD] = Init;
1141}
1142
John McCallbcd03502009-12-07 02:54:59 +00001143/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001144///
John McCallbcd03502009-12-07 02:54:59 +00001145/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001146/// the TypeLoc wrappers.
1147///
1148/// \param T the type that will be the basis for type source info. This type
1149/// should refer to how the declarator was written in source code, not to
1150/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001151TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001152 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001153 if (!DataSize)
1154 DataSize = TypeLoc::getFullDataSizeForType(T);
1155 else
1156 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001157 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001158
John McCallbcd03502009-12-07 02:54:59 +00001159 TypeSourceInfo *TInfo =
1160 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1161 new (TInfo) TypeSourceInfo(T);
1162 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001163}
1164
John McCallbcd03502009-12-07 02:54:59 +00001165TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001166 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001167 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001168 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001169 return DI;
1170}
1171
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001172const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001173ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001174 return getObjCLayout(D, 0);
1175}
1176
1177const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001178ASTContext::getASTObjCImplementationLayout(
1179 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001180 return getObjCLayout(D->getClassInterface(), D);
1181}
1182
Chris Lattner983a8bb2007-07-13 22:13:22 +00001183//===----------------------------------------------------------------------===//
1184// Type creation/memoization methods
1185//===----------------------------------------------------------------------===//
1186
Jay Foad39c79802011-01-12 09:06:06 +00001187QualType
John McCall33ddac02011-01-19 10:06:00 +00001188ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1189 unsigned fastQuals = quals.getFastQualifiers();
1190 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001191
1192 // Check if we've already instantiated this type.
1193 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001194 ExtQuals::Profile(ID, baseType, quals);
1195 void *insertPos = 0;
1196 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1197 assert(eq->getQualifiers() == quals);
1198 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001199 }
1200
John McCall33ddac02011-01-19 10:06:00 +00001201 // If the base type is not canonical, make the appropriate canonical type.
1202 QualType canon;
1203 if (!baseType->isCanonicalUnqualified()) {
1204 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1205 canonSplit.second.addConsistentQualifiers(quals);
1206 canon = getExtQualType(canonSplit.first, canonSplit.second);
1207
1208 // Re-find the insert position.
1209 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1210 }
1211
1212 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1213 ExtQualNodes.InsertNode(eq, insertPos);
1214 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001215}
1216
Jay Foad39c79802011-01-12 09:06:06 +00001217QualType
1218ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001219 QualType CanT = getCanonicalType(T);
1220 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001221 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001222
John McCall8ccfcb52009-09-24 19:53:00 +00001223 // If we are composing extended qualifiers together, merge together
1224 // into one ExtQuals node.
1225 QualifierCollector Quals;
1226 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001227
John McCall8ccfcb52009-09-24 19:53:00 +00001228 // If this type already has an address space specified, it cannot get
1229 // another one.
1230 assert(!Quals.hasAddressSpace() &&
1231 "Type cannot be in multiple addr spaces!");
1232 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001233
John McCall8ccfcb52009-09-24 19:53:00 +00001234 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001235}
1236
Chris Lattnerd60183d2009-02-18 22:53:11 +00001237QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001238 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001239 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001240 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001241 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001242
John McCall53fa7142010-12-24 02:08:15 +00001243 if (const PointerType *ptr = T->getAs<PointerType>()) {
1244 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001245 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001246 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1247 return getPointerType(ResultType);
1248 }
1249 }
Mike Stump11289f42009-09-09 15:08:12 +00001250
John McCall8ccfcb52009-09-24 19:53:00 +00001251 // If we are composing extended qualifiers together, merge together
1252 // into one ExtQuals node.
1253 QualifierCollector Quals;
1254 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001255
John McCall8ccfcb52009-09-24 19:53:00 +00001256 // If this type already has an ObjCGC specified, it cannot get
1257 // another one.
1258 assert(!Quals.hasObjCGCAttr() &&
1259 "Type cannot have multiple ObjCGCs!");
1260 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001261
John McCall8ccfcb52009-09-24 19:53:00 +00001262 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001263}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001264
John McCall4f5019e2010-12-19 02:44:49 +00001265const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1266 FunctionType::ExtInfo Info) {
1267 if (T->getExtInfo() == Info)
1268 return T;
1269
1270 QualType Result;
1271 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1272 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1273 } else {
1274 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1275 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1276 EPI.ExtInfo = Info;
1277 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1278 FPT->getNumArgs(), EPI);
1279 }
1280
1281 return cast<FunctionType>(Result.getTypePtr());
1282}
1283
Chris Lattnerc6395932007-06-22 20:56:16 +00001284/// getComplexType - Return the uniqued reference to the type for a complex
1285/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001286QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001287 // Unique pointers, to guarantee there is only one pointer of a particular
1288 // structure.
1289 llvm::FoldingSetNodeID ID;
1290 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001291
Chris Lattnerc6395932007-06-22 20:56:16 +00001292 void *InsertPos = 0;
1293 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1294 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001295
Chris Lattnerc6395932007-06-22 20:56:16 +00001296 // If the pointee type isn't canonical, this won't be a canonical type either,
1297 // so fill in the canonical type field.
1298 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001299 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001300 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001301
Chris Lattnerc6395932007-06-22 20:56:16 +00001302 // Get the new insert position for the node we care about.
1303 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001304 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001305 }
John McCall90d1c2d2009-09-24 23:30:46 +00001306 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001307 Types.push_back(New);
1308 ComplexTypes.InsertNode(New, InsertPos);
1309 return QualType(New, 0);
1310}
1311
Chris Lattner970e54e2006-11-12 00:37:36 +00001312/// getPointerType - Return the uniqued reference to the type for a pointer to
1313/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001314QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001315 // Unique pointers, to guarantee there is only one pointer of a particular
1316 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001317 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001318 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001319
Chris Lattner67521df2007-01-27 01:29:36 +00001320 void *InsertPos = 0;
1321 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001322 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001323
Chris Lattner7ccecb92006-11-12 08:50:50 +00001324 // If the pointee type isn't canonical, this won't be a canonical type either,
1325 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001326 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001327 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001328 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001329
Chris Lattner67521df2007-01-27 01:29:36 +00001330 // Get the new insert position for the node we care about.
1331 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001332 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001333 }
John McCall90d1c2d2009-09-24 23:30:46 +00001334 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001335 Types.push_back(New);
1336 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001337 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001338}
1339
Mike Stump11289f42009-09-09 15:08:12 +00001340/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001341/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001342QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001343 assert(T->isFunctionType() && "block of function types only");
1344 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001345 // structure.
1346 llvm::FoldingSetNodeID ID;
1347 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001348
Steve Naroffec33ed92008-08-27 16:04:49 +00001349 void *InsertPos = 0;
1350 if (BlockPointerType *PT =
1351 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1352 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001353
1354 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001355 // type either so fill in the canonical type field.
1356 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001357 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001358 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001359
Steve Naroffec33ed92008-08-27 16:04:49 +00001360 // Get the new insert position for the node we care about.
1361 BlockPointerType *NewIP =
1362 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001363 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001364 }
John McCall90d1c2d2009-09-24 23:30:46 +00001365 BlockPointerType *New
1366 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001367 Types.push_back(New);
1368 BlockPointerTypes.InsertNode(New, InsertPos);
1369 return QualType(New, 0);
1370}
1371
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001372/// getLValueReferenceType - Return the uniqued reference to the type for an
1373/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001374QualType
1375ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001376 // Unique pointers, to guarantee there is only one pointer of a particular
1377 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001378 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001379 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001380
1381 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001382 if (LValueReferenceType *RT =
1383 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001384 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001385
John McCallfc93cf92009-10-22 22:37:11 +00001386 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1387
Bill Wendling3708c182007-05-27 10:15:43 +00001388 // If the referencee type isn't canonical, this won't be a canonical type
1389 // either, so fill in the canonical type field.
1390 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001391 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1392 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1393 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001394
Bill Wendling3708c182007-05-27 10:15:43 +00001395 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001396 LValueReferenceType *NewIP =
1397 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001398 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001399 }
1400
John McCall90d1c2d2009-09-24 23:30:46 +00001401 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001402 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1403 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001404 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001405 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001406
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001407 return QualType(New, 0);
1408}
1409
1410/// getRValueReferenceType - Return the uniqued reference to the type for an
1411/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001412QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001413 // Unique pointers, to guarantee there is only one pointer of a particular
1414 // structure.
1415 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001416 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001417
1418 void *InsertPos = 0;
1419 if (RValueReferenceType *RT =
1420 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1421 return QualType(RT, 0);
1422
John McCallfc93cf92009-10-22 22:37:11 +00001423 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1424
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001425 // If the referencee type isn't canonical, this won't be a canonical type
1426 // either, so fill in the canonical type field.
1427 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001428 if (InnerRef || !T.isCanonical()) {
1429 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1430 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001431
1432 // Get the new insert position for the node we care about.
1433 RValueReferenceType *NewIP =
1434 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001435 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001436 }
1437
John McCall90d1c2d2009-09-24 23:30:46 +00001438 RValueReferenceType *New
1439 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001440 Types.push_back(New);
1441 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001442 return QualType(New, 0);
1443}
1444
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001445/// getMemberPointerType - Return the uniqued reference to the type for a
1446/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001447QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001448 // Unique pointers, to guarantee there is only one pointer of a particular
1449 // structure.
1450 llvm::FoldingSetNodeID ID;
1451 MemberPointerType::Profile(ID, T, Cls);
1452
1453 void *InsertPos = 0;
1454 if (MemberPointerType *PT =
1455 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1456 return QualType(PT, 0);
1457
1458 // If the pointee or class type isn't canonical, this won't be a canonical
1459 // type either, so fill in the canonical type field.
1460 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001461 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001462 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1463
1464 // Get the new insert position for the node we care about.
1465 MemberPointerType *NewIP =
1466 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001467 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001468 }
John McCall90d1c2d2009-09-24 23:30:46 +00001469 MemberPointerType *New
1470 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001471 Types.push_back(New);
1472 MemberPointerTypes.InsertNode(New, InsertPos);
1473 return QualType(New, 0);
1474}
1475
Mike Stump11289f42009-09-09 15:08:12 +00001476/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001477/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001478QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001479 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001480 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001481 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001482 assert((EltTy->isDependentType() ||
1483 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001484 "Constant array of VLAs is illegal!");
1485
Chris Lattnere2df3f92009-05-13 04:12:56 +00001486 // Convert the array size into a canonical width matching the pointer size for
1487 // the target.
1488 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001489 ArySize =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001490 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001491
Chris Lattner23b7eb62007-06-15 23:05:46 +00001492 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001493 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001494
Chris Lattner36f8e652007-01-27 08:31:04 +00001495 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001496 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001497 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001498 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001499
John McCall33ddac02011-01-19 10:06:00 +00001500 // If the element type isn't canonical or has qualifiers, this won't
1501 // be a canonical type either, so fill in the canonical type field.
1502 QualType Canon;
1503 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1504 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1505 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001506 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001507 Canon = getQualifiedType(Canon, canonSplit.second);
1508
Chris Lattner36f8e652007-01-27 08:31:04 +00001509 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001510 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001511 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001512 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001513 }
Mike Stump11289f42009-09-09 15:08:12 +00001514
John McCall90d1c2d2009-09-24 23:30:46 +00001515 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001516 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001517 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001518 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001519 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001520}
1521
John McCall06549462011-01-18 08:40:38 +00001522/// getVariableArrayDecayedType - Turns the given type, which may be
1523/// variably-modified, into the corresponding type with all the known
1524/// sizes replaced with [*].
1525QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1526 // Vastly most common case.
1527 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001528
John McCall06549462011-01-18 08:40:38 +00001529 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001530
John McCall06549462011-01-18 08:40:38 +00001531 SplitQualType split = type.getSplitDesugaredType();
1532 const Type *ty = split.first;
1533 switch (ty->getTypeClass()) {
1534#define TYPE(Class, Base)
1535#define ABSTRACT_TYPE(Class, Base)
1536#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1537#include "clang/AST/TypeNodes.def"
1538 llvm_unreachable("didn't desugar past all non-canonical types?");
1539
1540 // These types should never be variably-modified.
1541 case Type::Builtin:
1542 case Type::Complex:
1543 case Type::Vector:
1544 case Type::ExtVector:
1545 case Type::DependentSizedExtVector:
1546 case Type::ObjCObject:
1547 case Type::ObjCInterface:
1548 case Type::ObjCObjectPointer:
1549 case Type::Record:
1550 case Type::Enum:
1551 case Type::UnresolvedUsing:
1552 case Type::TypeOfExpr:
1553 case Type::TypeOf:
1554 case Type::Decltype:
1555 case Type::DependentName:
1556 case Type::InjectedClassName:
1557 case Type::TemplateSpecialization:
1558 case Type::DependentTemplateSpecialization:
1559 case Type::TemplateTypeParm:
1560 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001561 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001562 case Type::PackExpansion:
1563 llvm_unreachable("type should never be variably-modified");
1564
1565 // These types can be variably-modified but should never need to
1566 // further decay.
1567 case Type::FunctionNoProto:
1568 case Type::FunctionProto:
1569 case Type::BlockPointer:
1570 case Type::MemberPointer:
1571 return type;
1572
1573 // These types can be variably-modified. All these modifications
1574 // preserve structure except as noted by comments.
1575 // TODO: if we ever care about optimizing VLAs, there are no-op
1576 // optimizations available here.
1577 case Type::Pointer:
1578 result = getPointerType(getVariableArrayDecayedType(
1579 cast<PointerType>(ty)->getPointeeType()));
1580 break;
1581
1582 case Type::LValueReference: {
1583 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1584 result = getLValueReferenceType(
1585 getVariableArrayDecayedType(lv->getPointeeType()),
1586 lv->isSpelledAsLValue());
1587 break;
1588 }
1589
1590 case Type::RValueReference: {
1591 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1592 result = getRValueReferenceType(
1593 getVariableArrayDecayedType(lv->getPointeeType()));
1594 break;
1595 }
1596
1597 case Type::ConstantArray: {
1598 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1599 result = getConstantArrayType(
1600 getVariableArrayDecayedType(cat->getElementType()),
1601 cat->getSize(),
1602 cat->getSizeModifier(),
1603 cat->getIndexTypeCVRQualifiers());
1604 break;
1605 }
1606
1607 case Type::DependentSizedArray: {
1608 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1609 result = getDependentSizedArrayType(
1610 getVariableArrayDecayedType(dat->getElementType()),
1611 dat->getSizeExpr(),
1612 dat->getSizeModifier(),
1613 dat->getIndexTypeCVRQualifiers(),
1614 dat->getBracketsRange());
1615 break;
1616 }
1617
1618 // Turn incomplete types into [*] types.
1619 case Type::IncompleteArray: {
1620 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1621 result = getVariableArrayType(
1622 getVariableArrayDecayedType(iat->getElementType()),
1623 /*size*/ 0,
1624 ArrayType::Normal,
1625 iat->getIndexTypeCVRQualifiers(),
1626 SourceRange());
1627 break;
1628 }
1629
1630 // Turn VLA types into [*] types.
1631 case Type::VariableArray: {
1632 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1633 result = getVariableArrayType(
1634 getVariableArrayDecayedType(vat->getElementType()),
1635 /*size*/ 0,
1636 ArrayType::Star,
1637 vat->getIndexTypeCVRQualifiers(),
1638 vat->getBracketsRange());
1639 break;
1640 }
1641 }
1642
1643 // Apply the top-level qualifiers from the original.
1644 return getQualifiedType(result, split.second);
1645}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001646
Steve Naroffcadebd02007-08-30 18:14:25 +00001647/// getVariableArrayType - Returns a non-unique reference to the type for a
1648/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001649QualType ASTContext::getVariableArrayType(QualType EltTy,
1650 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001651 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001652 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001653 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001654 // Since we don't unique expressions, it isn't possible to unique VLA's
1655 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001656 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001657
John McCall33ddac02011-01-19 10:06:00 +00001658 // Be sure to pull qualifiers off the element type.
1659 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1660 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1661 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001662 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001663 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001664 }
1665
John McCall90d1c2d2009-09-24 23:30:46 +00001666 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001667 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001668
1669 VariableArrayTypes.push_back(New);
1670 Types.push_back(New);
1671 return QualType(New, 0);
1672}
1673
Douglas Gregor4619e432008-12-05 23:32:09 +00001674/// getDependentSizedArrayType - Returns a non-unique reference to
1675/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001676/// type.
John McCall33ddac02011-01-19 10:06:00 +00001677QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1678 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001679 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001680 unsigned elementTypeQuals,
1681 SourceRange brackets) const {
1682 assert((!numElements || numElements->isTypeDependent() ||
1683 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001684 "Size must be type- or value-dependent!");
1685
John McCall33ddac02011-01-19 10:06:00 +00001686 // Dependently-sized array types that do not have a specified number
1687 // of elements will have their sizes deduced from a dependent
1688 // initializer. We do no canonicalization here at all, which is okay
1689 // because they can't be used in most locations.
1690 if (!numElements) {
1691 DependentSizedArrayType *newType
1692 = new (*this, TypeAlignment)
1693 DependentSizedArrayType(*this, elementType, QualType(),
1694 numElements, ASM, elementTypeQuals,
1695 brackets);
1696 Types.push_back(newType);
1697 return QualType(newType, 0);
1698 }
1699
1700 // Otherwise, we actually build a new type every time, but we
1701 // also build a canonical type.
1702
1703 SplitQualType canonElementType = getCanonicalType(elementType).split();
1704
1705 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001706 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001707 DependentSizedArrayType::Profile(ID, *this,
1708 QualType(canonElementType.first, 0),
1709 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001710
John McCall33ddac02011-01-19 10:06:00 +00001711 // Look for an existing type with these properties.
1712 DependentSizedArrayType *canonTy =
1713 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001714
John McCall33ddac02011-01-19 10:06:00 +00001715 // If we don't have one, build one.
1716 if (!canonTy) {
1717 canonTy = new (*this, TypeAlignment)
1718 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1719 QualType(), numElements, ASM, elementTypeQuals,
1720 brackets);
1721 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1722 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001723 }
1724
John McCall33ddac02011-01-19 10:06:00 +00001725 // Apply qualifiers from the element type to the array.
1726 QualType canon = getQualifiedType(QualType(canonTy,0),
1727 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001728
John McCall33ddac02011-01-19 10:06:00 +00001729 // If we didn't need extra canonicalization for the element type,
1730 // then just use that as our result.
1731 if (QualType(canonElementType.first, 0) == elementType)
1732 return canon;
1733
1734 // Otherwise, we need to build a type which follows the spelling
1735 // of the element type.
1736 DependentSizedArrayType *sugaredType
1737 = new (*this, TypeAlignment)
1738 DependentSizedArrayType(*this, elementType, canon, numElements,
1739 ASM, elementTypeQuals, brackets);
1740 Types.push_back(sugaredType);
1741 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001742}
1743
John McCall33ddac02011-01-19 10:06:00 +00001744QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001745 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001746 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001747 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001748 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001749
John McCall33ddac02011-01-19 10:06:00 +00001750 void *insertPos = 0;
1751 if (IncompleteArrayType *iat =
1752 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1753 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001754
1755 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001756 // either, so fill in the canonical type field. We also have to pull
1757 // qualifiers off the element type.
1758 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001759
John McCall33ddac02011-01-19 10:06:00 +00001760 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1761 SplitQualType canonSplit = getCanonicalType(elementType).split();
1762 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1763 ASM, elementTypeQuals);
1764 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001765
1766 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001767 IncompleteArrayType *existing =
1768 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1769 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001770 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001771
John McCall33ddac02011-01-19 10:06:00 +00001772 IncompleteArrayType *newType = new (*this, TypeAlignment)
1773 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001774
John McCall33ddac02011-01-19 10:06:00 +00001775 IncompleteArrayTypes.InsertNode(newType, insertPos);
1776 Types.push_back(newType);
1777 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001778}
1779
Steve Naroff91fcddb2007-07-18 18:00:27 +00001780/// getVectorType - Return the unique reference to a vector type of
1781/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001782QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001783 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001784 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001785
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001786 // Check if we've already instantiated a vector of this type.
1787 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001788 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001789
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001790 void *InsertPos = 0;
1791 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1792 return QualType(VTP, 0);
1793
1794 // If the element type isn't canonical, this won't be a canonical type either,
1795 // so fill in the canonical type field.
1796 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001797 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001798 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001799
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001800 // Get the new insert position for the node we care about.
1801 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001802 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001803 }
John McCall90d1c2d2009-09-24 23:30:46 +00001804 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001805 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001806 VectorTypes.InsertNode(New, InsertPos);
1807 Types.push_back(New);
1808 return QualType(New, 0);
1809}
1810
Nate Begemance4d7fc2008-04-18 23:10:10 +00001811/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001812/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001813QualType
1814ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall33ddac02011-01-19 10:06:00 +00001815 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001816
Steve Naroff91fcddb2007-07-18 18:00:27 +00001817 // Check if we've already instantiated a vector of this type.
1818 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001819 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001820 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001821 void *InsertPos = 0;
1822 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1823 return QualType(VTP, 0);
1824
1825 // If the element type isn't canonical, this won't be a canonical type either,
1826 // so fill in the canonical type field.
1827 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001828 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001829 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001830
Steve Naroff91fcddb2007-07-18 18:00:27 +00001831 // Get the new insert position for the node we care about.
1832 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001833 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001834 }
John McCall90d1c2d2009-09-24 23:30:46 +00001835 ExtVectorType *New = new (*this, TypeAlignment)
1836 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001837 VectorTypes.InsertNode(New, InsertPos);
1838 Types.push_back(New);
1839 return QualType(New, 0);
1840}
1841
Jay Foad39c79802011-01-12 09:06:06 +00001842QualType
1843ASTContext::getDependentSizedExtVectorType(QualType vecType,
1844 Expr *SizeExpr,
1845 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001846 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001847 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001848 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001849
Douglas Gregor352169a2009-07-31 03:54:25 +00001850 void *InsertPos = 0;
1851 DependentSizedExtVectorType *Canon
1852 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1853 DependentSizedExtVectorType *New;
1854 if (Canon) {
1855 // We already have a canonical version of this array type; use it as
1856 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001857 New = new (*this, TypeAlignment)
1858 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1859 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001860 } else {
1861 QualType CanonVecTy = getCanonicalType(vecType);
1862 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001863 New = new (*this, TypeAlignment)
1864 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1865 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001866
1867 DependentSizedExtVectorType *CanonCheck
1868 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1869 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1870 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001871 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1872 } else {
1873 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1874 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001875 New = new (*this, TypeAlignment)
1876 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001877 }
1878 }
Mike Stump11289f42009-09-09 15:08:12 +00001879
Douglas Gregor758a8692009-06-17 21:51:59 +00001880 Types.push_back(New);
1881 return QualType(New, 0);
1882}
1883
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001884/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001885///
Jay Foad39c79802011-01-12 09:06:06 +00001886QualType
1887ASTContext::getFunctionNoProtoType(QualType ResultTy,
1888 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00001889 const CallingConv DefaultCC = Info.getCC();
1890 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1891 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001892 // Unique functions, to guarantee there is only one function of a particular
1893 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001894 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001895 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001896
Chris Lattner47955de2007-01-27 08:37:20 +00001897 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001898 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001899 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001900 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001901
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001902 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001903 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001904 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001905 Canonical =
1906 getFunctionNoProtoType(getCanonicalType(ResultTy),
1907 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001908
Chris Lattner47955de2007-01-27 08:37:20 +00001909 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001910 FunctionNoProtoType *NewIP =
1911 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001912 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001913 }
Mike Stump11289f42009-09-09 15:08:12 +00001914
Roman Divacky65b88cd2011-03-01 17:40:53 +00001915 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00001916 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00001917 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00001918 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001919 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001920 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001921}
1922
1923/// getFunctionType - Return a normal function type with a typed argument
1924/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001925QualType
1926ASTContext::getFunctionType(QualType ResultTy,
1927 const QualType *ArgArray, unsigned NumArgs,
1928 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001929 // Unique functions, to guarantee there is only one function of a particular
1930 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001931 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00001932 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001933
1934 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001935 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001936 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001937 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001938
1939 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00001940 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001941 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001942 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001943 isCanonical = false;
1944
Roman Divacky65b88cd2011-03-01 17:40:53 +00001945 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
1946 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1947 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00001948
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001949 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001950 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001951 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001952 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001953 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001954 CanonicalArgs.reserve(NumArgs);
1955 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001956 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001957
John McCalldb40c7f2010-12-14 08:05:40 +00001958 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00001959 CanonicalEPI.ExceptionSpecType = EST_None;
1960 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00001961 CanonicalEPI.ExtInfo
1962 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1963
Chris Lattner76a00cf2008-04-06 22:59:24 +00001964 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001965 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00001966 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001967
Chris Lattnerfd4de792007-01-27 01:15:32 +00001968 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001969 FunctionProtoType *NewIP =
1970 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001971 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001972 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001973
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001974 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001975 // for two variable size arrays (for parameter and exception types) at the
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001976 // end of them. Instead of the exception types, there could be a noexcept
1977 // expression and a context pointer.
John McCalldb40c7f2010-12-14 08:05:40 +00001978 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001979 NumArgs * sizeof(QualType);
1980 if (EPI.ExceptionSpecType == EST_Dynamic)
1981 Size += EPI.NumExceptions * sizeof(QualType);
1982 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00001983 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001984 }
John McCalldb40c7f2010-12-14 08:05:40 +00001985 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00001986 FunctionProtoType::ExtProtoInfo newEPI = EPI;
1987 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00001988 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001989 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001990 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001991 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001992}
Chris Lattneref51c202006-11-10 07:17:23 +00001993
John McCalle78aac42010-03-10 03:28:59 +00001994#ifndef NDEBUG
1995static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1996 if (!isa<CXXRecordDecl>(D)) return false;
1997 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1998 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1999 return true;
2000 if (RD->getDescribedClassTemplate() &&
2001 !isa<ClassTemplateSpecializationDecl>(RD))
2002 return true;
2003 return false;
2004}
2005#endif
2006
2007/// getInjectedClassNameType - Return the unique reference to the
2008/// injected class name type for the specified templated declaration.
2009QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002010 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002011 assert(NeedsInjectedClassNameType(Decl));
2012 if (Decl->TypeForDecl) {
2013 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002014 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002015 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2016 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2017 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2018 } else {
John McCall424cec92011-01-19 06:33:43 +00002019 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002020 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002021 Decl->TypeForDecl = newType;
2022 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002023 }
2024 return QualType(Decl->TypeForDecl, 0);
2025}
2026
Douglas Gregor83a586e2008-04-13 21:07:44 +00002027/// getTypeDeclType - Return the unique reference to the type for the
2028/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002029QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002030 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002031 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002032
John McCall81e38502010-02-16 03:57:14 +00002033 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002034 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002035
John McCall96f0b5f2010-03-10 06:48:02 +00002036 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2037 "Template type parameter types are always available.");
2038
John McCall81e38502010-02-16 03:57:14 +00002039 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002040 assert(!Record->getPreviousDeclaration() &&
2041 "struct/union has previous declaration");
2042 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002043 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002044 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002045 assert(!Enum->getPreviousDeclaration() &&
2046 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002047 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002048 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002049 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002050 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2051 Decl->TypeForDecl = newType;
2052 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002053 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002054 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002055
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002056 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002057}
2058
Chris Lattner32d920b2007-01-26 02:01:53 +00002059/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00002060/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002061QualType
Jay Foad39c79802011-01-12 09:06:06 +00002062ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002063 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002064
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002065 if (Canonical.isNull())
2066 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002067 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002068 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002069 Decl->TypeForDecl = newType;
2070 Types.push_back(newType);
2071 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002072}
2073
Jay Foad39c79802011-01-12 09:06:06 +00002074QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002075 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2076
2077 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2078 if (PrevDecl->TypeForDecl)
2079 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2080
John McCall424cec92011-01-19 06:33:43 +00002081 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2082 Decl->TypeForDecl = newType;
2083 Types.push_back(newType);
2084 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002085}
2086
Jay Foad39c79802011-01-12 09:06:06 +00002087QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002088 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2089
2090 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2091 if (PrevDecl->TypeForDecl)
2092 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2093
John McCall424cec92011-01-19 06:33:43 +00002094 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2095 Decl->TypeForDecl = newType;
2096 Types.push_back(newType);
2097 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002098}
2099
John McCall81904512011-01-06 01:58:22 +00002100QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2101 QualType modifiedType,
2102 QualType equivalentType) {
2103 llvm::FoldingSetNodeID id;
2104 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2105
2106 void *insertPos = 0;
2107 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2108 if (type) return QualType(type, 0);
2109
2110 QualType canon = getCanonicalType(equivalentType);
2111 type = new (*this, TypeAlignment)
2112 AttributedType(canon, attrKind, modifiedType, equivalentType);
2113
2114 Types.push_back(type);
2115 AttributedTypes.InsertNode(type, insertPos);
2116
2117 return QualType(type, 0);
2118}
2119
2120
John McCallcebee162009-10-18 09:09:24 +00002121/// \brief Retrieve a substitution-result type.
2122QualType
2123ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002124 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002125 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002126 && "replacement types must always be canonical");
2127
2128 llvm::FoldingSetNodeID ID;
2129 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2130 void *InsertPos = 0;
2131 SubstTemplateTypeParmType *SubstParm
2132 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2133
2134 if (!SubstParm) {
2135 SubstParm = new (*this, TypeAlignment)
2136 SubstTemplateTypeParmType(Parm, Replacement);
2137 Types.push_back(SubstParm);
2138 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2139 }
2140
2141 return QualType(SubstParm, 0);
2142}
2143
Douglas Gregorada4b792011-01-14 02:55:32 +00002144/// \brief Retrieve a
2145QualType ASTContext::getSubstTemplateTypeParmPackType(
2146 const TemplateTypeParmType *Parm,
2147 const TemplateArgument &ArgPack) {
2148#ifndef NDEBUG
2149 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2150 PEnd = ArgPack.pack_end();
2151 P != PEnd; ++P) {
2152 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2153 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2154 }
2155#endif
2156
2157 llvm::FoldingSetNodeID ID;
2158 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2159 void *InsertPos = 0;
2160 if (SubstTemplateTypeParmPackType *SubstParm
2161 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2162 return QualType(SubstParm, 0);
2163
2164 QualType Canon;
2165 if (!Parm->isCanonicalUnqualified()) {
2166 Canon = getCanonicalType(QualType(Parm, 0));
2167 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2168 ArgPack);
2169 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2170 }
2171
2172 SubstTemplateTypeParmPackType *SubstParm
2173 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2174 ArgPack);
2175 Types.push_back(SubstParm);
2176 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2177 return QualType(SubstParm, 0);
2178}
2179
Douglas Gregoreff93e02009-02-05 23:33:38 +00002180/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002181/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002182/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002183QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002184 bool ParameterPack,
Jay Foad39c79802011-01-12 09:06:06 +00002185 IdentifierInfo *Name) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002186 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002187 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002188 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002189 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002190 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2191
2192 if (TypeParm)
2193 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002194
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002195 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002196 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002197 TypeParm = new (*this, TypeAlignment)
2198 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002199
2200 TemplateTypeParmType *TypeCheck
2201 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2202 assert(!TypeCheck && "Template type parameter canonical type broken");
2203 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002204 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002205 TypeParm = new (*this, TypeAlignment)
2206 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002207
2208 Types.push_back(TypeParm);
2209 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2210
2211 return QualType(TypeParm, 0);
2212}
2213
John McCalle78aac42010-03-10 03:28:59 +00002214TypeSourceInfo *
2215ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2216 SourceLocation NameLoc,
2217 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002218 QualType CanonType) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002219 assert(!Name.getAsDependentTemplateName() &&
2220 "No dependent template names here!");
John McCalle78aac42010-03-10 03:28:59 +00002221 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2222
2223 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2224 TemplateSpecializationTypeLoc TL
2225 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2226 TL.setTemplateNameLoc(NameLoc);
2227 TL.setLAngleLoc(Args.getLAngleLoc());
2228 TL.setRAngleLoc(Args.getRAngleLoc());
2229 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2230 TL.setArgLocInfo(i, Args[i].getLocInfo());
2231 return DI;
2232}
2233
Mike Stump11289f42009-09-09 15:08:12 +00002234QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002235ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002236 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002237 QualType Canon) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002238 assert(!Template.getAsDependentTemplateName() &&
2239 "No dependent template names here!");
2240
John McCall6b51f282009-11-23 01:53:49 +00002241 unsigned NumArgs = Args.size();
2242
John McCall0ad16662009-10-29 08:12:44 +00002243 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2244 ArgVec.reserve(NumArgs);
2245 for (unsigned i = 0; i != NumArgs; ++i)
2246 ArgVec.push_back(Args[i].getArgument());
2247
John McCall2408e322010-04-27 00:57:59 +00002248 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00002249 Canon);
John McCall0ad16662009-10-29 08:12:44 +00002250}
2251
2252QualType
2253ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002254 const TemplateArgument *Args,
2255 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002256 QualType Canon) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002257 assert(!Template.getAsDependentTemplateName() &&
2258 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002259 // Look through qualified template names.
2260 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2261 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002262
Douglas Gregor15301382009-07-30 17:40:51 +00002263 if (!Canon.isNull())
2264 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002265 else
2266 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00002267
Douglas Gregora8e02e72009-07-28 23:00:59 +00002268 // Allocate the (non-canonical) template specialization type, but don't
2269 // try to unique it: these types typically have location information that
2270 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002271 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002272 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002273 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002274 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002275 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002276 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002277 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002278
Douglas Gregor8bf42052009-02-09 18:46:07 +00002279 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002280 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002281}
2282
Mike Stump11289f42009-09-09 15:08:12 +00002283QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002284ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2285 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002286 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002287 assert(!Template.getAsDependentTemplateName() &&
2288 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002289 // Look through qualified template names.
2290 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2291 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002292
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002293 // Build the canonical template specialization type.
2294 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2295 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2296 CanonArgs.reserve(NumArgs);
2297 for (unsigned I = 0; I != NumArgs; ++I)
2298 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2299
2300 // Determine whether this canonical template specialization type already
2301 // exists.
2302 llvm::FoldingSetNodeID ID;
2303 TemplateSpecializationType::Profile(ID, CanonTemplate,
2304 CanonArgs.data(), NumArgs, *this);
2305
2306 void *InsertPos = 0;
2307 TemplateSpecializationType *Spec
2308 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2309
2310 if (!Spec) {
2311 // Allocate a new canonical template specialization type.
2312 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2313 sizeof(TemplateArgument) * NumArgs),
2314 TypeAlignment);
2315 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2316 CanonArgs.data(), NumArgs,
2317 QualType());
2318 Types.push_back(Spec);
2319 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2320 }
2321
2322 assert(Spec->isDependentType() &&
2323 "Non-dependent template-id type must have a canonical type");
2324 return QualType(Spec, 0);
2325}
2326
2327QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002328ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2329 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002330 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002331 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002332 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002333
2334 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002335 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002336 if (T)
2337 return QualType(T, 0);
2338
Douglas Gregorc42075a2010-02-04 18:10:26 +00002339 QualType Canon = NamedType;
2340 if (!Canon.isCanonical()) {
2341 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002342 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2343 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002344 (void)CheckT;
2345 }
2346
Abramo Bagnara6150c882010-05-11 21:36:43 +00002347 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002348 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002349 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002350 return QualType(T, 0);
2351}
2352
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002353QualType
Jay Foad39c79802011-01-12 09:06:06 +00002354ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002355 llvm::FoldingSetNodeID ID;
2356 ParenType::Profile(ID, InnerType);
2357
2358 void *InsertPos = 0;
2359 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2360 if (T)
2361 return QualType(T, 0);
2362
2363 QualType Canon = InnerType;
2364 if (!Canon.isCanonical()) {
2365 Canon = getCanonicalType(InnerType);
2366 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2367 assert(!CheckT && "Paren canonical type broken");
2368 (void)CheckT;
2369 }
2370
2371 T = new (*this) ParenType(InnerType, Canon);
2372 Types.push_back(T);
2373 ParenTypes.InsertNode(T, InsertPos);
2374 return QualType(T, 0);
2375}
2376
Douglas Gregor02085352010-03-31 20:19:30 +00002377QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2378 NestedNameSpecifier *NNS,
2379 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002380 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002381 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2382
2383 if (Canon.isNull()) {
2384 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002385 ElaboratedTypeKeyword CanonKeyword = Keyword;
2386 if (Keyword == ETK_None)
2387 CanonKeyword = ETK_Typename;
2388
2389 if (CanonNNS != NNS || CanonKeyword != Keyword)
2390 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002391 }
2392
2393 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002394 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002395
2396 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002397 DependentNameType *T
2398 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002399 if (T)
2400 return QualType(T, 0);
2401
Douglas Gregor02085352010-03-31 20:19:30 +00002402 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002403 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002404 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002405 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002406}
2407
Mike Stump11289f42009-09-09 15:08:12 +00002408QualType
John McCallc392f372010-06-11 00:33:02 +00002409ASTContext::getDependentTemplateSpecializationType(
2410 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002411 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002412 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002413 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002414 // TODO: avoid this copy
2415 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2416 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2417 ArgCopy.push_back(Args[I].getArgument());
2418 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2419 ArgCopy.size(),
2420 ArgCopy.data());
2421}
2422
2423QualType
2424ASTContext::getDependentTemplateSpecializationType(
2425 ElaboratedTypeKeyword Keyword,
2426 NestedNameSpecifier *NNS,
2427 const IdentifierInfo *Name,
2428 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002429 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002430 assert((!NNS || NNS->isDependent()) &&
2431 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002432
Douglas Gregorc42075a2010-02-04 18:10:26 +00002433 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002434 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2435 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002436
2437 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002438 DependentTemplateSpecializationType *T
2439 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002440 if (T)
2441 return QualType(T, 0);
2442
John McCallc392f372010-06-11 00:33:02 +00002443 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002444
John McCallc392f372010-06-11 00:33:02 +00002445 ElaboratedTypeKeyword CanonKeyword = Keyword;
2446 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2447
2448 bool AnyNonCanonArgs = false;
2449 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2450 for (unsigned I = 0; I != NumArgs; ++I) {
2451 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2452 if (!CanonArgs[I].structurallyEquals(Args[I]))
2453 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002454 }
2455
John McCallc392f372010-06-11 00:33:02 +00002456 QualType Canon;
2457 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2458 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2459 Name, NumArgs,
2460 CanonArgs.data());
2461
2462 // Find the insert position again.
2463 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2464 }
2465
2466 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2467 sizeof(TemplateArgument) * NumArgs),
2468 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002469 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002470 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002471 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002472 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002473 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002474}
2475
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002476QualType ASTContext::getPackExpansionType(QualType Pattern,
2477 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002478 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002479 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002480
2481 assert(Pattern->containsUnexpandedParameterPack() &&
2482 "Pack expansions must expand one or more parameter packs");
2483 void *InsertPos = 0;
2484 PackExpansionType *T
2485 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2486 if (T)
2487 return QualType(T, 0);
2488
2489 QualType Canon;
2490 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002491 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002492
2493 // Find the insert position again.
2494 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2495 }
2496
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002497 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002498 Types.push_back(T);
2499 PackExpansionTypes.InsertNode(T, InsertPos);
2500 return QualType(T, 0);
2501}
2502
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002503/// CmpProtocolNames - Comparison predicate for sorting protocols
2504/// alphabetically.
2505static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2506 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002507 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002508}
2509
John McCall8b07ec22010-05-15 11:32:37 +00002510static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002511 unsigned NumProtocols) {
2512 if (NumProtocols == 0) return true;
2513
2514 for (unsigned i = 1; i != NumProtocols; ++i)
2515 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2516 return false;
2517 return true;
2518}
2519
2520static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002521 unsigned &NumProtocols) {
2522 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002523
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002524 // Sort protocols, keyed by name.
2525 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2526
2527 // Remove duplicates.
2528 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2529 NumProtocols = ProtocolsEnd-Protocols;
2530}
2531
John McCall8b07ec22010-05-15 11:32:37 +00002532QualType ASTContext::getObjCObjectType(QualType BaseType,
2533 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002534 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002535 // If the base type is an interface and there aren't any protocols
2536 // to add, then the interface type will do just fine.
2537 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2538 return BaseType;
2539
2540 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002541 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002542 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002543 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002544 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2545 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002546
John McCall8b07ec22010-05-15 11:32:37 +00002547 // Build the canonical type, which has the canonical base type and
2548 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002549 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002550 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2551 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2552 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002553 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2554 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002555 unsigned UniqueCount = NumProtocols;
2556
John McCallfc93cf92009-10-22 22:37:11 +00002557 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002558 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2559 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002560 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002561 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2562 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002563 }
2564
2565 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002566 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2567 }
2568
2569 unsigned Size = sizeof(ObjCObjectTypeImpl);
2570 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2571 void *Mem = Allocate(Size, TypeAlignment);
2572 ObjCObjectTypeImpl *T =
2573 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2574
2575 Types.push_back(T);
2576 ObjCObjectTypes.InsertNode(T, InsertPos);
2577 return QualType(T, 0);
2578}
2579
2580/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2581/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002582QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002583 llvm::FoldingSetNodeID ID;
2584 ObjCObjectPointerType::Profile(ID, ObjectT);
2585
2586 void *InsertPos = 0;
2587 if (ObjCObjectPointerType *QT =
2588 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2589 return QualType(QT, 0);
2590
2591 // Find the canonical object type.
2592 QualType Canonical;
2593 if (!ObjectT.isCanonical()) {
2594 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2595
2596 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002597 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2598 }
2599
Douglas Gregorf85bee62010-02-08 22:59:26 +00002600 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002601 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2602 ObjCObjectPointerType *QType =
2603 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002604
Steve Narofffb4330f2009-06-17 22:40:22 +00002605 Types.push_back(QType);
2606 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002607 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002608}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002609
Douglas Gregor1c283312010-08-11 12:19:30 +00002610/// getObjCInterfaceType - Return the unique reference to the type for the
2611/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002612QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002613 if (Decl->TypeForDecl)
2614 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002615
Douglas Gregor1c283312010-08-11 12:19:30 +00002616 // FIXME: redeclarations?
2617 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2618 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2619 Decl->TypeForDecl = T;
2620 Types.push_back(T);
2621 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002622}
2623
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002624/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2625/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002626/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002627/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002628/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002629QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002630 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002631 if (tofExpr->isTypeDependent()) {
2632 llvm::FoldingSetNodeID ID;
2633 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002634
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002635 void *InsertPos = 0;
2636 DependentTypeOfExprType *Canon
2637 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2638 if (Canon) {
2639 // We already have a "canonical" version of an identical, dependent
2640 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002641 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002642 QualType((TypeOfExprType*)Canon, 0));
2643 }
2644 else {
2645 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002646 Canon
2647 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002648 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2649 toe = Canon;
2650 }
2651 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002652 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002653 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002654 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002655 Types.push_back(toe);
2656 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002657}
2658
Steve Naroffa773cd52007-08-01 18:02:17 +00002659/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2660/// TypeOfType AST's. The only motivation to unique these nodes would be
2661/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002662/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002663/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002664QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002665 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002666 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002667 Types.push_back(tot);
2668 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002669}
2670
Anders Carlssonad6bd352009-06-24 21:24:56 +00002671/// getDecltypeForExpr - Given an expr, will return the decltype for that
2672/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002673static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002674 if (e->isTypeDependent())
2675 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002676
Anders Carlssonad6bd352009-06-24 21:24:56 +00002677 // If e is an id expression or a class member access, decltype(e) is defined
2678 // as the type of the entity named by e.
2679 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2680 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2681 return VD->getType();
2682 }
2683 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2684 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2685 return FD->getType();
2686 }
2687 // If e is a function call or an invocation of an overloaded operator,
2688 // (parentheses around e are ignored), decltype(e) is defined as the
2689 // return type of that function.
2690 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2691 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002692
Anders Carlssonad6bd352009-06-24 21:24:56 +00002693 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002694
2695 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002696 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002697 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002698 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002699
Anders Carlssonad6bd352009-06-24 21:24:56 +00002700 return T;
2701}
2702
Anders Carlsson81df7b82009-06-24 19:06:50 +00002703/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2704/// DecltypeType AST's. The only motivation to unique these nodes would be
2705/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002706/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002707/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002708QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002709 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002710 if (e->isTypeDependent()) {
2711 llvm::FoldingSetNodeID ID;
2712 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002713
Douglas Gregora21f6c32009-07-30 23:36:40 +00002714 void *InsertPos = 0;
2715 DependentDecltypeType *Canon
2716 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2717 if (Canon) {
2718 // We already have a "canonical" version of an equivalent, dependent
2719 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002720 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002721 QualType((DecltypeType*)Canon, 0));
2722 }
2723 else {
2724 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002725 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002726 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2727 dt = Canon;
2728 }
2729 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002730 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002731 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002732 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002733 Types.push_back(dt);
2734 return QualType(dt, 0);
2735}
2736
Richard Smithb2bc2e62011-02-21 20:05:19 +00002737/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002738QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002739 void *InsertPos = 0;
2740 if (!DeducedType.isNull()) {
2741 // Look in the folding set for an existing type.
2742 llvm::FoldingSetNodeID ID;
2743 AutoType::Profile(ID, DeducedType);
2744 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2745 return QualType(AT, 0);
2746 }
2747
2748 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2749 Types.push_back(AT);
2750 if (InsertPos)
2751 AutoTypes.InsertNode(AT, InsertPos);
2752 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002753}
2754
Chris Lattnerfb072462007-01-23 05:45:31 +00002755/// getTagDeclType - Return the unique reference to the type for the
2756/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002757QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002758 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002759 // FIXME: What is the design on getTagDeclType when it requires casting
2760 // away const? mutable?
2761 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002762}
2763
Mike Stump11289f42009-09-09 15:08:12 +00002764/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2765/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2766/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002767CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002768 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002769}
Chris Lattnerfb072462007-01-23 05:45:31 +00002770
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002771/// getSignedWCharType - Return the type of "signed wchar_t".
2772/// Used when in C++, as a GCC extension.
2773QualType ASTContext::getSignedWCharType() const {
2774 // FIXME: derive from "Target" ?
2775 return WCharTy;
2776}
2777
2778/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2779/// Used when in C++, as a GCC extension.
2780QualType ASTContext::getUnsignedWCharType() const {
2781 // FIXME: derive from "Target" ?
2782 return UnsignedIntTy;
2783}
2784
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002785/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2786/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2787QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002788 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002789}
2790
Chris Lattnera21ad802008-04-02 05:18:44 +00002791//===----------------------------------------------------------------------===//
2792// Type Operators
2793//===----------------------------------------------------------------------===//
2794
Jay Foad39c79802011-01-12 09:06:06 +00002795CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002796 // Push qualifiers into arrays, and then discard any remaining
2797 // qualifiers.
2798 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002799 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002800 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002801 QualType Result;
2802 if (isa<ArrayType>(Ty)) {
2803 Result = getArrayDecayedType(QualType(Ty,0));
2804 } else if (isa<FunctionType>(Ty)) {
2805 Result = getPointerType(QualType(Ty, 0));
2806 } else {
2807 Result = QualType(Ty, 0);
2808 }
2809
2810 return CanQualType::CreateUnsafe(Result);
2811}
2812
Chris Lattner7adf0762008-08-04 07:31:14 +00002813
John McCall6c9dd522011-01-18 07:41:22 +00002814QualType ASTContext::getUnqualifiedArrayType(QualType type,
2815 Qualifiers &quals) {
2816 SplitQualType splitType = type.getSplitUnqualifiedType();
2817
2818 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2819 // the unqualified desugared type and then drops it on the floor.
2820 // We then have to strip that sugar back off with
2821 // getUnqualifiedDesugaredType(), which is silly.
2822 const ArrayType *AT =
2823 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2824
2825 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002826 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002827 quals = splitType.second;
2828 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002829 }
2830
John McCall6c9dd522011-01-18 07:41:22 +00002831 // Otherwise, recurse on the array's element type.
2832 QualType elementType = AT->getElementType();
2833 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2834
2835 // If that didn't change the element type, AT has no qualifiers, so we
2836 // can just use the results in splitType.
2837 if (elementType == unqualElementType) {
2838 assert(quals.empty()); // from the recursive call
2839 quals = splitType.second;
2840 return QualType(splitType.first, 0);
2841 }
2842
2843 // Otherwise, add in the qualifiers from the outermost type, then
2844 // build the type back up.
2845 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002846
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002847 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002848 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002849 CAT->getSizeModifier(), 0);
2850 }
2851
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002852 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002853 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002854 }
2855
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002856 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002857 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002858 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002859 VAT->getSizeModifier(),
2860 VAT->getIndexTypeCVRQualifiers(),
2861 VAT->getBracketsRange());
2862 }
2863
2864 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002865 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002866 DSAT->getSizeModifier(), 0,
2867 SourceRange());
2868}
2869
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002870/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2871/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2872/// they point to and return true. If T1 and T2 aren't pointer types
2873/// or pointer-to-member types, or if they are not similar at this
2874/// level, returns false and leaves T1 and T2 unchanged. Top-level
2875/// qualifiers on T1 and T2 are ignored. This function will typically
2876/// be called in a loop that successively "unwraps" pointer and
2877/// pointer-to-member types to compare them at each level.
2878bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2879 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2880 *T2PtrType = T2->getAs<PointerType>();
2881 if (T1PtrType && T2PtrType) {
2882 T1 = T1PtrType->getPointeeType();
2883 T2 = T2PtrType->getPointeeType();
2884 return true;
2885 }
2886
2887 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2888 *T2MPType = T2->getAs<MemberPointerType>();
2889 if (T1MPType && T2MPType &&
2890 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2891 QualType(T2MPType->getClass(), 0))) {
2892 T1 = T1MPType->getPointeeType();
2893 T2 = T2MPType->getPointeeType();
2894 return true;
2895 }
2896
2897 if (getLangOptions().ObjC1) {
2898 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2899 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2900 if (T1OPType && T2OPType) {
2901 T1 = T1OPType->getPointeeType();
2902 T2 = T2OPType->getPointeeType();
2903 return true;
2904 }
2905 }
2906
2907 // FIXME: Block pointers, too?
2908
2909 return false;
2910}
2911
Jay Foad39c79802011-01-12 09:06:06 +00002912DeclarationNameInfo
2913ASTContext::getNameForTemplate(TemplateName Name,
2914 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002915 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002916 // DNInfo work in progress: CHECKME: what about DNLoc?
2917 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2918
John McCall847e2a12009-11-24 18:42:40 +00002919 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002920 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002921 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002922 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2923 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002924 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002925 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2926 // DNInfo work in progress: FIXME: source locations?
2927 DeclarationNameLoc DNLoc;
2928 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2929 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2930 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002931 }
2932 }
2933
John McCalld28ae272009-12-02 08:04:21 +00002934 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2935 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002936 // DNInfo work in progress: CHECKME: what about DNLoc?
2937 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002938}
2939
Jay Foad39c79802011-01-12 09:06:06 +00002940TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002941 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2942 if (TemplateTemplateParmDecl *TTP
2943 = dyn_cast<TemplateTemplateParmDecl>(Template))
2944 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2945
2946 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002947 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002948 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002949
Douglas Gregor5590be02011-01-15 06:45:20 +00002950 if (SubstTemplateTemplateParmPackStorage *SubstPack
2951 = Name.getAsSubstTemplateTemplateParmPack()) {
2952 TemplateTemplateParmDecl *CanonParam
2953 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2954 TemplateArgument CanonArgPack
2955 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2956 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2957 }
2958
John McCalld28ae272009-12-02 08:04:21 +00002959 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002960
Douglas Gregor6bc50582009-05-07 06:41:52 +00002961 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2962 assert(DTN && "Non-dependent template names must refer to template decls.");
2963 return DTN->CanonicalTemplateName;
2964}
2965
Douglas Gregoradee3e32009-11-11 23:06:43 +00002966bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2967 X = getCanonicalTemplateName(X);
2968 Y = getCanonicalTemplateName(Y);
2969 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2970}
2971
Mike Stump11289f42009-09-09 15:08:12 +00002972TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00002973ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00002974 switch (Arg.getKind()) {
2975 case TemplateArgument::Null:
2976 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002977
Douglas Gregora8e02e72009-07-28 23:00:59 +00002978 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002979 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002980
Douglas Gregora8e02e72009-07-28 23:00:59 +00002981 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002982 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002983
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002984 case TemplateArgument::Template:
2985 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002986
2987 case TemplateArgument::TemplateExpansion:
2988 return TemplateArgument(getCanonicalTemplateName(
2989 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00002990 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002991
Douglas Gregora8e02e72009-07-28 23:00:59 +00002992 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002993 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002994 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002995
Douglas Gregora8e02e72009-07-28 23:00:59 +00002996 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002997 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002998
Douglas Gregora8e02e72009-07-28 23:00:59 +00002999 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003000 if (Arg.pack_size() == 0)
3001 return Arg;
3002
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003003 TemplateArgument *CanonArgs
3004 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003005 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003006 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003007 AEnd = Arg.pack_end();
3008 A != AEnd; (void)++A, ++Idx)
3009 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003010
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003011 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003012 }
3013 }
3014
3015 // Silence GCC warning
3016 assert(false && "Unhandled template argument kind");
3017 return TemplateArgument();
3018}
3019
Douglas Gregor333489b2009-03-27 23:10:48 +00003020NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003021ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003022 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003023 return 0;
3024
3025 switch (NNS->getKind()) {
3026 case NestedNameSpecifier::Identifier:
3027 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003028 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003029 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3030 NNS->getAsIdentifier());
3031
3032 case NestedNameSpecifier::Namespace:
3033 // A namespace is canonical; build a nested-name-specifier with
3034 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003035 return NestedNameSpecifier::Create(*this, 0,
3036 NNS->getAsNamespace()->getOriginalNamespace());
3037
3038 case NestedNameSpecifier::NamespaceAlias:
3039 // A namespace is canonical; build a nested-name-specifier with
3040 // this namespace and no prefix.
3041 return NestedNameSpecifier::Create(*this, 0,
3042 NNS->getAsNamespaceAlias()->getNamespace()
3043 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003044
3045 case NestedNameSpecifier::TypeSpec:
3046 case NestedNameSpecifier::TypeSpecWithTemplate: {
3047 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003048
3049 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3050 // break it apart into its prefix and identifier, then reconsititute those
3051 // as the canonical nested-name-specifier. This is required to canonicalize
3052 // a dependent nested-name-specifier involving typedefs of dependent-name
3053 // types, e.g.,
3054 // typedef typename T::type T1;
3055 // typedef typename T1::type T2;
3056 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3057 NestedNameSpecifier *Prefix
3058 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3059 return NestedNameSpecifier::Create(*this, Prefix,
3060 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3061 }
3062
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003063 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003064 if (const DependentTemplateSpecializationType *DTST
3065 = T->getAs<DependentTemplateSpecializationType>()) {
3066 NestedNameSpecifier *Prefix
3067 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003068
3069 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3070 Prefix, DTST->getIdentifier(),
3071 DTST->getNumArgs(),
3072 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003073 T = getCanonicalType(T);
3074 }
3075
John McCall33ddac02011-01-19 10:06:00 +00003076 return NestedNameSpecifier::Create(*this, 0, false,
3077 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003078 }
3079
3080 case NestedNameSpecifier::Global:
3081 // The global specifier is canonical and unique.
3082 return NNS;
3083 }
3084
3085 // Required to silence a GCC warning
3086 return 0;
3087}
3088
Chris Lattner7adf0762008-08-04 07:31:14 +00003089
Jay Foad39c79802011-01-12 09:06:06 +00003090const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003091 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003092 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003093 // Handle the common positive case fast.
3094 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3095 return AT;
3096 }
Mike Stump11289f42009-09-09 15:08:12 +00003097
John McCall8ccfcb52009-09-24 19:53:00 +00003098 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003099 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003100 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003101
John McCall8ccfcb52009-09-24 19:53:00 +00003102 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003103 // implements C99 6.7.3p8: "If the specification of an array type includes
3104 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003105
Chris Lattner7adf0762008-08-04 07:31:14 +00003106 // If we get here, we either have type qualifiers on the type, or we have
3107 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003108 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003109
John McCall33ddac02011-01-19 10:06:00 +00003110 SplitQualType split = T.getSplitDesugaredType();
3111 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003112
Chris Lattner7adf0762008-08-04 07:31:14 +00003113 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003114 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3115 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003116 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003117
Chris Lattner7adf0762008-08-04 07:31:14 +00003118 // Otherwise, we have an array and we have qualifiers on it. Push the
3119 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003120 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003121
Chris Lattner7adf0762008-08-04 07:31:14 +00003122 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3123 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3124 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003125 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003126 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3127 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3128 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003129 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003130
Mike Stump11289f42009-09-09 15:08:12 +00003131 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003132 = dyn_cast<DependentSizedArrayType>(ATy))
3133 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003134 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003135 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003136 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003137 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003138 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003139
Chris Lattner7adf0762008-08-04 07:31:14 +00003140 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003141 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003142 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003143 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003144 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003145 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003146}
3147
Chris Lattnera21ad802008-04-02 05:18:44 +00003148/// getArrayDecayedType - Return the properly qualified result of decaying the
3149/// specified array type to a pointer. This operation is non-trivial when
3150/// handling typedefs etc. The canonical type of "T" must be an array type,
3151/// this returns a pointer to a properly qualified element of the array.
3152///
3153/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003154QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003155 // Get the element type with 'getAsArrayType' so that we don't lose any
3156 // typedefs in the element type of the array. This also handles propagation
3157 // of type qualifiers from the array type into the element type if present
3158 // (C99 6.7.3p8).
3159 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3160 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003161
Chris Lattner7adf0762008-08-04 07:31:14 +00003162 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003163
3164 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003165 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003166}
3167
John McCall33ddac02011-01-19 10:06:00 +00003168QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3169 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003170}
3171
John McCall33ddac02011-01-19 10:06:00 +00003172QualType ASTContext::getBaseElementType(QualType type) const {
3173 Qualifiers qs;
3174 while (true) {
3175 SplitQualType split = type.getSplitDesugaredType();
3176 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3177 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003178
John McCall33ddac02011-01-19 10:06:00 +00003179 type = array->getElementType();
3180 qs.addConsistentQualifiers(split.second);
3181 }
Mike Stump11289f42009-09-09 15:08:12 +00003182
John McCall33ddac02011-01-19 10:06:00 +00003183 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003184}
3185
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003186/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003187uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003188ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3189 uint64_t ElementCount = 1;
3190 do {
3191 ElementCount *= CA->getSize().getZExtValue();
3192 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3193 } while (CA);
3194 return ElementCount;
3195}
3196
Steve Naroff0af91202007-04-27 21:51:21 +00003197/// getFloatingRank - Return a relative rank for floating point types.
3198/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003199static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003200 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003201 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003202
John McCall9dd450b2009-09-21 23:43:11 +00003203 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3204 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003205 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003206 case BuiltinType::Float: return FloatRank;
3207 case BuiltinType::Double: return DoubleRank;
3208 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003209 }
3210}
3211
Mike Stump11289f42009-09-09 15:08:12 +00003212/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3213/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003214/// 'typeDomain' is a real floating point or complex type.
3215/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003216QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3217 QualType Domain) const {
3218 FloatingRank EltRank = getFloatingRank(Size);
3219 if (Domain->isComplexType()) {
3220 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003221 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003222 case FloatRank: return FloatComplexTy;
3223 case DoubleRank: return DoubleComplexTy;
3224 case LongDoubleRank: return LongDoubleComplexTy;
3225 }
Steve Naroff0af91202007-04-27 21:51:21 +00003226 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003227
3228 assert(Domain->isRealFloatingType() && "Unknown domain!");
3229 switch (EltRank) {
3230 default: assert(0 && "getFloatingRank(): illegal value for rank");
3231 case FloatRank: return FloatTy;
3232 case DoubleRank: return DoubleTy;
3233 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003234 }
Steve Naroffe4718892007-04-27 18:30:00 +00003235}
3236
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003237/// getFloatingTypeOrder - Compare the rank of the two specified floating
3238/// point types, ignoring the domain of the type (i.e. 'double' ==
3239/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003240/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003241int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003242 FloatingRank LHSR = getFloatingRank(LHS);
3243 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003244
Chris Lattnerb90739d2008-04-06 23:38:49 +00003245 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003246 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003247 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003248 return 1;
3249 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003250}
3251
Chris Lattner76a00cf2008-04-06 22:59:24 +00003252/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3253/// routine will assert if passed a built-in type that isn't an integer or enum,
3254/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003255unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003256 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003257 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003258 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003259
Chris Lattnerad3467e2010-12-25 23:25:43 +00003260 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3261 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003262 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3263
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003264 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3265 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3266
3267 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3268 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3269
Chris Lattner76a00cf2008-04-06 22:59:24 +00003270 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003271 default: assert(0 && "getIntegerRank(): not a built-in integer");
3272 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003273 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003274 case BuiltinType::Char_S:
3275 case BuiltinType::Char_U:
3276 case BuiltinType::SChar:
3277 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003278 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003279 case BuiltinType::Short:
3280 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003281 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003282 case BuiltinType::Int:
3283 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003284 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003285 case BuiltinType::Long:
3286 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003287 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003288 case BuiltinType::LongLong:
3289 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003290 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003291 case BuiltinType::Int128:
3292 case BuiltinType::UInt128:
3293 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003294 }
3295}
3296
Eli Friedman629ffb92009-08-20 04:21:42 +00003297/// \brief Whether this is a promotable bitfield reference according
3298/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3299///
3300/// \returns the type this bit-field will promote to, or NULL if no
3301/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003302QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003303 if (E->isTypeDependent() || E->isValueDependent())
3304 return QualType();
3305
Eli Friedman629ffb92009-08-20 04:21:42 +00003306 FieldDecl *Field = E->getBitField();
3307 if (!Field)
3308 return QualType();
3309
3310 QualType FT = Field->getType();
3311
3312 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3313 uint64_t BitWidth = BitWidthAP.getZExtValue();
3314 uint64_t IntSize = getTypeSize(IntTy);
3315 // GCC extension compatibility: if the bit-field size is less than or equal
3316 // to the size of int, it gets promoted no matter what its type is.
3317 // For instance, unsigned long bf : 4 gets promoted to signed int.
3318 if (BitWidth < IntSize)
3319 return IntTy;
3320
3321 if (BitWidth == IntSize)
3322 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3323
3324 // Types bigger than int are not subject to promotions, and therefore act
3325 // like the base type.
3326 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3327 // is ridiculous.
3328 return QualType();
3329}
3330
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003331/// getPromotedIntegerType - Returns the type that Promotable will
3332/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3333/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003334QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003335 assert(!Promotable.isNull());
3336 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003337 if (const EnumType *ET = Promotable->getAs<EnumType>())
3338 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003339 if (Promotable->isSignedIntegerType())
3340 return IntTy;
3341 uint64_t PromotableSize = getTypeSize(Promotable);
3342 uint64_t IntSize = getTypeSize(IntTy);
3343 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3344 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3345}
3346
Mike Stump11289f42009-09-09 15:08:12 +00003347/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003348/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003349/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003350int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003351 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3352 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003353 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003354
Chris Lattner76a00cf2008-04-06 22:59:24 +00003355 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3356 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003357
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003358 unsigned LHSRank = getIntegerRank(LHSC);
3359 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003360
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003361 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3362 if (LHSRank == RHSRank) return 0;
3363 return LHSRank > RHSRank ? 1 : -1;
3364 }
Mike Stump11289f42009-09-09 15:08:12 +00003365
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003366 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3367 if (LHSUnsigned) {
3368 // If the unsigned [LHS] type is larger, return it.
3369 if (LHSRank >= RHSRank)
3370 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003371
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003372 // If the signed type can represent all values of the unsigned type, it
3373 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003374 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003375 return -1;
3376 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003377
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003378 // If the unsigned [RHS] type is larger, return it.
3379 if (RHSRank >= LHSRank)
3380 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003381
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003382 // If the signed type can represent all values of the unsigned type, it
3383 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003384 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003385 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003386}
Anders Carlsson98f07902007-08-17 05:31:46 +00003387
Anders Carlsson6d417272009-11-14 21:45:58 +00003388static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003389CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3390 DeclContext *DC, IdentifierInfo *Id) {
3391 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003392 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003393 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003394 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003395 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003396}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003397
Mike Stump11289f42009-09-09 15:08:12 +00003398// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003399QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003400 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003401 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003402 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003403 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003404 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003405
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003406 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003407
Anders Carlsson98f07902007-08-17 05:31:46 +00003408 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003409 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003410 // int flags;
3411 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003412 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003413 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003414 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003415 FieldTypes[3] = LongTy;
3416
Anders Carlsson98f07902007-08-17 05:31:46 +00003417 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003418 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003419 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003420 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003421 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003422 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003423 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003424 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003425 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003426 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003427 }
3428
Douglas Gregord5058122010-02-11 01:19:42 +00003429 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003430 }
Mike Stump11289f42009-09-09 15:08:12 +00003431
Anders Carlsson98f07902007-08-17 05:31:46 +00003432 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003433}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003434
Douglas Gregor512b0772009-04-23 22:29:11 +00003435void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003436 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003437 assert(Rec && "Invalid CFConstantStringType");
3438 CFConstantStringTypeDecl = Rec->getDecl();
3439}
3440
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003441// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003442QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003443 if (!NSConstantStringTypeDecl) {
3444 NSConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003445 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003446 &Idents.get("__builtin_NSString"));
3447 NSConstantStringTypeDecl->startDefinition();
3448
3449 QualType FieldTypes[3];
3450
3451 // const int *isa;
3452 FieldTypes[0] = getPointerType(IntTy.withConst());
3453 // const char *str;
3454 FieldTypes[1] = getPointerType(CharTy.withConst());
3455 // unsigned int length;
3456 FieldTypes[2] = UnsignedIntTy;
3457
3458 // Create fields
3459 for (unsigned i = 0; i < 3; ++i) {
3460 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003461 SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003462 SourceLocation(), 0,
3463 FieldTypes[i], /*TInfo=*/0,
3464 /*BitWidth=*/0,
3465 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003466 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003467 NSConstantStringTypeDecl->addDecl(Field);
3468 }
3469
3470 NSConstantStringTypeDecl->completeDefinition();
3471 }
3472
3473 return getTagDeclType(NSConstantStringTypeDecl);
3474}
3475
3476void ASTContext::setNSConstantStringType(QualType T) {
3477 const RecordType *Rec = T->getAs<RecordType>();
3478 assert(Rec && "Invalid NSConstantStringType");
3479 NSConstantStringTypeDecl = Rec->getDecl();
3480}
3481
Jay Foad39c79802011-01-12 09:06:06 +00003482QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003483 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003484 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003485 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003486 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003487 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003488
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003489 QualType FieldTypes[] = {
3490 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003491 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003492 getPointerType(UnsignedLongTy),
3493 getConstantArrayType(UnsignedLongTy,
3494 llvm::APInt(32, 5), ArrayType::Normal, 0)
3495 };
Mike Stump11289f42009-09-09 15:08:12 +00003496
Douglas Gregor91f84212008-12-11 16:49:14 +00003497 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003498 FieldDecl *Field = FieldDecl::Create(*this,
3499 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003500 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003501 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003502 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003503 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003504 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003505 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003506 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003507 }
Mike Stump11289f42009-09-09 15:08:12 +00003508
Douglas Gregord5058122010-02-11 01:19:42 +00003509 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003510 }
Mike Stump11289f42009-09-09 15:08:12 +00003511
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003512 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3513}
3514
Jay Foad39c79802011-01-12 09:06:06 +00003515QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003516 if (BlockDescriptorType)
3517 return getTagDeclType(BlockDescriptorType);
3518
3519 RecordDecl *T;
3520 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003521 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003522 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003523 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003524
3525 QualType FieldTypes[] = {
3526 UnsignedLongTy,
3527 UnsignedLongTy,
3528 };
3529
3530 const char *FieldNames[] = {
3531 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003532 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003533 };
3534
3535 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003536 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003537 SourceLocation(),
3538 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003539 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003540 /*BitWidth=*/0,
3541 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003542 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003543 T->addDecl(Field);
3544 }
3545
Douglas Gregord5058122010-02-11 01:19:42 +00003546 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003547
3548 BlockDescriptorType = T;
3549
3550 return getTagDeclType(BlockDescriptorType);
3551}
3552
3553void ASTContext::setBlockDescriptorType(QualType T) {
3554 const RecordType *Rec = T->getAs<RecordType>();
3555 assert(Rec && "Invalid BlockDescriptorType");
3556 BlockDescriptorType = Rec->getDecl();
3557}
3558
Jay Foad39c79802011-01-12 09:06:06 +00003559QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003560 if (BlockDescriptorExtendedType)
3561 return getTagDeclType(BlockDescriptorExtendedType);
3562
3563 RecordDecl *T;
3564 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003565 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003566 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003567 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003568
3569 QualType FieldTypes[] = {
3570 UnsignedLongTy,
3571 UnsignedLongTy,
3572 getPointerType(VoidPtrTy),
3573 getPointerType(VoidPtrTy)
3574 };
3575
3576 const char *FieldNames[] = {
3577 "reserved",
3578 "Size",
3579 "CopyFuncPtr",
3580 "DestroyFuncPtr"
3581 };
3582
3583 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003584 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003585 SourceLocation(),
3586 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003587 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003588 /*BitWidth=*/0,
3589 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003590 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003591 T->addDecl(Field);
3592 }
3593
Douglas Gregord5058122010-02-11 01:19:42 +00003594 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003595
3596 BlockDescriptorExtendedType = T;
3597
3598 return getTagDeclType(BlockDescriptorExtendedType);
3599}
3600
3601void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3602 const RecordType *Rec = T->getAs<RecordType>();
3603 assert(Rec && "Invalid BlockDescriptorType");
3604 BlockDescriptorExtendedType = Rec->getDecl();
3605}
3606
Jay Foad39c79802011-01-12 09:06:06 +00003607bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003608 if (Ty->isBlockPointerType())
3609 return true;
3610 if (isObjCNSObjectType(Ty))
3611 return true;
3612 if (Ty->isObjCObjectPointerType())
3613 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003614 if (getLangOptions().CPlusPlus) {
3615 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3616 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3617 return RD->hasConstCopyConstructor(*this);
3618
3619 }
3620 }
Mike Stump94967902009-10-21 18:16:27 +00003621 return false;
3622}
3623
Jay Foad39c79802011-01-12 09:06:06 +00003624QualType
3625ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003626 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003627 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003628 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003629 // unsigned int __flags;
3630 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003631 // void *__copy_helper; // as needed
3632 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003633 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003634 // } *
3635
Mike Stump94967902009-10-21 18:16:27 +00003636 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3637
3638 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003639 llvm::SmallString<36> Name;
3640 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3641 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003642 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003643 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003644 T->startDefinition();
3645 QualType Int32Ty = IntTy;
3646 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3647 QualType FieldTypes[] = {
3648 getPointerType(VoidPtrTy),
3649 getPointerType(getTagDeclType(T)),
3650 Int32Ty,
3651 Int32Ty,
3652 getPointerType(VoidPtrTy),
3653 getPointerType(VoidPtrTy),
3654 Ty
3655 };
3656
Daniel Dunbar56df9772010-08-17 22:39:59 +00003657 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003658 "__isa",
3659 "__forwarding",
3660 "__flags",
3661 "__size",
3662 "__copy_helper",
3663 "__destroy_helper",
3664 DeclName,
3665 };
3666
3667 for (size_t i = 0; i < 7; ++i) {
3668 if (!HasCopyAndDispose && i >=4 && i <= 5)
3669 continue;
3670 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003671 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003672 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003673 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003674 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003675 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003676 T->addDecl(Field);
3677 }
3678
Douglas Gregord5058122010-02-11 01:19:42 +00003679 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003680
3681 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003682}
3683
Douglas Gregor512b0772009-04-23 22:29:11 +00003684void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003685 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003686 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3687 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3688}
3689
Anders Carlsson18acd442007-10-29 06:33:42 +00003690// This returns true if a type has been typedefed to BOOL:
3691// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003692static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003693 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003694 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3695 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003696
Anders Carlssond8499822007-10-29 05:01:08 +00003697 return false;
3698}
3699
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003700/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003701/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003702CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003703 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003704
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003705 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003706 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003707 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003708 // Treat arrays as pointers, since that's how they're passed in.
3709 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003710 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003711 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003712}
3713
3714static inline
3715std::string charUnitsToString(const CharUnits &CU) {
3716 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003717}
3718
John McCall351762c2011-02-07 10:33:21 +00003719/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003720/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003721std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3722 std::string S;
3723
David Chisnall950a9512009-11-17 19:33:30 +00003724 const BlockDecl *Decl = Expr->getBlockDecl();
3725 QualType BlockTy =
3726 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3727 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003728 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003729 // Compute size of all parameters.
3730 // Start with computing size of a pointer in number of bytes.
3731 // FIXME: There might(should) be a better way of doing this computation!
3732 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003733 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3734 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003735 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003736 E = Decl->param_end(); PI != E; ++PI) {
3737 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003738 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003739 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003740 ParmOffset += sz;
3741 }
3742 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003743 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003744 // Block pointer and offset.
3745 S += "@?0";
3746 ParmOffset = PtrSize;
3747
3748 // Argument types.
3749 ParmOffset = PtrSize;
3750 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3751 Decl->param_end(); PI != E; ++PI) {
3752 ParmVarDecl *PVDecl = *PI;
3753 QualType PType = PVDecl->getOriginalType();
3754 if (const ArrayType *AT =
3755 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3756 // Use array's original type only if it has known number of
3757 // elements.
3758 if (!isa<ConstantArrayType>(AT))
3759 PType = PVDecl->getType();
3760 } else if (PType->isFunctionType())
3761 PType = PVDecl->getType();
3762 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003763 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003764 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003765 }
John McCall351762c2011-02-07 10:33:21 +00003766
3767 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003768}
3769
David Chisnall50e4eba2010-12-30 14:05:53 +00003770void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3771 std::string& S) {
3772 // Encode result type.
3773 getObjCEncodingForType(Decl->getResultType(), S);
3774 CharUnits ParmOffset;
3775 // Compute size of all parameters.
3776 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3777 E = Decl->param_end(); PI != E; ++PI) {
3778 QualType PType = (*PI)->getType();
3779 CharUnits sz = getObjCEncodingTypeSize(PType);
3780 assert (sz.isPositive() &&
3781 "getObjCEncodingForMethodDecl - Incomplete param type");
3782 ParmOffset += sz;
3783 }
3784 S += charUnitsToString(ParmOffset);
3785 ParmOffset = CharUnits::Zero();
3786
3787 // Argument types.
3788 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3789 E = Decl->param_end(); PI != E; ++PI) {
3790 ParmVarDecl *PVDecl = *PI;
3791 QualType PType = PVDecl->getOriginalType();
3792 if (const ArrayType *AT =
3793 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3794 // Use array's original type only if it has known number of
3795 // elements.
3796 if (!isa<ConstantArrayType>(AT))
3797 PType = PVDecl->getType();
3798 } else if (PType->isFunctionType())
3799 PType = PVDecl->getType();
3800 getObjCEncodingForType(PType, S);
3801 S += charUnitsToString(ParmOffset);
3802 ParmOffset += getObjCEncodingTypeSize(PType);
3803 }
3804}
3805
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003806/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003807/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003808void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003809 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003810 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003811 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003812 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003813 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003814 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003815 // Compute size of all parameters.
3816 // Start with computing size of a pointer in number of bytes.
3817 // FIXME: There might(should) be a better way of doing this computation!
3818 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003819 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003820 // The first two arguments (self and _cmd) are pointers; account for
3821 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003822 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003823 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003824 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003825 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003826 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003827 assert (sz.isPositive() &&
3828 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003829 ParmOffset += sz;
3830 }
Ken Dyck40775002010-01-11 17:06:35 +00003831 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003832 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003833 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003834
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003835 // Argument types.
3836 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003837 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003838 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003839 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003840 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003841 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003842 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3843 // Use array's original type only if it has known number of
3844 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003845 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003846 PType = PVDecl->getType();
3847 } else if (PType->isFunctionType())
3848 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003849 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003850 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003851 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003852 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003853 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003854 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003855 }
3856}
3857
Daniel Dunbar4932b362008-08-28 04:38:10 +00003858/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003859/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003860/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3861/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003862/// Property attributes are stored as a comma-delimited C string. The simple
3863/// attributes readonly and bycopy are encoded as single characters. The
3864/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3865/// encoded as single characters, followed by an identifier. Property types
3866/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003867/// these attributes are defined by the following enumeration:
3868/// @code
3869/// enum PropertyAttributes {
3870/// kPropertyReadOnly = 'R', // property is read-only.
3871/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3872/// kPropertyByref = '&', // property is a reference to the value last assigned
3873/// kPropertyDynamic = 'D', // property is dynamic
3874/// kPropertyGetter = 'G', // followed by getter selector name
3875/// kPropertySetter = 'S', // followed by setter selector name
3876/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3877/// kPropertyType = 't' // followed by old-style type encoding.
3878/// kPropertyWeak = 'W' // 'weak' property
3879/// kPropertyStrong = 'P' // property GC'able
3880/// kPropertyNonAtomic = 'N' // property non-atomic
3881/// };
3882/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003883void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003884 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003885 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003886 // Collect information from the property implementation decl(s).
3887 bool Dynamic = false;
3888 ObjCPropertyImplDecl *SynthesizePID = 0;
3889
3890 // FIXME: Duplicated code due to poor abstraction.
3891 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003892 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003893 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3894 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003895 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003896 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003897 ObjCPropertyImplDecl *PID = *i;
3898 if (PID->getPropertyDecl() == PD) {
3899 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3900 Dynamic = true;
3901 } else {
3902 SynthesizePID = PID;
3903 }
3904 }
3905 }
3906 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003907 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003908 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003909 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003910 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003911 ObjCPropertyImplDecl *PID = *i;
3912 if (PID->getPropertyDecl() == PD) {
3913 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3914 Dynamic = true;
3915 } else {
3916 SynthesizePID = PID;
3917 }
3918 }
Mike Stump11289f42009-09-09 15:08:12 +00003919 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003920 }
3921 }
3922
3923 // FIXME: This is not very efficient.
3924 S = "T";
3925
3926 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003927 // GCC has some special rules regarding encoding of properties which
3928 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003929 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003930 true /* outermost type */,
3931 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003932
3933 if (PD->isReadOnly()) {
3934 S += ",R";
3935 } else {
3936 switch (PD->getSetterKind()) {
3937 case ObjCPropertyDecl::Assign: break;
3938 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003939 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003940 }
3941 }
3942
3943 // It really isn't clear at all what this means, since properties
3944 // are "dynamic by default".
3945 if (Dynamic)
3946 S += ",D";
3947
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003948 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3949 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003950
Daniel Dunbar4932b362008-08-28 04:38:10 +00003951 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3952 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003953 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003954 }
3955
3956 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3957 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003958 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003959 }
3960
3961 if (SynthesizePID) {
3962 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3963 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003964 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003965 }
3966
3967 // FIXME: OBJCGC: weak & strong
3968}
3969
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003970/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003971/// Another legacy compatibility encoding: 32-bit longs are encoded as
3972/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003973/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3974///
3975void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003976 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003977 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00003978 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003979 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003980 else
Jay Foad39c79802011-01-12 09:06:06 +00003981 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003982 PointeeTy = IntTy;
3983 }
3984 }
3985}
3986
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003987void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00003988 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003989 // We follow the behavior of gcc, expanding structures which are
3990 // directly pointed to, and expanding embedded structures. Note that
3991 // these rules are sufficient to prevent recursive encoding of the
3992 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003993 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003994 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003995}
3996
David Chisnallb190a2c2010-06-04 01:10:52 +00003997static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3998 switch (T->getAs<BuiltinType>()->getKind()) {
3999 default: assert(0 && "Unhandled builtin type kind");
4000 case BuiltinType::Void: return 'v';
4001 case BuiltinType::Bool: return 'B';
4002 case BuiltinType::Char_U:
4003 case BuiltinType::UChar: return 'C';
4004 case BuiltinType::UShort: return 'S';
4005 case BuiltinType::UInt: return 'I';
4006 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004007 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004008 case BuiltinType::UInt128: return 'T';
4009 case BuiltinType::ULongLong: return 'Q';
4010 case BuiltinType::Char_S:
4011 case BuiltinType::SChar: return 'c';
4012 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004013 case BuiltinType::WChar_S:
4014 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004015 case BuiltinType::Int: return 'i';
4016 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004017 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004018 case BuiltinType::LongLong: return 'q';
4019 case BuiltinType::Int128: return 't';
4020 case BuiltinType::Float: return 'f';
4021 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004022 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004023 }
4024}
4025
Jay Foad39c79802011-01-12 09:06:06 +00004026static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004027 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004028 const Expr *E = FD->getBitWidth();
4029 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004030 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004031 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4032 // The GNU runtime requires more information; bitfields are encoded as b,
4033 // then the offset (in bits) of the first element, then the type of the
4034 // bitfield, then the size in bits. For example, in this structure:
4035 //
4036 // struct
4037 // {
4038 // int integer;
4039 // int flags:2;
4040 // };
4041 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4042 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4043 // information is not especially sensible, but we're stuck with it for
4044 // compatibility with GCC, although providing it breaks anything that
4045 // actually uses runtime introspection and wants to work on both runtimes...
4046 if (!Ctx->getLangOptions().NeXTRuntime) {
4047 const RecordDecl *RD = FD->getParent();
4048 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4049 // FIXME: This same linear search is also used in ExprConstant - it might
4050 // be better if the FieldDecl stored its offset. We'd be increasing the
4051 // size of the object slightly, but saving some time every time it is used.
4052 unsigned i = 0;
4053 for (RecordDecl::field_iterator Field = RD->field_begin(),
4054 FieldEnd = RD->field_end();
4055 Field != FieldEnd; (void)++Field, ++i) {
4056 if (*Field == FD)
4057 break;
4058 }
4059 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004060 if (T->isEnumeralType())
4061 S += 'i';
4062 else
Jay Foad39c79802011-01-12 09:06:06 +00004063 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004064 }
4065 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004066 S += llvm::utostr(N);
4067}
4068
Daniel Dunbar07d07852009-10-18 21:17:35 +00004069// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004070void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4071 bool ExpandPointedToStructures,
4072 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004073 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004074 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00004075 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004076 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004077 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004078 return EncodeBitField(this, S, T, FD);
4079 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004080 return;
4081 }
Mike Stump11289f42009-09-09 15:08:12 +00004082
John McCall9dd450b2009-09-21 23:43:11 +00004083 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004084 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004085 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004086 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004087 return;
4088 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004089
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004090 // encoding for pointer or r3eference types.
4091 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004092 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004093 if (PT->isObjCSelType()) {
4094 S += ':';
4095 return;
4096 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004097 PointeeTy = PT->getPointeeType();
4098 }
4099 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4100 PointeeTy = RT->getPointeeType();
4101 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004102 bool isReadOnly = false;
4103 // For historical/compatibility reasons, the read-only qualifier of the
4104 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4105 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004106 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004107 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004108 if (OutermostType && T.isConstQualified()) {
4109 isReadOnly = true;
4110 S += 'r';
4111 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004112 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004113 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004114 while (P->getAs<PointerType>())
4115 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004116 if (P.isConstQualified()) {
4117 isReadOnly = true;
4118 S += 'r';
4119 }
4120 }
4121 if (isReadOnly) {
4122 // Another legacy compatibility encoding. Some ObjC qualifier and type
4123 // combinations need to be rearranged.
4124 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004125 if (llvm::StringRef(S).endswith("nr"))
4126 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004127 }
Mike Stump11289f42009-09-09 15:08:12 +00004128
Anders Carlssond8499822007-10-29 05:01:08 +00004129 if (PointeeTy->isCharType()) {
4130 // char pointer types should be encoded as '*' unless it is a
4131 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004132 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004133 S += '*';
4134 return;
4135 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004136 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004137 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4138 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4139 S += '#';
4140 return;
4141 }
4142 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4143 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4144 S += '@';
4145 return;
4146 }
4147 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004148 }
Anders Carlssond8499822007-10-29 05:01:08 +00004149 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004150 getLegacyIntegralTypeEncoding(PointeeTy);
4151
Mike Stump11289f42009-09-09 15:08:12 +00004152 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004153 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004154 return;
4155 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004156
Chris Lattnere7cabb92009-07-13 00:10:46 +00004157 if (const ArrayType *AT =
4158 // Ignore type qualifiers etc.
4159 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004160 if (isa<IncompleteArrayType>(AT)) {
4161 // Incomplete arrays are encoded as a pointer to the array element.
4162 S += '^';
4163
Mike Stump11289f42009-09-09 15:08:12 +00004164 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004165 false, ExpandStructures, FD);
4166 } else {
4167 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004168
Anders Carlssond05f44b2009-02-22 01:38:57 +00004169 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4170 S += llvm::utostr(CAT->getSize().getZExtValue());
4171 else {
4172 //Variable length arrays are encoded as a regular array with 0 elements.
4173 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4174 S += '0';
4175 }
Mike Stump11289f42009-09-09 15:08:12 +00004176
4177 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004178 false, ExpandStructures, FD);
4179 S += ']';
4180 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004181 return;
4182 }
Mike Stump11289f42009-09-09 15:08:12 +00004183
John McCall9dd450b2009-09-21 23:43:11 +00004184 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004185 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004186 return;
4187 }
Mike Stump11289f42009-09-09 15:08:12 +00004188
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004189 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004190 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004191 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004192 // Anonymous structures print as '?'
4193 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4194 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004195 if (ClassTemplateSpecializationDecl *Spec
4196 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4197 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4198 std::string TemplateArgsStr
4199 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004200 TemplateArgs.data(),
4201 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004202 (*this).PrintingPolicy);
4203
4204 S += TemplateArgsStr;
4205 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004206 } else {
4207 S += '?';
4208 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004209 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004210 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004211 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4212 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004213 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004214 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004215 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004216 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004217 S += '"';
4218 }
Mike Stump11289f42009-09-09 15:08:12 +00004219
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004220 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004221 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004222 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004223 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004224 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004225 QualType qt = Field->getType();
4226 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004227 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004228 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004229 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004230 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004231 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004232 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004233 return;
4234 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004235
Chris Lattnere7cabb92009-07-13 00:10:46 +00004236 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004237 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004238 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004239 else
4240 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004241 return;
4242 }
Mike Stump11289f42009-09-09 15:08:12 +00004243
Chris Lattnere7cabb92009-07-13 00:10:46 +00004244 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004245 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004246 return;
4247 }
Mike Stump11289f42009-09-09 15:08:12 +00004248
John McCall8b07ec22010-05-15 11:32:37 +00004249 // Ignore protocol qualifiers when mangling at this level.
4250 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4251 T = OT->getBaseType();
4252
John McCall8ccfcb52009-09-24 19:53:00 +00004253 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004254 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004255 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004256 S += '{';
4257 const IdentifierInfo *II = OI->getIdentifier();
4258 S += II->getName();
4259 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004260 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4261 DeepCollectObjCIvars(OI, true, Ivars);
4262 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4263 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4264 if (Field->isBitField())
4265 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004266 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004267 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004268 }
4269 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004270 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004271 }
Mike Stump11289f42009-09-09 15:08:12 +00004272
John McCall9dd450b2009-09-21 23:43:11 +00004273 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004274 if (OPT->isObjCIdType()) {
4275 S += '@';
4276 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004277 }
Mike Stump11289f42009-09-09 15:08:12 +00004278
Steve Narofff0c86112009-10-28 22:03:49 +00004279 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4280 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4281 // Since this is a binary compatibility issue, need to consult with runtime
4282 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004283 S += '#';
4284 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004285 }
Mike Stump11289f42009-09-09 15:08:12 +00004286
Chris Lattnere7cabb92009-07-13 00:10:46 +00004287 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004288 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004289 ExpandPointedToStructures,
4290 ExpandStructures, FD);
4291 if (FD || EncodingProperty) {
4292 // Note that we do extended encoding of protocol qualifer list
4293 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004294 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004295 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4296 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004297 S += '<';
4298 S += (*I)->getNameAsString();
4299 S += '>';
4300 }
4301 S += '"';
4302 }
4303 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004304 }
Mike Stump11289f42009-09-09 15:08:12 +00004305
Chris Lattnere7cabb92009-07-13 00:10:46 +00004306 QualType PointeeTy = OPT->getPointeeType();
4307 if (!EncodingProperty &&
4308 isa<TypedefType>(PointeeTy.getTypePtr())) {
4309 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004310 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004311 // {...};
4312 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004313 getObjCEncodingForTypeImpl(PointeeTy, S,
4314 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004315 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004316 return;
4317 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004318
4319 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004320 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004321 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004322 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004323 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4324 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004325 S += '<';
4326 S += (*I)->getNameAsString();
4327 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004328 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004329 S += '"';
4330 }
4331 return;
4332 }
Mike Stump11289f42009-09-09 15:08:12 +00004333
John McCalla9e6e8d2010-05-17 23:56:34 +00004334 // gcc just blithely ignores member pointers.
4335 // TODO: maybe there should be a mangling for these
4336 if (T->getAs<MemberPointerType>())
4337 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004338
4339 if (T->isVectorType()) {
4340 // This matches gcc's encoding, even though technically it is
4341 // insufficient.
4342 // FIXME. We should do a better job than gcc.
4343 return;
4344 }
4345
Chris Lattnere7cabb92009-07-13 00:10:46 +00004346 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004347}
4348
Mike Stump11289f42009-09-09 15:08:12 +00004349void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004350 std::string& S) const {
4351 if (QT & Decl::OBJC_TQ_In)
4352 S += 'n';
4353 if (QT & Decl::OBJC_TQ_Inout)
4354 S += 'N';
4355 if (QT & Decl::OBJC_TQ_Out)
4356 S += 'o';
4357 if (QT & Decl::OBJC_TQ_Bycopy)
4358 S += 'O';
4359 if (QT & Decl::OBJC_TQ_Byref)
4360 S += 'R';
4361 if (QT & Decl::OBJC_TQ_Oneway)
4362 S += 'V';
4363}
4364
Chris Lattnere7cabb92009-07-13 00:10:46 +00004365void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004366 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004367
Anders Carlsson87c149b2007-10-11 01:00:40 +00004368 BuiltinVaListType = T;
4369}
4370
Chris Lattnere7cabb92009-07-13 00:10:46 +00004371void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004372 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004373}
4374
Chris Lattnere7cabb92009-07-13 00:10:46 +00004375void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004376 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004377}
4378
Chris Lattnere7cabb92009-07-13 00:10:46 +00004379void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004380 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004381}
4382
Chris Lattnere7cabb92009-07-13 00:10:46 +00004383void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004384 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004385}
4386
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004387void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004388 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004389 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004390
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004391 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004392}
4393
John McCalld28ae272009-12-02 08:04:21 +00004394/// \brief Retrieve the template name that corresponds to a non-empty
4395/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004396TemplateName
4397ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4398 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004399 unsigned size = End - Begin;
4400 assert(size > 1 && "set is not overloaded!");
4401
4402 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4403 size * sizeof(FunctionTemplateDecl*));
4404 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4405
4406 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004407 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004408 NamedDecl *D = *I;
4409 assert(isa<FunctionTemplateDecl>(D) ||
4410 (isa<UsingShadowDecl>(D) &&
4411 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4412 *Storage++ = D;
4413 }
4414
4415 return TemplateName(OT);
4416}
4417
Douglas Gregordc572a32009-03-30 22:58:21 +00004418/// \brief Retrieve the template name that represents a qualified
4419/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004420TemplateName
4421ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4422 bool TemplateKeyword,
4423 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004424 assert(NNS && "Missing nested-name-specifier in qualified template name");
4425
Douglas Gregorc42075a2010-02-04 18:10:26 +00004426 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004427 llvm::FoldingSetNodeID ID;
4428 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4429
4430 void *InsertPos = 0;
4431 QualifiedTemplateName *QTN =
4432 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4433 if (!QTN) {
4434 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4435 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4436 }
4437
4438 return TemplateName(QTN);
4439}
4440
4441/// \brief Retrieve the template name that represents a dependent
4442/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004443TemplateName
4444ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4445 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004446 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004447 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004448
4449 llvm::FoldingSetNodeID ID;
4450 DependentTemplateName::Profile(ID, NNS, Name);
4451
4452 void *InsertPos = 0;
4453 DependentTemplateName *QTN =
4454 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4455
4456 if (QTN)
4457 return TemplateName(QTN);
4458
4459 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4460 if (CanonNNS == NNS) {
4461 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4462 } else {
4463 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4464 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004465 DependentTemplateName *CheckQTN =
4466 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4467 assert(!CheckQTN && "Dependent type name canonicalization broken");
4468 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004469 }
4470
4471 DependentTemplateNames.InsertNode(QTN, InsertPos);
4472 return TemplateName(QTN);
4473}
4474
Douglas Gregor71395fa2009-11-04 00:56:37 +00004475/// \brief Retrieve the template name that represents a dependent
4476/// template name such as \c MetaFun::template operator+.
4477TemplateName
4478ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004479 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004480 assert((!NNS || NNS->isDependent()) &&
4481 "Nested name specifier must be dependent");
4482
4483 llvm::FoldingSetNodeID ID;
4484 DependentTemplateName::Profile(ID, NNS, Operator);
4485
4486 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004487 DependentTemplateName *QTN
4488 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004489
4490 if (QTN)
4491 return TemplateName(QTN);
4492
4493 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4494 if (CanonNNS == NNS) {
4495 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4496 } else {
4497 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4498 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004499
4500 DependentTemplateName *CheckQTN
4501 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4502 assert(!CheckQTN && "Dependent template name canonicalization broken");
4503 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004504 }
4505
4506 DependentTemplateNames.InsertNode(QTN, InsertPos);
4507 return TemplateName(QTN);
4508}
4509
Douglas Gregor5590be02011-01-15 06:45:20 +00004510TemplateName
4511ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4512 const TemplateArgument &ArgPack) const {
4513 ASTContext &Self = const_cast<ASTContext &>(*this);
4514 llvm::FoldingSetNodeID ID;
4515 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4516
4517 void *InsertPos = 0;
4518 SubstTemplateTemplateParmPackStorage *Subst
4519 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4520
4521 if (!Subst) {
4522 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4523 ArgPack.pack_size(),
4524 ArgPack.pack_begin());
4525 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4526 }
4527
4528 return TemplateName(Subst);
4529}
4530
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004531/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004532/// TargetInfo, produce the corresponding type. The unsigned @p Type
4533/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004534CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004535 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004536 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004537 case TargetInfo::SignedShort: return ShortTy;
4538 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4539 case TargetInfo::SignedInt: return IntTy;
4540 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4541 case TargetInfo::SignedLong: return LongTy;
4542 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4543 case TargetInfo::SignedLongLong: return LongLongTy;
4544 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4545 }
4546
4547 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004548 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004549}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004550
4551//===----------------------------------------------------------------------===//
4552// Type Predicates.
4553//===----------------------------------------------------------------------===//
4554
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004555/// isObjCNSObjectType - Return true if this is an NSObject object using
4556/// NSObject attribute on a c-style pointer type.
4557/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004558/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004559///
4560bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCall424cec92011-01-19 06:33:43 +00004561 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004562 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004563 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004564 return true;
4565 }
Mike Stump11289f42009-09-09 15:08:12 +00004566 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004567}
4568
Fariborz Jahanian96207692009-02-18 21:49:28 +00004569/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4570/// garbage collection attribute.
4571///
John McCall553d45a2011-01-12 00:34:59 +00004572Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4573 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4574 return Qualifiers::GCNone;
4575
4576 assert(getLangOptions().ObjC1);
4577 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4578
4579 // Default behaviour under objective-C's gc is for ObjC pointers
4580 // (or pointers to them) be treated as though they were declared
4581 // as __strong.
4582 if (GCAttrs == Qualifiers::GCNone) {
4583 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4584 return Qualifiers::Strong;
4585 else if (Ty->isPointerType())
4586 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4587 } else {
4588 // It's not valid to set GC attributes on anything that isn't a
4589 // pointer.
4590#ifndef NDEBUG
4591 QualType CT = Ty->getCanonicalTypeInternal();
4592 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4593 CT = AT->getElementType();
4594 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4595#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004596 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004597 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004598}
4599
Chris Lattner49af6a42008-04-07 06:51:04 +00004600//===----------------------------------------------------------------------===//
4601// Type Compatibility Testing
4602//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004603
Mike Stump11289f42009-09-09 15:08:12 +00004604/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004605/// compatible.
4606static bool areCompatVectorTypes(const VectorType *LHS,
4607 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004608 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004609 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004610 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004611}
4612
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004613bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4614 QualType SecondVec) {
4615 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4616 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4617
4618 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4619 return true;
4620
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004621 // Treat Neon vector types and most AltiVec vector types as if they are the
4622 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004623 const VectorType *First = FirstVec->getAs<VectorType>();
4624 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004625 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004626 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004627 First->getVectorKind() != VectorType::AltiVecPixel &&
4628 First->getVectorKind() != VectorType::AltiVecBool &&
4629 Second->getVectorKind() != VectorType::AltiVecPixel &&
4630 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004631 return true;
4632
4633 return false;
4634}
4635
Steve Naroff8e6aee52009-07-23 01:01:38 +00004636//===----------------------------------------------------------------------===//
4637// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4638//===----------------------------------------------------------------------===//
4639
4640/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4641/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004642bool
4643ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4644 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004645 if (lProto == rProto)
4646 return true;
4647 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4648 E = rProto->protocol_end(); PI != E; ++PI)
4649 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4650 return true;
4651 return false;
4652}
4653
Steve Naroff8e6aee52009-07-23 01:01:38 +00004654/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4655/// return true if lhs's protocols conform to rhs's protocol; false
4656/// otherwise.
4657bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4658 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4659 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4660 return false;
4661}
4662
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004663/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4664/// Class<p1, ...>.
4665bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4666 QualType rhs) {
4667 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4668 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4669 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4670
4671 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4672 E = lhsQID->qual_end(); I != E; ++I) {
4673 bool match = false;
4674 ObjCProtocolDecl *lhsProto = *I;
4675 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4676 E = rhsOPT->qual_end(); J != E; ++J) {
4677 ObjCProtocolDecl *rhsProto = *J;
4678 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4679 match = true;
4680 break;
4681 }
4682 }
4683 if (!match)
4684 return false;
4685 }
4686 return true;
4687}
4688
Steve Naroff8e6aee52009-07-23 01:01:38 +00004689/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4690/// ObjCQualifiedIDType.
4691bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4692 bool compare) {
4693 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004694 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004695 lhs->isObjCIdType() || lhs->isObjCClassType())
4696 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004697 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004698 rhs->isObjCIdType() || rhs->isObjCClassType())
4699 return true;
4700
4701 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004702 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004703
Steve Naroff8e6aee52009-07-23 01:01:38 +00004704 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004705
Steve Naroff8e6aee52009-07-23 01:01:38 +00004706 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004707 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004708 // make sure we check the class hierarchy.
4709 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4710 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4711 E = lhsQID->qual_end(); I != E; ++I) {
4712 // when comparing an id<P> on lhs with a static type on rhs,
4713 // see if static class implements all of id's protocols, directly or
4714 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004715 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004716 return false;
4717 }
4718 }
4719 // If there are no qualifiers and no interface, we have an 'id'.
4720 return true;
4721 }
Mike Stump11289f42009-09-09 15:08:12 +00004722 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004723 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4724 E = lhsQID->qual_end(); I != E; ++I) {
4725 ObjCProtocolDecl *lhsProto = *I;
4726 bool match = false;
4727
4728 // when comparing an id<P> on lhs with a static type on rhs,
4729 // see if static class implements all of id's protocols, directly or
4730 // through its super class and categories.
4731 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4732 E = rhsOPT->qual_end(); J != E; ++J) {
4733 ObjCProtocolDecl *rhsProto = *J;
4734 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4735 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4736 match = true;
4737 break;
4738 }
4739 }
Mike Stump11289f42009-09-09 15:08:12 +00004740 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004741 // make sure we check the class hierarchy.
4742 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4743 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4744 E = lhsQID->qual_end(); I != E; ++I) {
4745 // when comparing an id<P> on lhs with a static type on rhs,
4746 // see if static class implements all of id's protocols, directly or
4747 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004748 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004749 match = true;
4750 break;
4751 }
4752 }
4753 }
4754 if (!match)
4755 return false;
4756 }
Mike Stump11289f42009-09-09 15:08:12 +00004757
Steve Naroff8e6aee52009-07-23 01:01:38 +00004758 return true;
4759 }
Mike Stump11289f42009-09-09 15:08:12 +00004760
Steve Naroff8e6aee52009-07-23 01:01:38 +00004761 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4762 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4763
Mike Stump11289f42009-09-09 15:08:12 +00004764 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004765 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004766 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004767 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4768 E = lhsOPT->qual_end(); I != E; ++I) {
4769 ObjCProtocolDecl *lhsProto = *I;
4770 bool match = false;
4771
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004772 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004773 // see if static class implements all of id's protocols, directly or
4774 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004775 // First, lhs protocols in the qualifier list must be found, direct
4776 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004777 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4778 E = rhsQID->qual_end(); J != E; ++J) {
4779 ObjCProtocolDecl *rhsProto = *J;
4780 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4781 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4782 match = true;
4783 break;
4784 }
4785 }
4786 if (!match)
4787 return false;
4788 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004789
4790 // Static class's protocols, or its super class or category protocols
4791 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4792 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4793 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4794 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4795 // This is rather dubious but matches gcc's behavior. If lhs has
4796 // no type qualifier and its class has no static protocol(s)
4797 // assume that it is mismatch.
4798 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4799 return false;
4800 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4801 LHSInheritedProtocols.begin(),
4802 E = LHSInheritedProtocols.end(); I != E; ++I) {
4803 bool match = false;
4804 ObjCProtocolDecl *lhsProto = (*I);
4805 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4806 E = rhsQID->qual_end(); J != E; ++J) {
4807 ObjCProtocolDecl *rhsProto = *J;
4808 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4809 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4810 match = true;
4811 break;
4812 }
4813 }
4814 if (!match)
4815 return false;
4816 }
4817 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004818 return true;
4819 }
4820 return false;
4821}
4822
Eli Friedman47f77112008-08-22 00:56:42 +00004823/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004824/// compatible for assignment from RHS to LHS. This handles validation of any
4825/// protocol qualifiers on the LHS or RHS.
4826///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004827bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4828 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004829 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4830 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4831
Steve Naroff1329fa02009-07-15 18:40:39 +00004832 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004833 if (LHS->isObjCUnqualifiedIdOrClass() ||
4834 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004835 return true;
4836
John McCall8b07ec22010-05-15 11:32:37 +00004837 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004838 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4839 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004840 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004841
4842 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4843 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4844 QualType(RHSOPT,0));
4845
John McCall8b07ec22010-05-15 11:32:37 +00004846 // If we have 2 user-defined types, fall into that path.
4847 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004848 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004849
Steve Naroff8e6aee52009-07-23 01:01:38 +00004850 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004851}
4852
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004853/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4854/// for providing type-safty for objective-c pointers used to pass/return
4855/// arguments in block literals. When passed as arguments, passing 'A*' where
4856/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4857/// not OK. For the return type, the opposite is not OK.
4858bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4859 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004860 const ObjCObjectPointerType *RHSOPT,
4861 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004862 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004863 return true;
4864
4865 if (LHSOPT->isObjCBuiltinType()) {
4866 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4867 }
4868
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004869 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004870 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4871 QualType(RHSOPT,0),
4872 false);
4873
4874 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4875 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4876 if (LHS && RHS) { // We have 2 user-defined types.
4877 if (LHS != RHS) {
4878 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004879 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004880 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004881 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004882 }
4883 else
4884 return true;
4885 }
4886 return false;
4887}
4888
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004889/// getIntersectionOfProtocols - This routine finds the intersection of set
4890/// of protocols inherited from two distinct objective-c pointer objects.
4891/// It is used to build composite qualifier list of the composite type of
4892/// the conditional expression involving two objective-c pointer objects.
4893static
4894void getIntersectionOfProtocols(ASTContext &Context,
4895 const ObjCObjectPointerType *LHSOPT,
4896 const ObjCObjectPointerType *RHSOPT,
4897 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4898
John McCall8b07ec22010-05-15 11:32:37 +00004899 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4900 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4901 assert(LHS->getInterface() && "LHS must have an interface base");
4902 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004903
4904 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4905 unsigned LHSNumProtocols = LHS->getNumProtocols();
4906 if (LHSNumProtocols > 0)
4907 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4908 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004909 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004910 Context.CollectInheritedProtocols(LHS->getInterface(),
4911 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004912 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4913 LHSInheritedProtocols.end());
4914 }
4915
4916 unsigned RHSNumProtocols = RHS->getNumProtocols();
4917 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004918 ObjCProtocolDecl **RHSProtocols =
4919 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004920 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4921 if (InheritedProtocolSet.count(RHSProtocols[i]))
4922 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4923 }
4924 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004925 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004926 Context.CollectInheritedProtocols(RHS->getInterface(),
4927 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004928 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4929 RHSInheritedProtocols.begin(),
4930 E = RHSInheritedProtocols.end(); I != E; ++I)
4931 if (InheritedProtocolSet.count((*I)))
4932 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004933 }
4934}
4935
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004936/// areCommonBaseCompatible - Returns common base class of the two classes if
4937/// one found. Note that this is O'2 algorithm. But it will be called as the
4938/// last type comparison in a ?-exp of ObjC pointer types before a
4939/// warning is issued. So, its invokation is extremely rare.
4940QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004941 const ObjCObjectPointerType *Lptr,
4942 const ObjCObjectPointerType *Rptr) {
4943 const ObjCObjectType *LHS = Lptr->getObjectType();
4944 const ObjCObjectType *RHS = Rptr->getObjectType();
4945 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4946 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4947 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004948 return QualType();
4949
John McCall8b07ec22010-05-15 11:32:37 +00004950 while ((LDecl = LDecl->getSuperClass())) {
4951 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004952 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004953 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4954 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4955
4956 QualType Result = QualType(LHS, 0);
4957 if (!Protocols.empty())
4958 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4959 Result = getObjCObjectPointerType(Result);
4960 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004961 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004962 }
4963
4964 return QualType();
4965}
4966
John McCall8b07ec22010-05-15 11:32:37 +00004967bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4968 const ObjCObjectType *RHS) {
4969 assert(LHS->getInterface() && "LHS is not an interface type");
4970 assert(RHS->getInterface() && "RHS is not an interface type");
4971
Chris Lattner49af6a42008-04-07 06:51:04 +00004972 // Verify that the base decls are compatible: the RHS must be a subclass of
4973 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004974 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004975 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004976
Chris Lattner49af6a42008-04-07 06:51:04 +00004977 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4978 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004979 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004980 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004981
Chris Lattner49af6a42008-04-07 06:51:04 +00004982 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4983 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004984 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004985 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004986
John McCall8b07ec22010-05-15 11:32:37 +00004987 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4988 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004989 LHSPI != LHSPE; LHSPI++) {
4990 bool RHSImplementsProtocol = false;
4991
4992 // If the RHS doesn't implement the protocol on the left, the types
4993 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004994 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4995 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004996 RHSPI != RHSPE; RHSPI++) {
4997 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004998 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004999 break;
5000 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005001 }
5002 // FIXME: For better diagnostics, consider passing back the protocol name.
5003 if (!RHSImplementsProtocol)
5004 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005005 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005006 // The RHS implements all protocols listed on the LHS.
5007 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005008}
5009
Steve Naroffb7605152009-02-12 17:52:19 +00005010bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5011 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005012 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5013 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005014
Steve Naroff7cae42b2009-07-10 23:34:53 +00005015 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005016 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005017
5018 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5019 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005020}
5021
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005022bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5023 return canAssignObjCInterfaces(
5024 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5025 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5026}
5027
Mike Stump11289f42009-09-09 15:08:12 +00005028/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005029/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005030/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005031/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005032bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5033 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005034 if (getLangOptions().CPlusPlus)
5035 return hasSameType(LHS, RHS);
5036
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005037 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005038}
5039
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005040bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5041 return !mergeTypes(LHS, RHS, true).isNull();
5042}
5043
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005044/// mergeTransparentUnionType - if T is a transparent union type and a member
5045/// of T is compatible with SubType, return the merged type, else return
5046/// QualType()
5047QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5048 bool OfBlockPointer,
5049 bool Unqualified) {
5050 if (const RecordType *UT = T->getAsUnionType()) {
5051 RecordDecl *UD = UT->getDecl();
5052 if (UD->hasAttr<TransparentUnionAttr>()) {
5053 for (RecordDecl::field_iterator it = UD->field_begin(),
5054 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005055 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005056 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5057 if (!MT.isNull())
5058 return MT;
5059 }
5060 }
5061 }
5062
5063 return QualType();
5064}
5065
5066/// mergeFunctionArgumentTypes - merge two types which appear as function
5067/// argument types
5068QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5069 bool OfBlockPointer,
5070 bool Unqualified) {
5071 // GNU extension: two types are compatible if they appear as a function
5072 // argument, one of the types is a transparent union type and the other
5073 // type is compatible with a union member
5074 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5075 Unqualified);
5076 if (!lmerge.isNull())
5077 return lmerge;
5078
5079 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5080 Unqualified);
5081 if (!rmerge.isNull())
5082 return rmerge;
5083
5084 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5085}
5086
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005087QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005088 bool OfBlockPointer,
5089 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005090 const FunctionType *lbase = lhs->getAs<FunctionType>();
5091 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005092 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5093 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005094 bool allLTypes = true;
5095 bool allRTypes = true;
5096
5097 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005098 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005099 if (OfBlockPointer) {
5100 QualType RHS = rbase->getResultType();
5101 QualType LHS = lbase->getResultType();
5102 bool UnqualifiedResult = Unqualified;
5103 if (!UnqualifiedResult)
5104 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005105 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005106 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005107 else
John McCall8c6b56f2010-12-15 01:06:38 +00005108 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5109 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005110 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005111
5112 if (Unqualified)
5113 retType = retType.getUnqualifiedType();
5114
5115 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5116 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5117 if (Unqualified) {
5118 LRetType = LRetType.getUnqualifiedType();
5119 RRetType = RRetType.getUnqualifiedType();
5120 }
5121
5122 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005123 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005124 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005125 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005126
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005127 // FIXME: double check this
5128 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5129 // rbase->getRegParmAttr() != 0 &&
5130 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005131 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5132 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005133
Douglas Gregor8c940862010-01-18 17:14:39 +00005134 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005135 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005136 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005137
John McCall8c6b56f2010-12-15 01:06:38 +00005138 // Regparm is part of the calling convention.
5139 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5140 return QualType();
5141
5142 // It's noreturn if either type is.
5143 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5144 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5145 if (NoReturn != lbaseInfo.getNoReturn())
5146 allLTypes = false;
5147 if (NoReturn != rbaseInfo.getNoReturn())
5148 allRTypes = false;
5149
5150 FunctionType::ExtInfo einfo(NoReturn,
5151 lbaseInfo.getRegParm(),
5152 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00005153
Eli Friedman47f77112008-08-22 00:56:42 +00005154 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005155 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5156 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005157 unsigned lproto_nargs = lproto->getNumArgs();
5158 unsigned rproto_nargs = rproto->getNumArgs();
5159
5160 // Compatible functions must have the same number of arguments
5161 if (lproto_nargs != rproto_nargs)
5162 return QualType();
5163
5164 // Variadic and non-variadic functions aren't compatible
5165 if (lproto->isVariadic() != rproto->isVariadic())
5166 return QualType();
5167
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005168 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5169 return QualType();
5170
Eli Friedman47f77112008-08-22 00:56:42 +00005171 // Check argument compatibility
5172 llvm::SmallVector<QualType, 10> types;
5173 for (unsigned i = 0; i < lproto_nargs; i++) {
5174 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5175 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005176 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5177 OfBlockPointer,
5178 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005179 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005180
5181 if (Unqualified)
5182 argtype = argtype.getUnqualifiedType();
5183
Eli Friedman47f77112008-08-22 00:56:42 +00005184 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005185 if (Unqualified) {
5186 largtype = largtype.getUnqualifiedType();
5187 rargtype = rargtype.getUnqualifiedType();
5188 }
5189
Chris Lattner465fa322008-10-05 17:34:18 +00005190 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5191 allLTypes = false;
5192 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5193 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005194 }
5195 if (allLTypes) return lhs;
5196 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005197
5198 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5199 EPI.ExtInfo = einfo;
5200 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005201 }
5202
5203 if (lproto) allRTypes = false;
5204 if (rproto) allLTypes = false;
5205
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005206 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005207 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005208 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005209 if (proto->isVariadic()) return QualType();
5210 // Check that the types are compatible with the types that
5211 // would result from default argument promotions (C99 6.7.5.3p15).
5212 // The only types actually affected are promotable integer
5213 // types and floats, which would be passed as a different
5214 // type depending on whether the prototype is visible.
5215 unsigned proto_nargs = proto->getNumArgs();
5216 for (unsigned i = 0; i < proto_nargs; ++i) {
5217 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005218
5219 // Look at the promotion type of enum types, since that is the type used
5220 // to pass enum values.
5221 if (const EnumType *Enum = argTy->getAs<EnumType>())
5222 argTy = Enum->getDecl()->getPromotionType();
5223
Eli Friedman47f77112008-08-22 00:56:42 +00005224 if (argTy->isPromotableIntegerType() ||
5225 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5226 return QualType();
5227 }
5228
5229 if (allLTypes) return lhs;
5230 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005231
5232 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5233 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005234 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005235 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005236 }
5237
5238 if (allLTypes) return lhs;
5239 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005240 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005241}
5242
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005243QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005244 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005245 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005246 // C++ [expr]: If an expression initially has the type "reference to T", the
5247 // type is adjusted to "T" prior to any further analysis, the expression
5248 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005249 // expression is an lvalue unless the reference is an rvalue reference and
5250 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005251 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5252 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005253
5254 if (Unqualified) {
5255 LHS = LHS.getUnqualifiedType();
5256 RHS = RHS.getUnqualifiedType();
5257 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005258
Eli Friedman47f77112008-08-22 00:56:42 +00005259 QualType LHSCan = getCanonicalType(LHS),
5260 RHSCan = getCanonicalType(RHS);
5261
5262 // If two types are identical, they are compatible.
5263 if (LHSCan == RHSCan)
5264 return LHS;
5265
John McCall8ccfcb52009-09-24 19:53:00 +00005266 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005267 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5268 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005269 if (LQuals != RQuals) {
5270 // If any of these qualifiers are different, we have a type
5271 // mismatch.
5272 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5273 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5274 return QualType();
5275
5276 // Exactly one GC qualifier difference is allowed: __strong is
5277 // okay if the other type has no GC qualifier but is an Objective
5278 // C object pointer (i.e. implicitly strong by default). We fix
5279 // this by pretending that the unqualified type was actually
5280 // qualified __strong.
5281 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5282 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5283 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5284
5285 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5286 return QualType();
5287
5288 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5289 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5290 }
5291 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5292 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5293 }
Eli Friedman47f77112008-08-22 00:56:42 +00005294 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005295 }
5296
5297 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005298
Eli Friedmandcca6332009-06-01 01:22:52 +00005299 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5300 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005301
Chris Lattnerfd652912008-01-14 05:45:46 +00005302 // We want to consider the two function types to be the same for these
5303 // comparisons, just force one to the other.
5304 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5305 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005306
5307 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005308 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5309 LHSClass = Type::ConstantArray;
5310 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5311 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005312
John McCall8b07ec22010-05-15 11:32:37 +00005313 // ObjCInterfaces are just specialized ObjCObjects.
5314 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5315 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5316
Nate Begemance4d7fc2008-04-18 23:10:10 +00005317 // Canonicalize ExtVector -> Vector.
5318 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5319 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005320
Chris Lattner95554662008-04-07 05:43:21 +00005321 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005322 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005323 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005324 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005325 // Compatibility is based on the underlying type, not the promotion
5326 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005327 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005328 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5329 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005330 }
John McCall9dd450b2009-09-21 23:43:11 +00005331 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005332 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5333 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005334 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005335
Eli Friedman47f77112008-08-22 00:56:42 +00005336 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005337 }
Eli Friedman47f77112008-08-22 00:56:42 +00005338
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005339 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005340 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005341#define TYPE(Class, Base)
5342#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005343#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005344#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5345#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5346#include "clang/AST/TypeNodes.def"
5347 assert(false && "Non-canonical and dependent types shouldn't get here");
5348 return QualType();
5349
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005350 case Type::LValueReference:
5351 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005352 case Type::MemberPointer:
5353 assert(false && "C++ should never be in mergeTypes");
5354 return QualType();
5355
John McCall8b07ec22010-05-15 11:32:37 +00005356 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005357 case Type::IncompleteArray:
5358 case Type::VariableArray:
5359 case Type::FunctionProto:
5360 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005361 assert(false && "Types are eliminated above");
5362 return QualType();
5363
Chris Lattnerfd652912008-01-14 05:45:46 +00005364 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005365 {
5366 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005367 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5368 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005369 if (Unqualified) {
5370 LHSPointee = LHSPointee.getUnqualifiedType();
5371 RHSPointee = RHSPointee.getUnqualifiedType();
5372 }
5373 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5374 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005375 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005376 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005377 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005378 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005379 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005380 return getPointerType(ResultType);
5381 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005382 case Type::BlockPointer:
5383 {
5384 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005385 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5386 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005387 if (Unqualified) {
5388 LHSPointee = LHSPointee.getUnqualifiedType();
5389 RHSPointee = RHSPointee.getUnqualifiedType();
5390 }
5391 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5392 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005393 if (ResultType.isNull()) return QualType();
5394 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5395 return LHS;
5396 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5397 return RHS;
5398 return getBlockPointerType(ResultType);
5399 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005400 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005401 {
5402 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5403 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5404 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5405 return QualType();
5406
5407 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5408 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005409 if (Unqualified) {
5410 LHSElem = LHSElem.getUnqualifiedType();
5411 RHSElem = RHSElem.getUnqualifiedType();
5412 }
5413
5414 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005415 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005416 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5417 return LHS;
5418 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5419 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005420 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5421 ArrayType::ArraySizeModifier(), 0);
5422 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5423 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005424 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5425 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005426 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5427 return LHS;
5428 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5429 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005430 if (LVAT) {
5431 // FIXME: This isn't correct! But tricky to implement because
5432 // the array's size has to be the size of LHS, but the type
5433 // has to be different.
5434 return LHS;
5435 }
5436 if (RVAT) {
5437 // FIXME: This isn't correct! But tricky to implement because
5438 // the array's size has to be the size of RHS, but the type
5439 // has to be different.
5440 return RHS;
5441 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005442 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5443 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005444 return getIncompleteArrayType(ResultType,
5445 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005446 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005447 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005448 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005449 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005450 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005451 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005452 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005453 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005454 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005455 case Type::Complex:
5456 // Distinct complex types are incompatible.
5457 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005458 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005459 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005460 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5461 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005462 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005463 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005464 case Type::ObjCObject: {
5465 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005466 // FIXME: This should be type compatibility, e.g. whether
5467 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005468 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5469 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5470 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005471 return LHS;
5472
Eli Friedman47f77112008-08-22 00:56:42 +00005473 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005474 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005475 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005476 if (OfBlockPointer) {
5477 if (canAssignObjCInterfacesInBlockPointer(
5478 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005479 RHS->getAs<ObjCObjectPointerType>(),
5480 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005481 return LHS;
5482 return QualType();
5483 }
John McCall9dd450b2009-09-21 23:43:11 +00005484 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5485 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005486 return LHS;
5487
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005488 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005489 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005490 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005491
5492 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005493}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005494
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005495/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5496/// 'RHS' attributes and returns the merged version; including for function
5497/// return types.
5498QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5499 QualType LHSCan = getCanonicalType(LHS),
5500 RHSCan = getCanonicalType(RHS);
5501 // If two types are identical, they are compatible.
5502 if (LHSCan == RHSCan)
5503 return LHS;
5504 if (RHSCan->isFunctionType()) {
5505 if (!LHSCan->isFunctionType())
5506 return QualType();
5507 QualType OldReturnType =
5508 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5509 QualType NewReturnType =
5510 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5511 QualType ResReturnType =
5512 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5513 if (ResReturnType.isNull())
5514 return QualType();
5515 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5516 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5517 // In either case, use OldReturnType to build the new function type.
5518 const FunctionType *F = LHS->getAs<FunctionType>();
5519 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005520 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5521 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005522 QualType ResultType
5523 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005524 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005525 return ResultType;
5526 }
5527 }
5528 return QualType();
5529 }
5530
5531 // If the qualifiers are different, the types can still be merged.
5532 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5533 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5534 if (LQuals != RQuals) {
5535 // If any of these qualifiers are different, we have a type mismatch.
5536 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5537 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5538 return QualType();
5539
5540 // Exactly one GC qualifier difference is allowed: __strong is
5541 // okay if the other type has no GC qualifier but is an Objective
5542 // C object pointer (i.e. implicitly strong by default). We fix
5543 // this by pretending that the unqualified type was actually
5544 // qualified __strong.
5545 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5546 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5547 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5548
5549 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5550 return QualType();
5551
5552 if (GC_L == Qualifiers::Strong)
5553 return LHS;
5554 if (GC_R == Qualifiers::Strong)
5555 return RHS;
5556 return QualType();
5557 }
5558
5559 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5560 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5561 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5562 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5563 if (ResQT == LHSBaseQT)
5564 return LHS;
5565 if (ResQT == RHSBaseQT)
5566 return RHS;
5567 }
5568 return QualType();
5569}
5570
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005571//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005572// Integer Predicates
5573//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005574
Jay Foad39c79802011-01-12 09:06:06 +00005575unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005576 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005577 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005578 if (T->isBooleanType())
5579 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005580 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005581 return (unsigned)getTypeSize(T);
5582}
5583
5584QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005585 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005586
5587 // Turn <4 x signed int> -> <4 x unsigned int>
5588 if (const VectorType *VTy = T->getAs<VectorType>())
5589 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005590 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005591
5592 // For enums, we return the unsigned version of the base type.
5593 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005594 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005595
5596 const BuiltinType *BTy = T->getAs<BuiltinType>();
5597 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005598 switch (BTy->getKind()) {
5599 case BuiltinType::Char_S:
5600 case BuiltinType::SChar:
5601 return UnsignedCharTy;
5602 case BuiltinType::Short:
5603 return UnsignedShortTy;
5604 case BuiltinType::Int:
5605 return UnsignedIntTy;
5606 case BuiltinType::Long:
5607 return UnsignedLongTy;
5608 case BuiltinType::LongLong:
5609 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005610 case BuiltinType::Int128:
5611 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005612 default:
5613 assert(0 && "Unexpected signed integer type");
5614 return QualType();
5615 }
5616}
5617
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005618ASTMutationListener::~ASTMutationListener() { }
5619
Chris Lattnerecd79c62009-06-14 00:45:47 +00005620
5621//===----------------------------------------------------------------------===//
5622// Builtin Type Computation
5623//===----------------------------------------------------------------------===//
5624
5625/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005626/// pointer over the consumed characters. This returns the resultant type. If
5627/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5628/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5629/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005630///
5631/// RequiresICE is filled in on return to indicate whether the value is required
5632/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005633static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005634 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005635 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005636 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005637 // Modifiers.
5638 int HowLong = 0;
5639 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005640 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005641
Chris Lattnerdc226c22010-10-01 22:42:38 +00005642 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005643 bool Done = false;
5644 while (!Done) {
5645 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005646 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005647 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005648 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005649 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005650 case 'S':
5651 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5652 assert(!Signed && "Can't use 'S' modifier multiple times!");
5653 Signed = true;
5654 break;
5655 case 'U':
5656 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5657 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5658 Unsigned = true;
5659 break;
5660 case 'L':
5661 assert(HowLong <= 2 && "Can't have LLLL modifier");
5662 ++HowLong;
5663 break;
5664 }
5665 }
5666
5667 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005668
Chris Lattnerecd79c62009-06-14 00:45:47 +00005669 // Read the base type.
5670 switch (*Str++) {
5671 default: assert(0 && "Unknown builtin type letter!");
5672 case 'v':
5673 assert(HowLong == 0 && !Signed && !Unsigned &&
5674 "Bad modifiers used with 'v'!");
5675 Type = Context.VoidTy;
5676 break;
5677 case 'f':
5678 assert(HowLong == 0 && !Signed && !Unsigned &&
5679 "Bad modifiers used with 'f'!");
5680 Type = Context.FloatTy;
5681 break;
5682 case 'd':
5683 assert(HowLong < 2 && !Signed && !Unsigned &&
5684 "Bad modifiers used with 'd'!");
5685 if (HowLong)
5686 Type = Context.LongDoubleTy;
5687 else
5688 Type = Context.DoubleTy;
5689 break;
5690 case 's':
5691 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5692 if (Unsigned)
5693 Type = Context.UnsignedShortTy;
5694 else
5695 Type = Context.ShortTy;
5696 break;
5697 case 'i':
5698 if (HowLong == 3)
5699 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5700 else if (HowLong == 2)
5701 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5702 else if (HowLong == 1)
5703 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5704 else
5705 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5706 break;
5707 case 'c':
5708 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5709 if (Signed)
5710 Type = Context.SignedCharTy;
5711 else if (Unsigned)
5712 Type = Context.UnsignedCharTy;
5713 else
5714 Type = Context.CharTy;
5715 break;
5716 case 'b': // boolean
5717 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5718 Type = Context.BoolTy;
5719 break;
5720 case 'z': // size_t.
5721 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5722 Type = Context.getSizeType();
5723 break;
5724 case 'F':
5725 Type = Context.getCFConstantStringType();
5726 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005727 case 'G':
5728 Type = Context.getObjCIdType();
5729 break;
5730 case 'H':
5731 Type = Context.getObjCSelType();
5732 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005733 case 'a':
5734 Type = Context.getBuiltinVaListType();
5735 assert(!Type.isNull() && "builtin va list type not initialized!");
5736 break;
5737 case 'A':
5738 // This is a "reference" to a va_list; however, what exactly
5739 // this means depends on how va_list is defined. There are two
5740 // different kinds of va_list: ones passed by value, and ones
5741 // passed by reference. An example of a by-value va_list is
5742 // x86, where va_list is a char*. An example of by-ref va_list
5743 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5744 // we want this argument to be a char*&; for x86-64, we want
5745 // it to be a __va_list_tag*.
5746 Type = Context.getBuiltinVaListType();
5747 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005748 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005749 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005750 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005751 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005752 break;
5753 case 'V': {
5754 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005755 unsigned NumElements = strtoul(Str, &End, 10);
5756 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005757 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005758
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005759 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5760 RequiresICE, false);
5761 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005762
5763 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005764 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005765 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005766 break;
5767 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005768 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005769 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5770 false);
5771 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005772 Type = Context.getComplexType(ElementType);
5773 break;
5774 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005775 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005776 Type = Context.getFILEType();
5777 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005778 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005779 return QualType();
5780 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005781 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005782 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005783 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005784 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005785 else
5786 Type = Context.getjmp_bufType();
5787
Mike Stump2adb4da2009-07-28 23:47:15 +00005788 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005789 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005790 return QualType();
5791 }
5792 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005793 }
Mike Stump11289f42009-09-09 15:08:12 +00005794
Chris Lattnerdc226c22010-10-01 22:42:38 +00005795 // If there are modifiers and if we're allowed to parse them, go for it.
5796 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005797 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005798 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005799 default: Done = true; --Str; break;
5800 case '*':
5801 case '&': {
5802 // Both pointers and references can have their pointee types
5803 // qualified with an address space.
5804 char *End;
5805 unsigned AddrSpace = strtoul(Str, &End, 10);
5806 if (End != Str && AddrSpace != 0) {
5807 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5808 Str = End;
5809 }
5810 if (c == '*')
5811 Type = Context.getPointerType(Type);
5812 else
5813 Type = Context.getLValueReferenceType(Type);
5814 break;
5815 }
5816 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5817 case 'C':
5818 Type = Type.withConst();
5819 break;
5820 case 'D':
5821 Type = Context.getVolatileType(Type);
5822 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005823 }
5824 }
Chris Lattner84733392010-10-01 07:13:18 +00005825
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005826 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005827 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005828
Chris Lattnerecd79c62009-06-14 00:45:47 +00005829 return Type;
5830}
5831
5832/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005833QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005834 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005835 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005836 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005837
Chris Lattnerecd79c62009-06-14 00:45:47 +00005838 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005839
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005840 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005841 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005842 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5843 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005844 if (Error != GE_None)
5845 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005846
5847 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5848
Chris Lattnerecd79c62009-06-14 00:45:47 +00005849 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005850 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005851 if (Error != GE_None)
5852 return QualType();
5853
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005854 // If this argument is required to be an IntegerConstantExpression and the
5855 // caller cares, fill in the bitmask we return.
5856 if (RequiresICE && IntegerConstantArgs)
5857 *IntegerConstantArgs |= 1 << ArgTypes.size();
5858
Chris Lattnerecd79c62009-06-14 00:45:47 +00005859 // Do array -> pointer decay. The builtin should use the decayed type.
5860 if (Ty->isArrayType())
5861 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005862
Chris Lattnerecd79c62009-06-14 00:45:47 +00005863 ArgTypes.push_back(Ty);
5864 }
5865
5866 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5867 "'.' should only occur at end of builtin type list!");
5868
John McCall991eb4b2010-12-21 00:44:39 +00005869 FunctionType::ExtInfo EI;
5870 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5871
5872 bool Variadic = (TypeStr[0] == '.');
5873
5874 // We really shouldn't be making a no-proto type here, especially in C++.
5875 if (ArgTypes.empty() && Variadic)
5876 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005877
John McCalldb40c7f2010-12-14 08:05:40 +00005878 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005879 EPI.ExtInfo = EI;
5880 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00005881
5882 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005883}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005884
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005885GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5886 GVALinkage External = GVA_StrongExternal;
5887
5888 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005889 switch (L) {
5890 case NoLinkage:
5891 case InternalLinkage:
5892 case UniqueExternalLinkage:
5893 return GVA_Internal;
5894
5895 case ExternalLinkage:
5896 switch (FD->getTemplateSpecializationKind()) {
5897 case TSK_Undeclared:
5898 case TSK_ExplicitSpecialization:
5899 External = GVA_StrongExternal;
5900 break;
5901
5902 case TSK_ExplicitInstantiationDefinition:
5903 return GVA_ExplicitTemplateInstantiation;
5904
5905 case TSK_ExplicitInstantiationDeclaration:
5906 case TSK_ImplicitInstantiation:
5907 External = GVA_TemplateInstantiation;
5908 break;
5909 }
5910 }
5911
5912 if (!FD->isInlined())
5913 return External;
5914
5915 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5916 // GNU or C99 inline semantics. Determine whether this symbol should be
5917 // externally visible.
5918 if (FD->isInlineDefinitionExternallyVisible())
5919 return External;
5920
5921 // C99 inline semantics, where the symbol is not externally visible.
5922 return GVA_C99Inline;
5923 }
5924
5925 // C++0x [temp.explicit]p9:
5926 // [ Note: The intent is that an inline function that is the subject of
5927 // an explicit instantiation declaration will still be implicitly
5928 // instantiated when used so that the body can be considered for
5929 // inlining, but that no out-of-line copy of the inline function would be
5930 // generated in the translation unit. -- end note ]
5931 if (FD->getTemplateSpecializationKind()
5932 == TSK_ExplicitInstantiationDeclaration)
5933 return GVA_C99Inline;
5934
5935 return GVA_CXXInline;
5936}
5937
5938GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5939 // If this is a static data member, compute the kind of template
5940 // specialization. Otherwise, this variable is not part of a
5941 // template.
5942 TemplateSpecializationKind TSK = TSK_Undeclared;
5943 if (VD->isStaticDataMember())
5944 TSK = VD->getTemplateSpecializationKind();
5945
5946 Linkage L = VD->getLinkage();
5947 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5948 VD->getType()->getLinkage() == UniqueExternalLinkage)
5949 L = UniqueExternalLinkage;
5950
5951 switch (L) {
5952 case NoLinkage:
5953 case InternalLinkage:
5954 case UniqueExternalLinkage:
5955 return GVA_Internal;
5956
5957 case ExternalLinkage:
5958 switch (TSK) {
5959 case TSK_Undeclared:
5960 case TSK_ExplicitSpecialization:
5961 return GVA_StrongExternal;
5962
5963 case TSK_ExplicitInstantiationDeclaration:
5964 llvm_unreachable("Variable should not be instantiated");
5965 // Fall through to treat this like any other instantiation.
5966
5967 case TSK_ExplicitInstantiationDefinition:
5968 return GVA_ExplicitTemplateInstantiation;
5969
5970 case TSK_ImplicitInstantiation:
5971 return GVA_TemplateInstantiation;
5972 }
5973 }
5974
5975 return GVA_StrongExternal;
5976}
5977
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005978bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005979 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5980 if (!VD->isFileVarDecl())
5981 return false;
5982 } else if (!isa<FunctionDecl>(D))
5983 return false;
5984
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005985 // Weak references don't produce any output by themselves.
5986 if (D->hasAttr<WeakRefAttr>())
5987 return false;
5988
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005989 // Aliases and used decls are required.
5990 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5991 return true;
5992
5993 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5994 // Forward declarations aren't required.
5995 if (!FD->isThisDeclarationADefinition())
5996 return false;
5997
5998 // Constructors and destructors are required.
5999 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6000 return true;
6001
6002 // The key function for a class is required.
6003 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6004 const CXXRecordDecl *RD = MD->getParent();
6005 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6006 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6007 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6008 return true;
6009 }
6010 }
6011
6012 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6013
6014 // static, static inline, always_inline, and extern inline functions can
6015 // always be deferred. Normal inline functions can be deferred in C99/C++.
6016 // Implicit template instantiations can also be deferred in C++.
6017 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6018 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6019 return false;
6020 return true;
6021 }
6022
6023 const VarDecl *VD = cast<VarDecl>(D);
6024 assert(VD->isFileVarDecl() && "Expected file scoped var");
6025
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006026 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6027 return false;
6028
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006029 // Structs that have non-trivial constructors or destructors are required.
6030
6031 // FIXME: Handle references.
6032 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6033 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006034 if (RD->hasDefinition() &&
6035 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006036 return true;
6037 }
6038 }
6039
6040 GVALinkage L = GetGVALinkageForVariable(VD);
6041 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6042 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6043 return false;
6044 }
6045
6046 return true;
6047}
Charles Davis53c59df2010-08-16 03:33:14 +00006048
Charles Davis99202b32010-11-09 18:04:24 +00006049CallingConv ASTContext::getDefaultMethodCallConv() {
6050 // Pass through to the C++ ABI object
6051 return ABI->getDefaultMethodCallConv();
6052}
6053
Jay Foad39c79802011-01-12 09:06:06 +00006054bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006055 // Pass through to the C++ ABI object
6056 return ABI->isNearlyEmpty(RD);
6057}
6058
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006059MangleContext *ASTContext::createMangleContext() {
6060 switch (Target.getCXXABI()) {
6061 case CXXABI_ARM:
6062 case CXXABI_Itanium:
6063 return createItaniumMangleContext(*this, getDiagnostics());
6064 case CXXABI_Microsoft:
6065 return createMicrosoftMangleContext(*this, getDiagnostics());
6066 }
6067 assert(0 && "Unsupported ABI");
6068 return 0;
6069}
6070
Charles Davis53c59df2010-08-16 03:33:14 +00006071CXXABI::~CXXABI() {}