blob: 379c13a9342cc6978a9534a303b1de0cc87e931b [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
Eli Friedman786d0872011-04-30 19:24:24 +0000378 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000379 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
John McCall0009fcc2011-04-26 20:42:42 +0000405 // Placeholder type for bound members.
406 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
407
John McCall31996342011-04-07 08:22:57 +0000408 // "any" type; useful for debugger-like clients.
409 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
410
Chris Lattner970e54e2006-11-12 00:37:36 +0000411 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000412 FloatComplexTy = getComplexType(FloatTy);
413 DoubleComplexTy = getComplexType(DoubleTy);
414 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000415
Steve Naroff66e9f332007-10-15 14:41:52 +0000416 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000417
Steve Naroff1329fa02009-07-15 18:40:39 +0000418 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
419 ObjCIdTypedefType = QualType();
420 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000421 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000422
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000423 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000424 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
425 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000426 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000427
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000428 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000429
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000430 // void * type
431 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000432
433 // nullptr type (C++0x 2.14.7)
434 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000435}
436
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000437Diagnostic &ASTContext::getDiagnostics() const {
438 return SourceMgr.getDiagnostics();
439}
440
Douglas Gregor561eceb2010-08-30 16:49:28 +0000441AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
442 AttrVec *&Result = DeclAttrs[D];
443 if (!Result) {
444 void *Mem = Allocate(sizeof(AttrVec));
445 Result = new (Mem) AttrVec;
446 }
447
448 return *Result;
449}
450
451/// \brief Erase the attributes corresponding to the given declaration.
452void ASTContext::eraseDeclAttrs(const Decl *D) {
453 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
454 if (Pos != DeclAttrs.end()) {
455 Pos->second->~AttrVec();
456 DeclAttrs.erase(Pos);
457 }
458}
459
Douglas Gregor86d142a2009-10-08 07:24:58 +0000460MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000461ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000462 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000463 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000464 = InstantiatedFromStaticDataMember.find(Var);
465 if (Pos == InstantiatedFromStaticDataMember.end())
466 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000467
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000468 return Pos->second;
469}
470
Mike Stump11289f42009-09-09 15:08:12 +0000471void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000472ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000473 TemplateSpecializationKind TSK,
474 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000475 assert(Inst->isStaticDataMember() && "Not a static data member");
476 assert(Tmpl->isStaticDataMember() && "Not a static data member");
477 assert(!InstantiatedFromStaticDataMember[Inst] &&
478 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000479 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000480 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000481}
482
John McCalle61f2ba2009-11-18 02:36:19 +0000483NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000484ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000485 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000486 = InstantiatedFromUsingDecl.find(UUD);
487 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000488 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000489
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000490 return Pos->second;
491}
492
493void
John McCallb96ec562009-12-04 22:46:56 +0000494ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
495 assert((isa<UsingDecl>(Pattern) ||
496 isa<UnresolvedUsingValueDecl>(Pattern) ||
497 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
498 "pattern decl is not a using decl");
499 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
500 InstantiatedFromUsingDecl[Inst] = Pattern;
501}
502
503UsingShadowDecl *
504ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
505 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
506 = InstantiatedFromUsingShadowDecl.find(Inst);
507 if (Pos == InstantiatedFromUsingShadowDecl.end())
508 return 0;
509
510 return Pos->second;
511}
512
513void
514ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
515 UsingShadowDecl *Pattern) {
516 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
517 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000518}
519
Anders Carlsson5da84842009-09-01 04:26:58 +0000520FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
521 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
522 = InstantiatedFromUnnamedFieldDecl.find(Field);
523 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
524 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000525
Anders Carlsson5da84842009-09-01 04:26:58 +0000526 return Pos->second;
527}
528
529void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
530 FieldDecl *Tmpl) {
531 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
532 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
533 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
534 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000535
Anders Carlsson5da84842009-09-01 04:26:58 +0000536 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
537}
538
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000539bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
540 const FieldDecl *LastFD) const {
541 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
542 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0);
543
544}
545
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000546bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
547 const FieldDecl *LastFD) const {
548 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Fariborz Jahanian759e4a12011-05-03 22:07:14 +0000549 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0 &&
550 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000551
552}
553
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000554bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
555 const FieldDecl *LastFD) const {
556 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
557 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() &&
558 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
559}
560
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000561bool ASTContext::NoneBitfieldFollowsBitfield(const FieldDecl *FD,
562 const FieldDecl *LastFD) const {
563 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
564 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
565}
566
567bool ASTContext::BitfieldFollowsNoneBitfield(const FieldDecl *FD,
568 const FieldDecl *LastFD) const {
569 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
570 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
571}
572
Douglas Gregor832940b2010-03-02 23:58:15 +0000573ASTContext::overridden_cxx_method_iterator
574ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
575 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
576 = OverriddenMethods.find(Method);
577 if (Pos == OverriddenMethods.end())
578 return 0;
579
580 return Pos->second.begin();
581}
582
583ASTContext::overridden_cxx_method_iterator
584ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
585 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
586 = OverriddenMethods.find(Method);
587 if (Pos == OverriddenMethods.end())
588 return 0;
589
590 return Pos->second.end();
591}
592
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000593unsigned
594ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
595 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
596 = OverriddenMethods.find(Method);
597 if (Pos == OverriddenMethods.end())
598 return 0;
599
600 return Pos->second.size();
601}
602
Douglas Gregor832940b2010-03-02 23:58:15 +0000603void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
604 const CXXMethodDecl *Overridden) {
605 OverriddenMethods[Method].push_back(Overridden);
606}
607
Chris Lattner53cfe802007-07-18 17:52:12 +0000608//===----------------------------------------------------------------------===//
609// Type Sizing and Analysis
610//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000611
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000612/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
613/// scalar floating point type.
614const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000615 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000616 assert(BT && "Not a floating point type!");
617 switch (BT->getKind()) {
618 default: assert(0 && "Not a floating point type!");
619 case BuiltinType::Float: return Target.getFloatFormat();
620 case BuiltinType::Double: return Target.getDoubleFormat();
621 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
622 }
623}
624
Ken Dyck160146e2010-01-27 17:10:57 +0000625/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000626/// specified decl. Note that bitfields do not have a valid alignment, so
627/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000628/// If @p RefAsPointee, references are treated like their underlying type
629/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000630CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000631 unsigned Align = Target.getCharWidth();
632
John McCall94268702010-10-08 18:24:19 +0000633 bool UseAlignAttrOnly = false;
634 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
635 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000636
John McCall94268702010-10-08 18:24:19 +0000637 // __attribute__((aligned)) can increase or decrease alignment
638 // *except* on a struct or struct member, where it only increases
639 // alignment unless 'packed' is also specified.
640 //
641 // It is an error for [[align]] to decrease alignment, so we can
642 // ignore that possibility; Sema should diagnose it.
643 if (isa<FieldDecl>(D)) {
644 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
645 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
646 } else {
647 UseAlignAttrOnly = true;
648 }
649 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000650 else if (isa<FieldDecl>(D))
651 UseAlignAttrOnly =
652 D->hasAttr<PackedAttr>() ||
653 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000654
John McCall4e819612011-01-20 07:57:12 +0000655 // If we're using the align attribute only, just ignore everything
656 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000657 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000658 // do nothing
659
John McCall94268702010-10-08 18:24:19 +0000660 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000661 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000662 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000663 if (RefAsPointee)
664 T = RT->getPointeeType();
665 else
666 T = getPointerType(RT->getPointeeType());
667 }
668 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000669 // Adjust alignments of declarations with array type by the
670 // large-array alignment on the target.
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000671 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000672 const ArrayType *arrayType;
673 if (MinWidth && (arrayType = getAsArrayType(T))) {
674 if (isa<VariableArrayType>(arrayType))
675 Align = std::max(Align, Target.getLargeArrayAlign());
676 else if (isa<ConstantArrayType>(arrayType) &&
677 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
678 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000679
John McCall33ddac02011-01-19 10:06:00 +0000680 // Walk through any array types while we're at it.
681 T = getBaseElementType(arrayType);
682 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000683 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
684 }
John McCall4e819612011-01-20 07:57:12 +0000685
686 // Fields can be subject to extra alignment constraints, like if
687 // the field is packed, the struct is packed, or the struct has a
688 // a max-field-alignment constraint (#pragma pack). So calculate
689 // the actual alignment of the field within the struct, and then
690 // (as we're expected to) constrain that by the alignment of the type.
691 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
692 // So calculate the alignment of the field.
693 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
694
695 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000696 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000697
698 // Use the GCD of that and the offset within the record.
699 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
700 if (offset > 0) {
701 // Alignment is always a power of 2, so the GCD will be a power of 2,
702 // which means we get to do this crazy thing instead of Euclid's.
703 uint64_t lowBitOfOffset = offset & (~offset + 1);
704 if (lowBitOfOffset < fieldAlign)
705 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
706 }
707
708 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000709 }
Chris Lattner68061312009-01-24 21:53:27 +0000710 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000711
Ken Dyckcc56c542011-01-15 18:38:59 +0000712 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000713}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000714
John McCall87fe5d52010-05-20 01:18:31 +0000715std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000716ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000717 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000718 return std::make_pair(toCharUnitsFromBits(Info.first),
719 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000720}
721
722std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000723ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000724 return getTypeInfoInChars(T.getTypePtr());
725}
726
Chris Lattner983a8bb2007-07-13 22:13:22 +0000727/// getTypeSize - Return the size of the specified type, in bits. This method
728/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000729///
730/// FIXME: Pointers into different addr spaces could have different sizes and
731/// alignment requirements: getPointerInfo should take an AddrSpace, this
732/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000733std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000734ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000735 uint64_t Width=0;
736 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000737 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000738#define TYPE(Class, Base)
739#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000740#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000741#define DEPENDENT_TYPE(Class, Base) case Type::Class:
742#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000743 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000744 break;
745
Chris Lattner355332d2007-07-13 22:27:08 +0000746 case Type::FunctionNoProto:
747 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000748 // GCC extension: alignof(function) = 32 bits
749 Width = 0;
750 Align = 32;
751 break;
752
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000753 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000754 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000755 Width = 0;
756 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
757 break;
758
Steve Naroff5c131802007-08-30 01:06:46 +0000759 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000760 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000761
Chris Lattner37e05872008-03-05 18:54:05 +0000762 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000763 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000764 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000765 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000766 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000767 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000768 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000769 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000770 const VectorType *VT = cast<VectorType>(T);
771 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
772 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000773 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000774 // If the alignment is not a power of 2, round up to the next power of 2.
775 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000776 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000777 Align = llvm::NextPowerOf2(Align);
778 Width = llvm::RoundUpToAlignment(Width, Align);
779 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000780 break;
781 }
Chris Lattner647fb222007-07-18 18:26:58 +0000782
Chris Lattner7570e9c2008-03-08 08:52:55 +0000783 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000784 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000785 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000786 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000787 // GCC extension: alignof(void) = 8 bits.
788 Width = 0;
789 Align = 8;
790 break;
791
Chris Lattner6a4f7452007-12-19 19:23:28 +0000792 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000793 Width = Target.getBoolWidth();
794 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000795 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000796 case BuiltinType::Char_S:
797 case BuiltinType::Char_U:
798 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000799 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000800 Width = Target.getCharWidth();
801 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000802 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000803 case BuiltinType::WChar_S:
804 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000805 Width = Target.getWCharWidth();
806 Align = Target.getWCharAlign();
807 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000808 case BuiltinType::Char16:
809 Width = Target.getChar16Width();
810 Align = Target.getChar16Align();
811 break;
812 case BuiltinType::Char32:
813 Width = Target.getChar32Width();
814 Align = Target.getChar32Align();
815 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000816 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000817 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000818 Width = Target.getShortWidth();
819 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000820 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000821 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000822 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000823 Width = Target.getIntWidth();
824 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000825 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000826 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000827 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000828 Width = Target.getLongWidth();
829 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000830 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000831 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000832 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000833 Width = Target.getLongLongWidth();
834 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000835 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000836 case BuiltinType::Int128:
837 case BuiltinType::UInt128:
838 Width = 128;
839 Align = 128; // int128_t is 128-bit aligned on all targets.
840 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000841 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000842 Width = Target.getFloatWidth();
843 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000844 break;
845 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000846 Width = Target.getDoubleWidth();
847 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000848 break;
849 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000850 Width = Target.getLongDoubleWidth();
851 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000852 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000853 case BuiltinType::NullPtr:
854 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
855 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000856 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000857 case BuiltinType::ObjCId:
858 case BuiltinType::ObjCClass:
859 case BuiltinType::ObjCSel:
860 Width = Target.getPointerWidth(0);
861 Align = Target.getPointerAlign(0);
862 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000863 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000864 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000865 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000866 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000867 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000868 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000869 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000870 unsigned AS = getTargetAddressSpace(
871 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff921a45c2008-09-24 15:05:44 +0000872 Width = Target.getPointerWidth(AS);
873 Align = Target.getPointerAlign(AS);
874 break;
875 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000876 case Type::LValueReference:
877 case Type::RValueReference: {
878 // alignof and sizeof should never enter this code path here, so we go
879 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000880 unsigned AS = getTargetAddressSpace(
881 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000882 Width = Target.getPointerWidth(AS);
883 Align = Target.getPointerAlign(AS);
884 break;
885 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000886 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000887 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000888 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000889 Align = Target.getPointerAlign(AS);
890 break;
891 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000892 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000893 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000894 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000895 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000896 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000897 Align = PtrDiffInfo.second;
898 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000899 }
Chris Lattner647fb222007-07-18 18:26:58 +0000900 case Type::Complex: {
901 // Complex types have the same alignment as their elements, but twice the
902 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000903 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000904 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000905 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000906 Align = EltInfo.second;
907 break;
908 }
John McCall8b07ec22010-05-15 11:32:37 +0000909 case Type::ObjCObject:
910 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000911 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000912 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000913 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000914 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000915 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000916 break;
917 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000918 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000919 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000920 const TagType *TT = cast<TagType>(T);
921
922 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +0000923 Width = 8;
924 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +0000925 break;
926 }
Mike Stump11289f42009-09-09 15:08:12 +0000927
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000928 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000929 return getTypeInfo(ET->getDecl()->getIntegerType());
930
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000931 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000932 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000933 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000934 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +0000935 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000936 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000937
Chris Lattner63d2b362009-10-22 05:17:15 +0000938 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000939 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
940 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000941
Richard Smith30482bc2011-02-20 03:19:35 +0000942 case Type::Auto: {
943 const AutoType *A = cast<AutoType>(T);
944 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +0000945 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +0000946 }
947
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000948 case Type::Paren:
949 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
950
Douglas Gregoref462e62009-04-30 17:32:17 +0000951 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +0000952 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000953 std::pair<uint64_t, unsigned> Info
954 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +0000955 // If the typedef has an aligned attribute on it, it overrides any computed
956 // alignment we have. This violates the GCC documentation (which says that
957 // attribute(aligned) can only round up) but matches its implementation.
958 if (unsigned AttrAlign = Typedef->getMaxAlignment())
959 Align = AttrAlign;
960 else
961 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +0000962 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000963 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000964 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000965
966 case Type::TypeOfExpr:
967 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
968 .getTypePtr());
969
970 case Type::TypeOf:
971 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
972
Anders Carlsson81df7b82009-06-24 19:06:50 +0000973 case Type::Decltype:
974 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
975 .getTypePtr());
976
Abramo Bagnara6150c882010-05-11 21:36:43 +0000977 case Type::Elaborated:
978 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000979
John McCall81904512011-01-06 01:58:22 +0000980 case Type::Attributed:
981 return getTypeInfo(
982 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
983
Richard Smith3f1b5d02011-05-05 21:57:07 +0000984 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +0000985 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000986 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +0000987 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
988 // A type alias template specialization may refer to a typedef with the
989 // aligned attribute on it.
990 if (TST->isTypeAlias())
991 return getTypeInfo(TST->getAliasedType().getTypePtr());
992 else
993 return getTypeInfo(getCanonicalType(T));
994 }
995
Douglas Gregoref462e62009-04-30 17:32:17 +0000996 }
Mike Stump11289f42009-09-09 15:08:12 +0000997
Chris Lattner53cfe802007-07-18 17:52:12 +0000998 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000999 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001000}
1001
Ken Dyckcc56c542011-01-15 18:38:59 +00001002/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1003CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1004 return CharUnits::fromQuantity(BitSize / getCharWidth());
1005}
1006
Ken Dyckb0fcc592011-02-11 01:54:29 +00001007/// toBits - Convert a size in characters to a size in characters.
1008int64_t ASTContext::toBits(CharUnits CharSize) const {
1009 return CharSize.getQuantity() * getCharWidth();
1010}
1011
Ken Dyck8c89d592009-12-22 14:23:30 +00001012/// getTypeSizeInChars - Return the size of the specified type, in characters.
1013/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001014CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001015 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001016}
Jay Foad39c79802011-01-12 09:06:06 +00001017CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001018 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001019}
1020
Ken Dycka6046ab2010-01-26 17:25:18 +00001021/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001022/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001023CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001024 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001025}
Jay Foad39c79802011-01-12 09:06:06 +00001026CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001027 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001028}
1029
Chris Lattnera3402cd2009-01-27 18:08:34 +00001030/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1031/// type for the current target in bits. This can be different than the ABI
1032/// alignment in cases where it is beneficial for performance to overalign
1033/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001034unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001035 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001036
1037 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001038 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001039 T = CT->getElementType().getTypePtr();
1040 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1041 T->isSpecificBuiltinType(BuiltinType::LongLong))
1042 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1043
Chris Lattnera3402cd2009-01-27 18:08:34 +00001044 return ABIAlign;
1045}
1046
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001047/// ShallowCollectObjCIvars -
1048/// Collect all ivars, including those synthesized, in the current class.
1049///
1050void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +00001051 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001052 // FIXME. This need be removed but there are two many places which
1053 // assume const-ness of ObjCInterfaceDecl
1054 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1055 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1056 Iv= Iv->getNextIvar())
1057 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001058}
1059
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001060/// DeepCollectObjCIvars -
1061/// This routine first collects all declared, but not synthesized, ivars in
1062/// super class and then collects all ivars, including those synthesized for
1063/// current class. This routine is used for implementation of current class
1064/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001065///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001066void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1067 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +00001068 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001069 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1070 DeepCollectObjCIvars(SuperClass, false, Ivars);
1071 if (!leafClass) {
1072 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1073 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001074 Ivars.push_back(*I);
1075 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001076 else
1077 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001078}
1079
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001080/// CollectInheritedProtocols - Collect all protocols in current class and
1081/// those inherited by it.
1082void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001083 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001084 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001085 // We can use protocol_iterator here instead of
1086 // all_referenced_protocol_iterator since we are walking all categories.
1087 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1088 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001089 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001090 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001091 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001092 PE = Proto->protocol_end(); P != PE; ++P) {
1093 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001094 CollectInheritedProtocols(*P, Protocols);
1095 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001096 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001097
1098 // Categories of this Interface.
1099 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1100 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1101 CollectInheritedProtocols(CDeclChain, Protocols);
1102 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1103 while (SD) {
1104 CollectInheritedProtocols(SD, Protocols);
1105 SD = SD->getSuperClass();
1106 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001107 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001108 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001109 PE = OC->protocol_end(); P != PE; ++P) {
1110 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001111 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001112 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1113 PE = Proto->protocol_end(); P != PE; ++P)
1114 CollectInheritedProtocols(*P, Protocols);
1115 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001116 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001117 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1118 PE = OP->protocol_end(); P != PE; ++P) {
1119 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001120 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001121 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1122 PE = Proto->protocol_end(); P != PE; ++P)
1123 CollectInheritedProtocols(*P, Protocols);
1124 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001125 }
1126}
1127
Jay Foad39c79802011-01-12 09:06:06 +00001128unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001129 unsigned count = 0;
1130 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001131 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1132 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001133 count += CDecl->ivar_size();
1134
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001135 // Count ivar defined in this class's implementation. This
1136 // includes synthesized ivars.
1137 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001138 count += ImplDecl->ivar_size();
1139
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001140 return count;
1141}
1142
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001143/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1144ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1145 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1146 I = ObjCImpls.find(D);
1147 if (I != ObjCImpls.end())
1148 return cast<ObjCImplementationDecl>(I->second);
1149 return 0;
1150}
1151/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1152ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1153 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1154 I = ObjCImpls.find(D);
1155 if (I != ObjCImpls.end())
1156 return cast<ObjCCategoryImplDecl>(I->second);
1157 return 0;
1158}
1159
1160/// \brief Set the implementation of ObjCInterfaceDecl.
1161void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1162 ObjCImplementationDecl *ImplD) {
1163 assert(IFaceD && ImplD && "Passed null params");
1164 ObjCImpls[IFaceD] = ImplD;
1165}
1166/// \brief Set the implementation of ObjCCategoryDecl.
1167void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1168 ObjCCategoryImplDecl *ImplD) {
1169 assert(CatD && ImplD && "Passed null params");
1170 ObjCImpls[CatD] = ImplD;
1171}
1172
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001173/// \brief Get the copy initialization expression of VarDecl,or NULL if
1174/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001175Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001176 assert(VD && "Passed null params");
1177 assert(VD->hasAttr<BlocksAttr>() &&
1178 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001179 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001180 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001181 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1182}
1183
1184/// \brief Set the copy inialization expression of a block var decl.
1185void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1186 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001187 assert(VD->hasAttr<BlocksAttr>() &&
1188 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001189 BlockVarCopyInits[VD] = Init;
1190}
1191
John McCallbcd03502009-12-07 02:54:59 +00001192/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001193///
John McCallbcd03502009-12-07 02:54:59 +00001194/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001195/// the TypeLoc wrappers.
1196///
1197/// \param T the type that will be the basis for type source info. This type
1198/// should refer to how the declarator was written in source code, not to
1199/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001200TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001201 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001202 if (!DataSize)
1203 DataSize = TypeLoc::getFullDataSizeForType(T);
1204 else
1205 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001206 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001207
John McCallbcd03502009-12-07 02:54:59 +00001208 TypeSourceInfo *TInfo =
1209 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1210 new (TInfo) TypeSourceInfo(T);
1211 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001212}
1213
John McCallbcd03502009-12-07 02:54:59 +00001214TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001215 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001216 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001217 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001218 return DI;
1219}
1220
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001221const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001222ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001223 return getObjCLayout(D, 0);
1224}
1225
1226const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001227ASTContext::getASTObjCImplementationLayout(
1228 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001229 return getObjCLayout(D->getClassInterface(), D);
1230}
1231
Chris Lattner983a8bb2007-07-13 22:13:22 +00001232//===----------------------------------------------------------------------===//
1233// Type creation/memoization methods
1234//===----------------------------------------------------------------------===//
1235
Jay Foad39c79802011-01-12 09:06:06 +00001236QualType
John McCall33ddac02011-01-19 10:06:00 +00001237ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1238 unsigned fastQuals = quals.getFastQualifiers();
1239 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001240
1241 // Check if we've already instantiated this type.
1242 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001243 ExtQuals::Profile(ID, baseType, quals);
1244 void *insertPos = 0;
1245 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1246 assert(eq->getQualifiers() == quals);
1247 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001248 }
1249
John McCall33ddac02011-01-19 10:06:00 +00001250 // If the base type is not canonical, make the appropriate canonical type.
1251 QualType canon;
1252 if (!baseType->isCanonicalUnqualified()) {
1253 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1254 canonSplit.second.addConsistentQualifiers(quals);
1255 canon = getExtQualType(canonSplit.first, canonSplit.second);
1256
1257 // Re-find the insert position.
1258 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1259 }
1260
1261 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1262 ExtQualNodes.InsertNode(eq, insertPos);
1263 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001264}
1265
Jay Foad39c79802011-01-12 09:06:06 +00001266QualType
1267ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001268 QualType CanT = getCanonicalType(T);
1269 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001270 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001271
John McCall8ccfcb52009-09-24 19:53:00 +00001272 // If we are composing extended qualifiers together, merge together
1273 // into one ExtQuals node.
1274 QualifierCollector Quals;
1275 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001276
John McCall8ccfcb52009-09-24 19:53:00 +00001277 // If this type already has an address space specified, it cannot get
1278 // another one.
1279 assert(!Quals.hasAddressSpace() &&
1280 "Type cannot be in multiple addr spaces!");
1281 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001282
John McCall8ccfcb52009-09-24 19:53:00 +00001283 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001284}
1285
Chris Lattnerd60183d2009-02-18 22:53:11 +00001286QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001287 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001288 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001289 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001290 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001291
John McCall53fa7142010-12-24 02:08:15 +00001292 if (const PointerType *ptr = T->getAs<PointerType>()) {
1293 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001294 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001295 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1296 return getPointerType(ResultType);
1297 }
1298 }
Mike Stump11289f42009-09-09 15:08:12 +00001299
John McCall8ccfcb52009-09-24 19:53:00 +00001300 // If we are composing extended qualifiers together, merge together
1301 // into one ExtQuals node.
1302 QualifierCollector Quals;
1303 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001304
John McCall8ccfcb52009-09-24 19:53:00 +00001305 // If this type already has an ObjCGC specified, it cannot get
1306 // another one.
1307 assert(!Quals.hasObjCGCAttr() &&
1308 "Type cannot have multiple ObjCGCs!");
1309 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001310
John McCall8ccfcb52009-09-24 19:53:00 +00001311 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001312}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001313
John McCall4f5019e2010-12-19 02:44:49 +00001314const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1315 FunctionType::ExtInfo Info) {
1316 if (T->getExtInfo() == Info)
1317 return T;
1318
1319 QualType Result;
1320 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1321 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1322 } else {
1323 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1324 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1325 EPI.ExtInfo = Info;
1326 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1327 FPT->getNumArgs(), EPI);
1328 }
1329
1330 return cast<FunctionType>(Result.getTypePtr());
1331}
1332
Chris Lattnerc6395932007-06-22 20:56:16 +00001333/// getComplexType - Return the uniqued reference to the type for a complex
1334/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001335QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001336 // Unique pointers, to guarantee there is only one pointer of a particular
1337 // structure.
1338 llvm::FoldingSetNodeID ID;
1339 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001340
Chris Lattnerc6395932007-06-22 20:56:16 +00001341 void *InsertPos = 0;
1342 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1343 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001344
Chris Lattnerc6395932007-06-22 20:56:16 +00001345 // If the pointee type isn't canonical, this won't be a canonical type either,
1346 // so fill in the canonical type field.
1347 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001348 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001349 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001350
Chris Lattnerc6395932007-06-22 20:56:16 +00001351 // Get the new insert position for the node we care about.
1352 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001353 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001354 }
John McCall90d1c2d2009-09-24 23:30:46 +00001355 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001356 Types.push_back(New);
1357 ComplexTypes.InsertNode(New, InsertPos);
1358 return QualType(New, 0);
1359}
1360
Chris Lattner970e54e2006-11-12 00:37:36 +00001361/// getPointerType - Return the uniqued reference to the type for a pointer to
1362/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001363QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001364 // Unique pointers, to guarantee there is only one pointer of a particular
1365 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001366 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001367 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001368
Chris Lattner67521df2007-01-27 01:29:36 +00001369 void *InsertPos = 0;
1370 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001371 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001372
Chris Lattner7ccecb92006-11-12 08:50:50 +00001373 // If the pointee type isn't canonical, this won't be a canonical type either,
1374 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001375 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001376 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001377 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001378
Chris Lattner67521df2007-01-27 01:29:36 +00001379 // Get the new insert position for the node we care about.
1380 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001381 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001382 }
John McCall90d1c2d2009-09-24 23:30:46 +00001383 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001384 Types.push_back(New);
1385 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001386 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001387}
1388
Mike Stump11289f42009-09-09 15:08:12 +00001389/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001390/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001391QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001392 assert(T->isFunctionType() && "block of function types only");
1393 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001394 // structure.
1395 llvm::FoldingSetNodeID ID;
1396 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001397
Steve Naroffec33ed92008-08-27 16:04:49 +00001398 void *InsertPos = 0;
1399 if (BlockPointerType *PT =
1400 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1401 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001402
1403 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001404 // type either so fill in the canonical type field.
1405 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001406 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001407 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001408
Steve Naroffec33ed92008-08-27 16:04:49 +00001409 // Get the new insert position for the node we care about.
1410 BlockPointerType *NewIP =
1411 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001412 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001413 }
John McCall90d1c2d2009-09-24 23:30:46 +00001414 BlockPointerType *New
1415 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001416 Types.push_back(New);
1417 BlockPointerTypes.InsertNode(New, InsertPos);
1418 return QualType(New, 0);
1419}
1420
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001421/// getLValueReferenceType - Return the uniqued reference to the type for an
1422/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001423QualType
1424ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001425 // Unique pointers, to guarantee there is only one pointer of a particular
1426 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001427 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001428 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001429
1430 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001431 if (LValueReferenceType *RT =
1432 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001433 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001434
John McCallfc93cf92009-10-22 22:37:11 +00001435 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1436
Bill Wendling3708c182007-05-27 10:15:43 +00001437 // If the referencee type isn't canonical, this won't be a canonical type
1438 // either, so fill in the canonical type field.
1439 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001440 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1441 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1442 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001443
Bill Wendling3708c182007-05-27 10:15:43 +00001444 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001445 LValueReferenceType *NewIP =
1446 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001447 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001448 }
1449
John McCall90d1c2d2009-09-24 23:30:46 +00001450 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001451 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1452 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001453 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001454 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001455
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001456 return QualType(New, 0);
1457}
1458
1459/// getRValueReferenceType - Return the uniqued reference to the type for an
1460/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001461QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001462 // Unique pointers, to guarantee there is only one pointer of a particular
1463 // structure.
1464 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001465 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001466
1467 void *InsertPos = 0;
1468 if (RValueReferenceType *RT =
1469 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1470 return QualType(RT, 0);
1471
John McCallfc93cf92009-10-22 22:37:11 +00001472 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1473
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001474 // If the referencee type isn't canonical, this won't be a canonical type
1475 // either, so fill in the canonical type field.
1476 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001477 if (InnerRef || !T.isCanonical()) {
1478 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1479 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001480
1481 // Get the new insert position for the node we care about.
1482 RValueReferenceType *NewIP =
1483 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001484 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001485 }
1486
John McCall90d1c2d2009-09-24 23:30:46 +00001487 RValueReferenceType *New
1488 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001489 Types.push_back(New);
1490 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001491 return QualType(New, 0);
1492}
1493
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001494/// getMemberPointerType - Return the uniqued reference to the type for a
1495/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001496QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001497 // Unique pointers, to guarantee there is only one pointer of a particular
1498 // structure.
1499 llvm::FoldingSetNodeID ID;
1500 MemberPointerType::Profile(ID, T, Cls);
1501
1502 void *InsertPos = 0;
1503 if (MemberPointerType *PT =
1504 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1505 return QualType(PT, 0);
1506
1507 // If the pointee or class type isn't canonical, this won't be a canonical
1508 // type either, so fill in the canonical type field.
1509 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001510 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001511 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1512
1513 // Get the new insert position for the node we care about.
1514 MemberPointerType *NewIP =
1515 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001516 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001517 }
John McCall90d1c2d2009-09-24 23:30:46 +00001518 MemberPointerType *New
1519 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001520 Types.push_back(New);
1521 MemberPointerTypes.InsertNode(New, InsertPos);
1522 return QualType(New, 0);
1523}
1524
Mike Stump11289f42009-09-09 15:08:12 +00001525/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001526/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001527QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001528 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001529 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001530 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001531 assert((EltTy->isDependentType() ||
1532 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001533 "Constant array of VLAs is illegal!");
1534
Chris Lattnere2df3f92009-05-13 04:12:56 +00001535 // Convert the array size into a canonical width matching the pointer size for
1536 // the target.
1537 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001538 ArySize =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001539 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001540
Chris Lattner23b7eb62007-06-15 23:05:46 +00001541 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001542 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001543
Chris Lattner36f8e652007-01-27 08:31:04 +00001544 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001545 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001546 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001547 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001548
John McCall33ddac02011-01-19 10:06:00 +00001549 // If the element type isn't canonical or has qualifiers, this won't
1550 // be a canonical type either, so fill in the canonical type field.
1551 QualType Canon;
1552 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1553 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1554 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001555 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001556 Canon = getQualifiedType(Canon, canonSplit.second);
1557
Chris Lattner36f8e652007-01-27 08:31:04 +00001558 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001559 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001560 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001561 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001562 }
Mike Stump11289f42009-09-09 15:08:12 +00001563
John McCall90d1c2d2009-09-24 23:30:46 +00001564 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001565 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001566 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001567 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001568 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001569}
1570
John McCall06549462011-01-18 08:40:38 +00001571/// getVariableArrayDecayedType - Turns the given type, which may be
1572/// variably-modified, into the corresponding type with all the known
1573/// sizes replaced with [*].
1574QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1575 // Vastly most common case.
1576 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001577
John McCall06549462011-01-18 08:40:38 +00001578 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001579
John McCall06549462011-01-18 08:40:38 +00001580 SplitQualType split = type.getSplitDesugaredType();
1581 const Type *ty = split.first;
1582 switch (ty->getTypeClass()) {
1583#define TYPE(Class, Base)
1584#define ABSTRACT_TYPE(Class, Base)
1585#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1586#include "clang/AST/TypeNodes.def"
1587 llvm_unreachable("didn't desugar past all non-canonical types?");
1588
1589 // These types should never be variably-modified.
1590 case Type::Builtin:
1591 case Type::Complex:
1592 case Type::Vector:
1593 case Type::ExtVector:
1594 case Type::DependentSizedExtVector:
1595 case Type::ObjCObject:
1596 case Type::ObjCInterface:
1597 case Type::ObjCObjectPointer:
1598 case Type::Record:
1599 case Type::Enum:
1600 case Type::UnresolvedUsing:
1601 case Type::TypeOfExpr:
1602 case Type::TypeOf:
1603 case Type::Decltype:
1604 case Type::DependentName:
1605 case Type::InjectedClassName:
1606 case Type::TemplateSpecialization:
1607 case Type::DependentTemplateSpecialization:
1608 case Type::TemplateTypeParm:
1609 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001610 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001611 case Type::PackExpansion:
1612 llvm_unreachable("type should never be variably-modified");
1613
1614 // These types can be variably-modified but should never need to
1615 // further decay.
1616 case Type::FunctionNoProto:
1617 case Type::FunctionProto:
1618 case Type::BlockPointer:
1619 case Type::MemberPointer:
1620 return type;
1621
1622 // These types can be variably-modified. All these modifications
1623 // preserve structure except as noted by comments.
1624 // TODO: if we ever care about optimizing VLAs, there are no-op
1625 // optimizations available here.
1626 case Type::Pointer:
1627 result = getPointerType(getVariableArrayDecayedType(
1628 cast<PointerType>(ty)->getPointeeType()));
1629 break;
1630
1631 case Type::LValueReference: {
1632 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1633 result = getLValueReferenceType(
1634 getVariableArrayDecayedType(lv->getPointeeType()),
1635 lv->isSpelledAsLValue());
1636 break;
1637 }
1638
1639 case Type::RValueReference: {
1640 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1641 result = getRValueReferenceType(
1642 getVariableArrayDecayedType(lv->getPointeeType()));
1643 break;
1644 }
1645
1646 case Type::ConstantArray: {
1647 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1648 result = getConstantArrayType(
1649 getVariableArrayDecayedType(cat->getElementType()),
1650 cat->getSize(),
1651 cat->getSizeModifier(),
1652 cat->getIndexTypeCVRQualifiers());
1653 break;
1654 }
1655
1656 case Type::DependentSizedArray: {
1657 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1658 result = getDependentSizedArrayType(
1659 getVariableArrayDecayedType(dat->getElementType()),
1660 dat->getSizeExpr(),
1661 dat->getSizeModifier(),
1662 dat->getIndexTypeCVRQualifiers(),
1663 dat->getBracketsRange());
1664 break;
1665 }
1666
1667 // Turn incomplete types into [*] types.
1668 case Type::IncompleteArray: {
1669 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1670 result = getVariableArrayType(
1671 getVariableArrayDecayedType(iat->getElementType()),
1672 /*size*/ 0,
1673 ArrayType::Normal,
1674 iat->getIndexTypeCVRQualifiers(),
1675 SourceRange());
1676 break;
1677 }
1678
1679 // Turn VLA types into [*] types.
1680 case Type::VariableArray: {
1681 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1682 result = getVariableArrayType(
1683 getVariableArrayDecayedType(vat->getElementType()),
1684 /*size*/ 0,
1685 ArrayType::Star,
1686 vat->getIndexTypeCVRQualifiers(),
1687 vat->getBracketsRange());
1688 break;
1689 }
1690 }
1691
1692 // Apply the top-level qualifiers from the original.
1693 return getQualifiedType(result, split.second);
1694}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001695
Steve Naroffcadebd02007-08-30 18:14:25 +00001696/// getVariableArrayType - Returns a non-unique reference to the type for a
1697/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001698QualType ASTContext::getVariableArrayType(QualType EltTy,
1699 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001700 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001701 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001702 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001703 // Since we don't unique expressions, it isn't possible to unique VLA's
1704 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001705 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001706
John McCall33ddac02011-01-19 10:06:00 +00001707 // Be sure to pull qualifiers off the element type.
1708 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1709 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1710 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001711 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001712 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001713 }
1714
John McCall90d1c2d2009-09-24 23:30:46 +00001715 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001716 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001717
1718 VariableArrayTypes.push_back(New);
1719 Types.push_back(New);
1720 return QualType(New, 0);
1721}
1722
Douglas Gregor4619e432008-12-05 23:32:09 +00001723/// getDependentSizedArrayType - Returns a non-unique reference to
1724/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001725/// type.
John McCall33ddac02011-01-19 10:06:00 +00001726QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1727 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001728 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001729 unsigned elementTypeQuals,
1730 SourceRange brackets) const {
1731 assert((!numElements || numElements->isTypeDependent() ||
1732 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001733 "Size must be type- or value-dependent!");
1734
John McCall33ddac02011-01-19 10:06:00 +00001735 // Dependently-sized array types that do not have a specified number
1736 // of elements will have their sizes deduced from a dependent
1737 // initializer. We do no canonicalization here at all, which is okay
1738 // because they can't be used in most locations.
1739 if (!numElements) {
1740 DependentSizedArrayType *newType
1741 = new (*this, TypeAlignment)
1742 DependentSizedArrayType(*this, elementType, QualType(),
1743 numElements, ASM, elementTypeQuals,
1744 brackets);
1745 Types.push_back(newType);
1746 return QualType(newType, 0);
1747 }
1748
1749 // Otherwise, we actually build a new type every time, but we
1750 // also build a canonical type.
1751
1752 SplitQualType canonElementType = getCanonicalType(elementType).split();
1753
1754 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001755 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001756 DependentSizedArrayType::Profile(ID, *this,
1757 QualType(canonElementType.first, 0),
1758 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001759
John McCall33ddac02011-01-19 10:06:00 +00001760 // Look for an existing type with these properties.
1761 DependentSizedArrayType *canonTy =
1762 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001763
John McCall33ddac02011-01-19 10:06:00 +00001764 // If we don't have one, build one.
1765 if (!canonTy) {
1766 canonTy = new (*this, TypeAlignment)
1767 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1768 QualType(), numElements, ASM, elementTypeQuals,
1769 brackets);
1770 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1771 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001772 }
1773
John McCall33ddac02011-01-19 10:06:00 +00001774 // Apply qualifiers from the element type to the array.
1775 QualType canon = getQualifiedType(QualType(canonTy,0),
1776 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001777
John McCall33ddac02011-01-19 10:06:00 +00001778 // If we didn't need extra canonicalization for the element type,
1779 // then just use that as our result.
1780 if (QualType(canonElementType.first, 0) == elementType)
1781 return canon;
1782
1783 // Otherwise, we need to build a type which follows the spelling
1784 // of the element type.
1785 DependentSizedArrayType *sugaredType
1786 = new (*this, TypeAlignment)
1787 DependentSizedArrayType(*this, elementType, canon, numElements,
1788 ASM, elementTypeQuals, brackets);
1789 Types.push_back(sugaredType);
1790 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001791}
1792
John McCall33ddac02011-01-19 10:06:00 +00001793QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001794 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001795 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001796 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001797 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001798
John McCall33ddac02011-01-19 10:06:00 +00001799 void *insertPos = 0;
1800 if (IncompleteArrayType *iat =
1801 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1802 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001803
1804 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001805 // either, so fill in the canonical type field. We also have to pull
1806 // qualifiers off the element type.
1807 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001808
John McCall33ddac02011-01-19 10:06:00 +00001809 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1810 SplitQualType canonSplit = getCanonicalType(elementType).split();
1811 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1812 ASM, elementTypeQuals);
1813 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001814
1815 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001816 IncompleteArrayType *existing =
1817 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1818 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001819 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001820
John McCall33ddac02011-01-19 10:06:00 +00001821 IncompleteArrayType *newType = new (*this, TypeAlignment)
1822 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001823
John McCall33ddac02011-01-19 10:06:00 +00001824 IncompleteArrayTypes.InsertNode(newType, insertPos);
1825 Types.push_back(newType);
1826 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001827}
1828
Steve Naroff91fcddb2007-07-18 18:00:27 +00001829/// getVectorType - Return the unique reference to a vector type of
1830/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001831QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001832 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001833 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001834
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001835 // Check if we've already instantiated a vector of this type.
1836 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001837 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001838
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001839 void *InsertPos = 0;
1840 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1841 return QualType(VTP, 0);
1842
1843 // If the element type isn't canonical, this won't be a canonical type either,
1844 // so fill in the canonical type field.
1845 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001846 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001847 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001848
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001849 // Get the new insert position for the node we care about.
1850 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001851 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001852 }
John McCall90d1c2d2009-09-24 23:30:46 +00001853 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001854 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001855 VectorTypes.InsertNode(New, InsertPos);
1856 Types.push_back(New);
1857 return QualType(New, 0);
1858}
1859
Nate Begemance4d7fc2008-04-18 23:10:10 +00001860/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001861/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001862QualType
1863ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall33ddac02011-01-19 10:06:00 +00001864 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001865
Steve Naroff91fcddb2007-07-18 18:00:27 +00001866 // Check if we've already instantiated a vector of this type.
1867 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001868 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001869 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001870 void *InsertPos = 0;
1871 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1872 return QualType(VTP, 0);
1873
1874 // If the element type isn't canonical, this won't be a canonical type either,
1875 // so fill in the canonical type field.
1876 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001877 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001878 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001879
Steve Naroff91fcddb2007-07-18 18:00:27 +00001880 // Get the new insert position for the node we care about.
1881 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001882 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001883 }
John McCall90d1c2d2009-09-24 23:30:46 +00001884 ExtVectorType *New = new (*this, TypeAlignment)
1885 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001886 VectorTypes.InsertNode(New, InsertPos);
1887 Types.push_back(New);
1888 return QualType(New, 0);
1889}
1890
Jay Foad39c79802011-01-12 09:06:06 +00001891QualType
1892ASTContext::getDependentSizedExtVectorType(QualType vecType,
1893 Expr *SizeExpr,
1894 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001895 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001896 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001897 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001898
Douglas Gregor352169a2009-07-31 03:54:25 +00001899 void *InsertPos = 0;
1900 DependentSizedExtVectorType *Canon
1901 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1902 DependentSizedExtVectorType *New;
1903 if (Canon) {
1904 // We already have a canonical version of this array type; use it as
1905 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001906 New = new (*this, TypeAlignment)
1907 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1908 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001909 } else {
1910 QualType CanonVecTy = getCanonicalType(vecType);
1911 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001912 New = new (*this, TypeAlignment)
1913 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1914 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001915
1916 DependentSizedExtVectorType *CanonCheck
1917 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1918 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1919 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001920 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1921 } else {
1922 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1923 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001924 New = new (*this, TypeAlignment)
1925 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001926 }
1927 }
Mike Stump11289f42009-09-09 15:08:12 +00001928
Douglas Gregor758a8692009-06-17 21:51:59 +00001929 Types.push_back(New);
1930 return QualType(New, 0);
1931}
1932
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001933/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001934///
Jay Foad39c79802011-01-12 09:06:06 +00001935QualType
1936ASTContext::getFunctionNoProtoType(QualType ResultTy,
1937 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00001938 const CallingConv DefaultCC = Info.getCC();
1939 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1940 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001941 // Unique functions, to guarantee there is only one function of a particular
1942 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001943 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001944 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001945
Chris Lattner47955de2007-01-27 08:37:20 +00001946 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001947 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001948 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001949 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001950
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001951 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001952 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001953 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001954 Canonical =
1955 getFunctionNoProtoType(getCanonicalType(ResultTy),
1956 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001957
Chris Lattner47955de2007-01-27 08:37:20 +00001958 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001959 FunctionNoProtoType *NewIP =
1960 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001961 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001962 }
Mike Stump11289f42009-09-09 15:08:12 +00001963
Roman Divacky65b88cd2011-03-01 17:40:53 +00001964 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00001965 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00001966 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00001967 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001968 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001969 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001970}
1971
1972/// getFunctionType - Return a normal function type with a typed argument
1973/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001974QualType
1975ASTContext::getFunctionType(QualType ResultTy,
1976 const QualType *ArgArray, unsigned NumArgs,
1977 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001978 // Unique functions, to guarantee there is only one function of a particular
1979 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001980 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00001981 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001982
1983 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001984 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001985 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001986 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001987
1988 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00001989 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001990 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001991 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001992 isCanonical = false;
1993
Roman Divacky65b88cd2011-03-01 17:40:53 +00001994 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
1995 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1996 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00001997
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001998 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001999 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002000 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002001 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002002 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002003 CanonicalArgs.reserve(NumArgs);
2004 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002005 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002006
John McCalldb40c7f2010-12-14 08:05:40 +00002007 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002008 CanonicalEPI.ExceptionSpecType = EST_None;
2009 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002010 CanonicalEPI.ExtInfo
2011 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2012
Chris Lattner76a00cf2008-04-06 22:59:24 +00002013 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002014 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002015 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002016
Chris Lattnerfd4de792007-01-27 01:15:32 +00002017 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002018 FunctionProtoType *NewIP =
2019 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002020 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002021 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002022
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002023 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002024 // for two variable size arrays (for parameter and exception types) at the
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002025 // end of them. Instead of the exception types, there could be a noexcept
2026 // expression and a context pointer.
John McCalldb40c7f2010-12-14 08:05:40 +00002027 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002028 NumArgs * sizeof(QualType);
2029 if (EPI.ExceptionSpecType == EST_Dynamic)
2030 Size += EPI.NumExceptions * sizeof(QualType);
2031 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002032 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002033 }
John McCalldb40c7f2010-12-14 08:05:40 +00002034 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002035 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2036 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002037 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002038 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002039 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002040 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002041}
Chris Lattneref51c202006-11-10 07:17:23 +00002042
John McCalle78aac42010-03-10 03:28:59 +00002043#ifndef NDEBUG
2044static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2045 if (!isa<CXXRecordDecl>(D)) return false;
2046 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2047 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2048 return true;
2049 if (RD->getDescribedClassTemplate() &&
2050 !isa<ClassTemplateSpecializationDecl>(RD))
2051 return true;
2052 return false;
2053}
2054#endif
2055
2056/// getInjectedClassNameType - Return the unique reference to the
2057/// injected class name type for the specified templated declaration.
2058QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002059 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002060 assert(NeedsInjectedClassNameType(Decl));
2061 if (Decl->TypeForDecl) {
2062 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002063 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002064 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2065 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2066 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2067 } else {
John McCall424cec92011-01-19 06:33:43 +00002068 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002069 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002070 Decl->TypeForDecl = newType;
2071 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002072 }
2073 return QualType(Decl->TypeForDecl, 0);
2074}
2075
Douglas Gregor83a586e2008-04-13 21:07:44 +00002076/// getTypeDeclType - Return the unique reference to the type for the
2077/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002078QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002079 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002080 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002081
Richard Smithdda56e42011-04-15 14:24:37 +00002082 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002083 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002084
John McCall96f0b5f2010-03-10 06:48:02 +00002085 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2086 "Template type parameter types are always available.");
2087
John McCall81e38502010-02-16 03:57:14 +00002088 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002089 assert(!Record->getPreviousDeclaration() &&
2090 "struct/union has previous declaration");
2091 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002092 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002093 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002094 assert(!Enum->getPreviousDeclaration() &&
2095 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002096 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002097 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002098 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002099 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2100 Decl->TypeForDecl = newType;
2101 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002102 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002103 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002104
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002105 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002106}
2107
Chris Lattner32d920b2007-01-26 02:01:53 +00002108/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002109/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002110QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002111ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2112 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002113 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002114
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002115 if (Canonical.isNull())
2116 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002117 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002118 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002119 Decl->TypeForDecl = newType;
2120 Types.push_back(newType);
2121 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002122}
2123
Jay Foad39c79802011-01-12 09:06:06 +00002124QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002125 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2126
2127 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2128 if (PrevDecl->TypeForDecl)
2129 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2130
John McCall424cec92011-01-19 06:33:43 +00002131 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2132 Decl->TypeForDecl = newType;
2133 Types.push_back(newType);
2134 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002135}
2136
Jay Foad39c79802011-01-12 09:06:06 +00002137QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002138 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2139
2140 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2141 if (PrevDecl->TypeForDecl)
2142 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2143
John McCall424cec92011-01-19 06:33:43 +00002144 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2145 Decl->TypeForDecl = newType;
2146 Types.push_back(newType);
2147 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002148}
2149
John McCall81904512011-01-06 01:58:22 +00002150QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2151 QualType modifiedType,
2152 QualType equivalentType) {
2153 llvm::FoldingSetNodeID id;
2154 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2155
2156 void *insertPos = 0;
2157 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2158 if (type) return QualType(type, 0);
2159
2160 QualType canon = getCanonicalType(equivalentType);
2161 type = new (*this, TypeAlignment)
2162 AttributedType(canon, attrKind, modifiedType, equivalentType);
2163
2164 Types.push_back(type);
2165 AttributedTypes.InsertNode(type, insertPos);
2166
2167 return QualType(type, 0);
2168}
2169
2170
John McCallcebee162009-10-18 09:09:24 +00002171/// \brief Retrieve a substitution-result type.
2172QualType
2173ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002174 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002175 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002176 && "replacement types must always be canonical");
2177
2178 llvm::FoldingSetNodeID ID;
2179 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2180 void *InsertPos = 0;
2181 SubstTemplateTypeParmType *SubstParm
2182 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2183
2184 if (!SubstParm) {
2185 SubstParm = new (*this, TypeAlignment)
2186 SubstTemplateTypeParmType(Parm, Replacement);
2187 Types.push_back(SubstParm);
2188 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2189 }
2190
2191 return QualType(SubstParm, 0);
2192}
2193
Douglas Gregorada4b792011-01-14 02:55:32 +00002194/// \brief Retrieve a
2195QualType ASTContext::getSubstTemplateTypeParmPackType(
2196 const TemplateTypeParmType *Parm,
2197 const TemplateArgument &ArgPack) {
2198#ifndef NDEBUG
2199 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2200 PEnd = ArgPack.pack_end();
2201 P != PEnd; ++P) {
2202 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2203 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2204 }
2205#endif
2206
2207 llvm::FoldingSetNodeID ID;
2208 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2209 void *InsertPos = 0;
2210 if (SubstTemplateTypeParmPackType *SubstParm
2211 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2212 return QualType(SubstParm, 0);
2213
2214 QualType Canon;
2215 if (!Parm->isCanonicalUnqualified()) {
2216 Canon = getCanonicalType(QualType(Parm, 0));
2217 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2218 ArgPack);
2219 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2220 }
2221
2222 SubstTemplateTypeParmPackType *SubstParm
2223 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2224 ArgPack);
2225 Types.push_back(SubstParm);
2226 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2227 return QualType(SubstParm, 0);
2228}
2229
Douglas Gregoreff93e02009-02-05 23:33:38 +00002230/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002231/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002232/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002233QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002234 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002235 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002236 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002237 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002238 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002239 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002240 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2241
2242 if (TypeParm)
2243 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002244
Chandler Carruth08836322011-05-01 00:51:33 +00002245 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002246 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002247 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002248
2249 TemplateTypeParmType *TypeCheck
2250 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2251 assert(!TypeCheck && "Template type parameter canonical type broken");
2252 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002253 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002254 TypeParm = new (*this, TypeAlignment)
2255 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002256
2257 Types.push_back(TypeParm);
2258 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2259
2260 return QualType(TypeParm, 0);
2261}
2262
John McCalle78aac42010-03-10 03:28:59 +00002263TypeSourceInfo *
2264ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2265 SourceLocation NameLoc,
2266 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002267 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002268 assert(!Name.getAsDependentTemplateName() &&
2269 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002270 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002271
2272 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2273 TemplateSpecializationTypeLoc TL
2274 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2275 TL.setTemplateNameLoc(NameLoc);
2276 TL.setLAngleLoc(Args.getLAngleLoc());
2277 TL.setRAngleLoc(Args.getRAngleLoc());
2278 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2279 TL.setArgLocInfo(i, Args[i].getLocInfo());
2280 return DI;
2281}
2282
Mike Stump11289f42009-09-09 15:08:12 +00002283QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002284ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002285 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002286 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002287 assert(!Template.getAsDependentTemplateName() &&
2288 "No dependent template names here!");
2289
John McCall6b51f282009-11-23 01:53:49 +00002290 unsigned NumArgs = Args.size();
2291
John McCall0ad16662009-10-29 08:12:44 +00002292 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2293 ArgVec.reserve(NumArgs);
2294 for (unsigned i = 0; i != NumArgs; ++i)
2295 ArgVec.push_back(Args[i].getArgument());
2296
John McCall2408e322010-04-27 00:57:59 +00002297 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002298 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002299}
2300
2301QualType
2302ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002303 const TemplateArgument *Args,
2304 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002305 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002306 assert(!Template.getAsDependentTemplateName() &&
2307 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002308 // Look through qualified template names.
2309 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2310 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002311
Richard Smith3f1b5d02011-05-05 21:57:07 +00002312 bool isTypeAlias =
2313 Template.getAsTemplateDecl() &&
2314 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2315
2316 QualType CanonType;
2317 if (!Underlying.isNull())
2318 CanonType = getCanonicalType(Underlying);
2319 else {
2320 assert(!isTypeAlias &&
2321 "Underlying type for template alias must be computed by caller");
2322 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2323 NumArgs);
2324 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002325
Douglas Gregora8e02e72009-07-28 23:00:59 +00002326 // Allocate the (non-canonical) template specialization type, but don't
2327 // try to unique it: these types typically have location information that
2328 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002329 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2330 sizeof(TemplateArgument) * NumArgs +
2331 (isTypeAlias ? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002332 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002333 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002334 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002335 Args, NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002336 CanonType,
2337 isTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002338
Douglas Gregor8bf42052009-02-09 18:46:07 +00002339 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002340 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002341}
2342
Mike Stump11289f42009-09-09 15:08:12 +00002343QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002344ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2345 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002346 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002347 assert(!Template.getAsDependentTemplateName() &&
2348 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002349 assert((!Template.getAsTemplateDecl() ||
2350 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2351 "Underlying type for template alias must be computed by caller");
2352
Douglas Gregore29139c2011-03-03 17:04:51 +00002353 // Look through qualified template names.
2354 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2355 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002356
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002357 // Build the canonical template specialization type.
2358 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2359 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2360 CanonArgs.reserve(NumArgs);
2361 for (unsigned I = 0; I != NumArgs; ++I)
2362 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2363
2364 // Determine whether this canonical template specialization type already
2365 // exists.
2366 llvm::FoldingSetNodeID ID;
2367 TemplateSpecializationType::Profile(ID, CanonTemplate,
2368 CanonArgs.data(), NumArgs, *this);
2369
2370 void *InsertPos = 0;
2371 TemplateSpecializationType *Spec
2372 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2373
2374 if (!Spec) {
2375 // Allocate a new canonical template specialization type.
2376 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2377 sizeof(TemplateArgument) * NumArgs),
2378 TypeAlignment);
2379 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2380 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002381 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002382 Types.push_back(Spec);
2383 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2384 }
2385
2386 assert(Spec->isDependentType() &&
2387 "Non-dependent template-id type must have a canonical type");
2388 return QualType(Spec, 0);
2389}
2390
2391QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002392ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2393 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002394 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002395 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002396 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002397
2398 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002399 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002400 if (T)
2401 return QualType(T, 0);
2402
Douglas Gregorc42075a2010-02-04 18:10:26 +00002403 QualType Canon = NamedType;
2404 if (!Canon.isCanonical()) {
2405 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002406 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2407 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002408 (void)CheckT;
2409 }
2410
Abramo Bagnara6150c882010-05-11 21:36:43 +00002411 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002412 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002413 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002414 return QualType(T, 0);
2415}
2416
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002417QualType
Jay Foad39c79802011-01-12 09:06:06 +00002418ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002419 llvm::FoldingSetNodeID ID;
2420 ParenType::Profile(ID, InnerType);
2421
2422 void *InsertPos = 0;
2423 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2424 if (T)
2425 return QualType(T, 0);
2426
2427 QualType Canon = InnerType;
2428 if (!Canon.isCanonical()) {
2429 Canon = getCanonicalType(InnerType);
2430 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2431 assert(!CheckT && "Paren canonical type broken");
2432 (void)CheckT;
2433 }
2434
2435 T = new (*this) ParenType(InnerType, Canon);
2436 Types.push_back(T);
2437 ParenTypes.InsertNode(T, InsertPos);
2438 return QualType(T, 0);
2439}
2440
Douglas Gregor02085352010-03-31 20:19:30 +00002441QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2442 NestedNameSpecifier *NNS,
2443 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002444 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002445 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2446
2447 if (Canon.isNull()) {
2448 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002449 ElaboratedTypeKeyword CanonKeyword = Keyword;
2450 if (Keyword == ETK_None)
2451 CanonKeyword = ETK_Typename;
2452
2453 if (CanonNNS != NNS || CanonKeyword != Keyword)
2454 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002455 }
2456
2457 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002458 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002459
2460 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002461 DependentNameType *T
2462 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002463 if (T)
2464 return QualType(T, 0);
2465
Douglas Gregor02085352010-03-31 20:19:30 +00002466 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002467 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002468 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002469 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002470}
2471
Mike Stump11289f42009-09-09 15:08:12 +00002472QualType
John McCallc392f372010-06-11 00:33:02 +00002473ASTContext::getDependentTemplateSpecializationType(
2474 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002475 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002476 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002477 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002478 // TODO: avoid this copy
2479 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2480 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2481 ArgCopy.push_back(Args[I].getArgument());
2482 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2483 ArgCopy.size(),
2484 ArgCopy.data());
2485}
2486
2487QualType
2488ASTContext::getDependentTemplateSpecializationType(
2489 ElaboratedTypeKeyword Keyword,
2490 NestedNameSpecifier *NNS,
2491 const IdentifierInfo *Name,
2492 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002493 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002494 assert((!NNS || NNS->isDependent()) &&
2495 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002496
Douglas Gregorc42075a2010-02-04 18:10:26 +00002497 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002498 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2499 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002500
2501 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002502 DependentTemplateSpecializationType *T
2503 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002504 if (T)
2505 return QualType(T, 0);
2506
John McCallc392f372010-06-11 00:33:02 +00002507 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002508
John McCallc392f372010-06-11 00:33:02 +00002509 ElaboratedTypeKeyword CanonKeyword = Keyword;
2510 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2511
2512 bool AnyNonCanonArgs = false;
2513 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2514 for (unsigned I = 0; I != NumArgs; ++I) {
2515 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2516 if (!CanonArgs[I].structurallyEquals(Args[I]))
2517 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002518 }
2519
John McCallc392f372010-06-11 00:33:02 +00002520 QualType Canon;
2521 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2522 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2523 Name, NumArgs,
2524 CanonArgs.data());
2525
2526 // Find the insert position again.
2527 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2528 }
2529
2530 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2531 sizeof(TemplateArgument) * NumArgs),
2532 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002533 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002534 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002535 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002536 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002537 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002538}
2539
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002540QualType ASTContext::getPackExpansionType(QualType Pattern,
2541 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002542 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002543 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002544
2545 assert(Pattern->containsUnexpandedParameterPack() &&
2546 "Pack expansions must expand one or more parameter packs");
2547 void *InsertPos = 0;
2548 PackExpansionType *T
2549 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2550 if (T)
2551 return QualType(T, 0);
2552
2553 QualType Canon;
2554 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002555 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002556
2557 // Find the insert position again.
2558 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2559 }
2560
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002561 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002562 Types.push_back(T);
2563 PackExpansionTypes.InsertNode(T, InsertPos);
2564 return QualType(T, 0);
2565}
2566
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002567/// CmpProtocolNames - Comparison predicate for sorting protocols
2568/// alphabetically.
2569static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2570 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002571 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002572}
2573
John McCall8b07ec22010-05-15 11:32:37 +00002574static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002575 unsigned NumProtocols) {
2576 if (NumProtocols == 0) return true;
2577
2578 for (unsigned i = 1; i != NumProtocols; ++i)
2579 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2580 return false;
2581 return true;
2582}
2583
2584static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002585 unsigned &NumProtocols) {
2586 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002587
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002588 // Sort protocols, keyed by name.
2589 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2590
2591 // Remove duplicates.
2592 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2593 NumProtocols = ProtocolsEnd-Protocols;
2594}
2595
John McCall8b07ec22010-05-15 11:32:37 +00002596QualType ASTContext::getObjCObjectType(QualType BaseType,
2597 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002598 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002599 // If the base type is an interface and there aren't any protocols
2600 // to add, then the interface type will do just fine.
2601 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2602 return BaseType;
2603
2604 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002605 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002606 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002607 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002608 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2609 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002610
John McCall8b07ec22010-05-15 11:32:37 +00002611 // Build the canonical type, which has the canonical base type and
2612 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002613 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002614 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2615 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2616 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002617 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2618 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002619 unsigned UniqueCount = NumProtocols;
2620
John McCallfc93cf92009-10-22 22:37:11 +00002621 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002622 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2623 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002624 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002625 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2626 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002627 }
2628
2629 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002630 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2631 }
2632
2633 unsigned Size = sizeof(ObjCObjectTypeImpl);
2634 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2635 void *Mem = Allocate(Size, TypeAlignment);
2636 ObjCObjectTypeImpl *T =
2637 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2638
2639 Types.push_back(T);
2640 ObjCObjectTypes.InsertNode(T, InsertPos);
2641 return QualType(T, 0);
2642}
2643
2644/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2645/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002646QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002647 llvm::FoldingSetNodeID ID;
2648 ObjCObjectPointerType::Profile(ID, ObjectT);
2649
2650 void *InsertPos = 0;
2651 if (ObjCObjectPointerType *QT =
2652 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2653 return QualType(QT, 0);
2654
2655 // Find the canonical object type.
2656 QualType Canonical;
2657 if (!ObjectT.isCanonical()) {
2658 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2659
2660 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002661 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2662 }
2663
Douglas Gregorf85bee62010-02-08 22:59:26 +00002664 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002665 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2666 ObjCObjectPointerType *QType =
2667 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002668
Steve Narofffb4330f2009-06-17 22:40:22 +00002669 Types.push_back(QType);
2670 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002671 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002672}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002673
Douglas Gregor1c283312010-08-11 12:19:30 +00002674/// getObjCInterfaceType - Return the unique reference to the type for the
2675/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002676QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002677 if (Decl->TypeForDecl)
2678 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002679
Douglas Gregor1c283312010-08-11 12:19:30 +00002680 // FIXME: redeclarations?
2681 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2682 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2683 Decl->TypeForDecl = T;
2684 Types.push_back(T);
2685 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002686}
2687
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002688/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2689/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002690/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002691/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002692/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002693QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002694 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002695 if (tofExpr->isTypeDependent()) {
2696 llvm::FoldingSetNodeID ID;
2697 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002698
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002699 void *InsertPos = 0;
2700 DependentTypeOfExprType *Canon
2701 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2702 if (Canon) {
2703 // We already have a "canonical" version of an identical, dependent
2704 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002705 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002706 QualType((TypeOfExprType*)Canon, 0));
2707 }
2708 else {
2709 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002710 Canon
2711 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002712 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2713 toe = Canon;
2714 }
2715 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002716 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002717 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002718 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002719 Types.push_back(toe);
2720 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002721}
2722
Steve Naroffa773cd52007-08-01 18:02:17 +00002723/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2724/// TypeOfType AST's. The only motivation to unique these nodes would be
2725/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002726/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002727/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002728QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002729 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002730 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002731 Types.push_back(tot);
2732 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002733}
2734
Anders Carlssonad6bd352009-06-24 21:24:56 +00002735/// getDecltypeForExpr - Given an expr, will return the decltype for that
2736/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002737static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002738 if (e->isTypeDependent())
2739 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002740
Anders Carlssonad6bd352009-06-24 21:24:56 +00002741 // If e is an id expression or a class member access, decltype(e) is defined
2742 // as the type of the entity named by e.
2743 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2744 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2745 return VD->getType();
2746 }
2747 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2748 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2749 return FD->getType();
2750 }
2751 // If e is a function call or an invocation of an overloaded operator,
2752 // (parentheses around e are ignored), decltype(e) is defined as the
2753 // return type of that function.
2754 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2755 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002756
Anders Carlssonad6bd352009-06-24 21:24:56 +00002757 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002758
2759 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002760 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002761 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002762 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002763
Anders Carlssonad6bd352009-06-24 21:24:56 +00002764 return T;
2765}
2766
Anders Carlsson81df7b82009-06-24 19:06:50 +00002767/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2768/// DecltypeType AST's. The only motivation to unique these nodes would be
2769/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002770/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002771/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002772QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002773 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002774 if (e->isTypeDependent()) {
2775 llvm::FoldingSetNodeID ID;
2776 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002777
Douglas Gregora21f6c32009-07-30 23:36:40 +00002778 void *InsertPos = 0;
2779 DependentDecltypeType *Canon
2780 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2781 if (Canon) {
2782 // We already have a "canonical" version of an equivalent, dependent
2783 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002784 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002785 QualType((DecltypeType*)Canon, 0));
2786 }
2787 else {
2788 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002789 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002790 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2791 dt = Canon;
2792 }
2793 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002794 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002795 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002796 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002797 Types.push_back(dt);
2798 return QualType(dt, 0);
2799}
2800
Richard Smithb2bc2e62011-02-21 20:05:19 +00002801/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002802QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002803 void *InsertPos = 0;
2804 if (!DeducedType.isNull()) {
2805 // Look in the folding set for an existing type.
2806 llvm::FoldingSetNodeID ID;
2807 AutoType::Profile(ID, DeducedType);
2808 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2809 return QualType(AT, 0);
2810 }
2811
2812 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2813 Types.push_back(AT);
2814 if (InsertPos)
2815 AutoTypes.InsertNode(AT, InsertPos);
2816 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002817}
2818
Richard Smith02e85f32011-04-14 22:09:26 +00002819/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2820QualType ASTContext::getAutoDeductType() const {
2821 if (AutoDeductTy.isNull())
2822 AutoDeductTy = getAutoType(QualType());
2823 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2824 return AutoDeductTy;
2825}
2826
2827/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2828QualType ASTContext::getAutoRRefDeductType() const {
2829 if (AutoRRefDeductTy.isNull())
2830 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2831 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2832 return AutoRRefDeductTy;
2833}
2834
Chris Lattnerfb072462007-01-23 05:45:31 +00002835/// getTagDeclType - Return the unique reference to the type for the
2836/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002837QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002838 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002839 // FIXME: What is the design on getTagDeclType when it requires casting
2840 // away const? mutable?
2841 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002842}
2843
Mike Stump11289f42009-09-09 15:08:12 +00002844/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2845/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2846/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002847CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002848 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002849}
Chris Lattnerfb072462007-01-23 05:45:31 +00002850
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002851/// getSignedWCharType - Return the type of "signed wchar_t".
2852/// Used when in C++, as a GCC extension.
2853QualType ASTContext::getSignedWCharType() const {
2854 // FIXME: derive from "Target" ?
2855 return WCharTy;
2856}
2857
2858/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2859/// Used when in C++, as a GCC extension.
2860QualType ASTContext::getUnsignedWCharType() const {
2861 // FIXME: derive from "Target" ?
2862 return UnsignedIntTy;
2863}
2864
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002865/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2866/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2867QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002868 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002869}
2870
Chris Lattnera21ad802008-04-02 05:18:44 +00002871//===----------------------------------------------------------------------===//
2872// Type Operators
2873//===----------------------------------------------------------------------===//
2874
Jay Foad39c79802011-01-12 09:06:06 +00002875CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002876 // Push qualifiers into arrays, and then discard any remaining
2877 // qualifiers.
2878 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002879 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002880 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002881 QualType Result;
2882 if (isa<ArrayType>(Ty)) {
2883 Result = getArrayDecayedType(QualType(Ty,0));
2884 } else if (isa<FunctionType>(Ty)) {
2885 Result = getPointerType(QualType(Ty, 0));
2886 } else {
2887 Result = QualType(Ty, 0);
2888 }
2889
2890 return CanQualType::CreateUnsafe(Result);
2891}
2892
Chris Lattner7adf0762008-08-04 07:31:14 +00002893
John McCall6c9dd522011-01-18 07:41:22 +00002894QualType ASTContext::getUnqualifiedArrayType(QualType type,
2895 Qualifiers &quals) {
2896 SplitQualType splitType = type.getSplitUnqualifiedType();
2897
2898 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2899 // the unqualified desugared type and then drops it on the floor.
2900 // We then have to strip that sugar back off with
2901 // getUnqualifiedDesugaredType(), which is silly.
2902 const ArrayType *AT =
2903 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2904
2905 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002906 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002907 quals = splitType.second;
2908 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002909 }
2910
John McCall6c9dd522011-01-18 07:41:22 +00002911 // Otherwise, recurse on the array's element type.
2912 QualType elementType = AT->getElementType();
2913 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2914
2915 // If that didn't change the element type, AT has no qualifiers, so we
2916 // can just use the results in splitType.
2917 if (elementType == unqualElementType) {
2918 assert(quals.empty()); // from the recursive call
2919 quals = splitType.second;
2920 return QualType(splitType.first, 0);
2921 }
2922
2923 // Otherwise, add in the qualifiers from the outermost type, then
2924 // build the type back up.
2925 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002926
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002927 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002928 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002929 CAT->getSizeModifier(), 0);
2930 }
2931
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002932 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002933 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002934 }
2935
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002936 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002937 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002938 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002939 VAT->getSizeModifier(),
2940 VAT->getIndexTypeCVRQualifiers(),
2941 VAT->getBracketsRange());
2942 }
2943
2944 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002945 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002946 DSAT->getSizeModifier(), 0,
2947 SourceRange());
2948}
2949
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002950/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2951/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2952/// they point to and return true. If T1 and T2 aren't pointer types
2953/// or pointer-to-member types, or if they are not similar at this
2954/// level, returns false and leaves T1 and T2 unchanged. Top-level
2955/// qualifiers on T1 and T2 are ignored. This function will typically
2956/// be called in a loop that successively "unwraps" pointer and
2957/// pointer-to-member types to compare them at each level.
2958bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2959 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2960 *T2PtrType = T2->getAs<PointerType>();
2961 if (T1PtrType && T2PtrType) {
2962 T1 = T1PtrType->getPointeeType();
2963 T2 = T2PtrType->getPointeeType();
2964 return true;
2965 }
2966
2967 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2968 *T2MPType = T2->getAs<MemberPointerType>();
2969 if (T1MPType && T2MPType &&
2970 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2971 QualType(T2MPType->getClass(), 0))) {
2972 T1 = T1MPType->getPointeeType();
2973 T2 = T2MPType->getPointeeType();
2974 return true;
2975 }
2976
2977 if (getLangOptions().ObjC1) {
2978 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2979 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2980 if (T1OPType && T2OPType) {
2981 T1 = T1OPType->getPointeeType();
2982 T2 = T2OPType->getPointeeType();
2983 return true;
2984 }
2985 }
2986
2987 // FIXME: Block pointers, too?
2988
2989 return false;
2990}
2991
Jay Foad39c79802011-01-12 09:06:06 +00002992DeclarationNameInfo
2993ASTContext::getNameForTemplate(TemplateName Name,
2994 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002995 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002996 // DNInfo work in progress: CHECKME: what about DNLoc?
2997 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2998
John McCall847e2a12009-11-24 18:42:40 +00002999 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003000 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003001 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003002 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3003 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003004 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003005 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3006 // DNInfo work in progress: FIXME: source locations?
3007 DeclarationNameLoc DNLoc;
3008 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3009 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3010 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003011 }
3012 }
3013
John McCalld28ae272009-12-02 08:04:21 +00003014 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3015 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003016 // DNInfo work in progress: CHECKME: what about DNLoc?
3017 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003018}
3019
Jay Foad39c79802011-01-12 09:06:06 +00003020TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003021 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3022 if (TemplateTemplateParmDecl *TTP
3023 = dyn_cast<TemplateTemplateParmDecl>(Template))
3024 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3025
3026 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003027 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003028 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003029
Douglas Gregor5590be02011-01-15 06:45:20 +00003030 if (SubstTemplateTemplateParmPackStorage *SubstPack
3031 = Name.getAsSubstTemplateTemplateParmPack()) {
3032 TemplateTemplateParmDecl *CanonParam
3033 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
3034 TemplateArgument CanonArgPack
3035 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
3036 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
3037 }
3038
John McCalld28ae272009-12-02 08:04:21 +00003039 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00003040
Douglas Gregor6bc50582009-05-07 06:41:52 +00003041 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3042 assert(DTN && "Non-dependent template names must refer to template decls.");
3043 return DTN->CanonicalTemplateName;
3044}
3045
Douglas Gregoradee3e32009-11-11 23:06:43 +00003046bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3047 X = getCanonicalTemplateName(X);
3048 Y = getCanonicalTemplateName(Y);
3049 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3050}
3051
Mike Stump11289f42009-09-09 15:08:12 +00003052TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003053ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003054 switch (Arg.getKind()) {
3055 case TemplateArgument::Null:
3056 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003057
Douglas Gregora8e02e72009-07-28 23:00:59 +00003058 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003059 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003060
Douglas Gregora8e02e72009-07-28 23:00:59 +00003061 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003062 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003063
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003064 case TemplateArgument::Template:
3065 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003066
3067 case TemplateArgument::TemplateExpansion:
3068 return TemplateArgument(getCanonicalTemplateName(
3069 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003070 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003071
Douglas Gregora8e02e72009-07-28 23:00:59 +00003072 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003073 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003074 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003075
Douglas Gregora8e02e72009-07-28 23:00:59 +00003076 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003077 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003078
Douglas Gregora8e02e72009-07-28 23:00:59 +00003079 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003080 if (Arg.pack_size() == 0)
3081 return Arg;
3082
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003083 TemplateArgument *CanonArgs
3084 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003085 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003086 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003087 AEnd = Arg.pack_end();
3088 A != AEnd; (void)++A, ++Idx)
3089 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003090
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003091 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003092 }
3093 }
3094
3095 // Silence GCC warning
3096 assert(false && "Unhandled template argument kind");
3097 return TemplateArgument();
3098}
3099
Douglas Gregor333489b2009-03-27 23:10:48 +00003100NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003101ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003102 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003103 return 0;
3104
3105 switch (NNS->getKind()) {
3106 case NestedNameSpecifier::Identifier:
3107 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003108 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003109 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3110 NNS->getAsIdentifier());
3111
3112 case NestedNameSpecifier::Namespace:
3113 // A namespace is canonical; build a nested-name-specifier with
3114 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003115 return NestedNameSpecifier::Create(*this, 0,
3116 NNS->getAsNamespace()->getOriginalNamespace());
3117
3118 case NestedNameSpecifier::NamespaceAlias:
3119 // A namespace is canonical; build a nested-name-specifier with
3120 // this namespace and no prefix.
3121 return NestedNameSpecifier::Create(*this, 0,
3122 NNS->getAsNamespaceAlias()->getNamespace()
3123 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003124
3125 case NestedNameSpecifier::TypeSpec:
3126 case NestedNameSpecifier::TypeSpecWithTemplate: {
3127 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003128
3129 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3130 // break it apart into its prefix and identifier, then reconsititute those
3131 // as the canonical nested-name-specifier. This is required to canonicalize
3132 // a dependent nested-name-specifier involving typedefs of dependent-name
3133 // types, e.g.,
3134 // typedef typename T::type T1;
3135 // typedef typename T1::type T2;
3136 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3137 NestedNameSpecifier *Prefix
3138 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3139 return NestedNameSpecifier::Create(*this, Prefix,
3140 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3141 }
3142
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003143 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003144 if (const DependentTemplateSpecializationType *DTST
3145 = T->getAs<DependentTemplateSpecializationType>()) {
3146 NestedNameSpecifier *Prefix
3147 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003148
3149 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3150 Prefix, DTST->getIdentifier(),
3151 DTST->getNumArgs(),
3152 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003153 T = getCanonicalType(T);
3154 }
3155
John McCall33ddac02011-01-19 10:06:00 +00003156 return NestedNameSpecifier::Create(*this, 0, false,
3157 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003158 }
3159
3160 case NestedNameSpecifier::Global:
3161 // The global specifier is canonical and unique.
3162 return NNS;
3163 }
3164
3165 // Required to silence a GCC warning
3166 return 0;
3167}
3168
Chris Lattner7adf0762008-08-04 07:31:14 +00003169
Jay Foad39c79802011-01-12 09:06:06 +00003170const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003171 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003172 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003173 // Handle the common positive case fast.
3174 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3175 return AT;
3176 }
Mike Stump11289f42009-09-09 15:08:12 +00003177
John McCall8ccfcb52009-09-24 19:53:00 +00003178 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003179 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003180 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003181
John McCall8ccfcb52009-09-24 19:53:00 +00003182 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003183 // implements C99 6.7.3p8: "If the specification of an array type includes
3184 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003185
Chris Lattner7adf0762008-08-04 07:31:14 +00003186 // If we get here, we either have type qualifiers on the type, or we have
3187 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003188 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003189
John McCall33ddac02011-01-19 10:06:00 +00003190 SplitQualType split = T.getSplitDesugaredType();
3191 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003192
Chris Lattner7adf0762008-08-04 07:31:14 +00003193 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003194 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3195 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003196 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003197
Chris Lattner7adf0762008-08-04 07:31:14 +00003198 // Otherwise, we have an array and we have qualifiers on it. Push the
3199 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003200 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003201
Chris Lattner7adf0762008-08-04 07:31:14 +00003202 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3203 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3204 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003205 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003206 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3207 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3208 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003209 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003210
Mike Stump11289f42009-09-09 15:08:12 +00003211 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003212 = dyn_cast<DependentSizedArrayType>(ATy))
3213 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003214 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003215 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003216 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003217 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003218 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003219
Chris Lattner7adf0762008-08-04 07:31:14 +00003220 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003221 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003222 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003223 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003224 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003225 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003226}
3227
Chris Lattnera21ad802008-04-02 05:18:44 +00003228/// getArrayDecayedType - Return the properly qualified result of decaying the
3229/// specified array type to a pointer. This operation is non-trivial when
3230/// handling typedefs etc. The canonical type of "T" must be an array type,
3231/// this returns a pointer to a properly qualified element of the array.
3232///
3233/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003234QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003235 // Get the element type with 'getAsArrayType' so that we don't lose any
3236 // typedefs in the element type of the array. This also handles propagation
3237 // of type qualifiers from the array type into the element type if present
3238 // (C99 6.7.3p8).
3239 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3240 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003241
Chris Lattner7adf0762008-08-04 07:31:14 +00003242 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003243
3244 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003245 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003246}
3247
John McCall33ddac02011-01-19 10:06:00 +00003248QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3249 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003250}
3251
John McCall33ddac02011-01-19 10:06:00 +00003252QualType ASTContext::getBaseElementType(QualType type) const {
3253 Qualifiers qs;
3254 while (true) {
3255 SplitQualType split = type.getSplitDesugaredType();
3256 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3257 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003258
John McCall33ddac02011-01-19 10:06:00 +00003259 type = array->getElementType();
3260 qs.addConsistentQualifiers(split.second);
3261 }
Mike Stump11289f42009-09-09 15:08:12 +00003262
John McCall33ddac02011-01-19 10:06:00 +00003263 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003264}
3265
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003266/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003267uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003268ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3269 uint64_t ElementCount = 1;
3270 do {
3271 ElementCount *= CA->getSize().getZExtValue();
3272 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3273 } while (CA);
3274 return ElementCount;
3275}
3276
Steve Naroff0af91202007-04-27 21:51:21 +00003277/// getFloatingRank - Return a relative rank for floating point types.
3278/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003279static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003280 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003281 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003282
John McCall9dd450b2009-09-21 23:43:11 +00003283 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3284 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003285 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003286 case BuiltinType::Float: return FloatRank;
3287 case BuiltinType::Double: return DoubleRank;
3288 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003289 }
3290}
3291
Mike Stump11289f42009-09-09 15:08:12 +00003292/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3293/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003294/// 'typeDomain' is a real floating point or complex type.
3295/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003296QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3297 QualType Domain) const {
3298 FloatingRank EltRank = getFloatingRank(Size);
3299 if (Domain->isComplexType()) {
3300 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003301 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003302 case FloatRank: return FloatComplexTy;
3303 case DoubleRank: return DoubleComplexTy;
3304 case LongDoubleRank: return LongDoubleComplexTy;
3305 }
Steve Naroff0af91202007-04-27 21:51:21 +00003306 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003307
3308 assert(Domain->isRealFloatingType() && "Unknown domain!");
3309 switch (EltRank) {
3310 default: assert(0 && "getFloatingRank(): illegal value for rank");
3311 case FloatRank: return FloatTy;
3312 case DoubleRank: return DoubleTy;
3313 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003314 }
Steve Naroffe4718892007-04-27 18:30:00 +00003315}
3316
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003317/// getFloatingTypeOrder - Compare the rank of the two specified floating
3318/// point types, ignoring the domain of the type (i.e. 'double' ==
3319/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003320/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003321int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003322 FloatingRank LHSR = getFloatingRank(LHS);
3323 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003324
Chris Lattnerb90739d2008-04-06 23:38:49 +00003325 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003326 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003327 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003328 return 1;
3329 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003330}
3331
Chris Lattner76a00cf2008-04-06 22:59:24 +00003332/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3333/// routine will assert if passed a built-in type that isn't an integer or enum,
3334/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003335unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003336 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003337 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003338 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003339
Chris Lattnerad3467e2010-12-25 23:25:43 +00003340 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3341 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003342 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3343
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003344 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3345 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3346
3347 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3348 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3349
Chris Lattner76a00cf2008-04-06 22:59:24 +00003350 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003351 default: assert(0 && "getIntegerRank(): not a built-in integer");
3352 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003353 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003354 case BuiltinType::Char_S:
3355 case BuiltinType::Char_U:
3356 case BuiltinType::SChar:
3357 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003358 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003359 case BuiltinType::Short:
3360 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003361 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003362 case BuiltinType::Int:
3363 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003364 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003365 case BuiltinType::Long:
3366 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003367 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003368 case BuiltinType::LongLong:
3369 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003370 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003371 case BuiltinType::Int128:
3372 case BuiltinType::UInt128:
3373 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003374 }
3375}
3376
Eli Friedman629ffb92009-08-20 04:21:42 +00003377/// \brief Whether this is a promotable bitfield reference according
3378/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3379///
3380/// \returns the type this bit-field will promote to, or NULL if no
3381/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003382QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003383 if (E->isTypeDependent() || E->isValueDependent())
3384 return QualType();
3385
Eli Friedman629ffb92009-08-20 04:21:42 +00003386 FieldDecl *Field = E->getBitField();
3387 if (!Field)
3388 return QualType();
3389
3390 QualType FT = Field->getType();
3391
3392 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3393 uint64_t BitWidth = BitWidthAP.getZExtValue();
3394 uint64_t IntSize = getTypeSize(IntTy);
3395 // GCC extension compatibility: if the bit-field size is less than or equal
3396 // to the size of int, it gets promoted no matter what its type is.
3397 // For instance, unsigned long bf : 4 gets promoted to signed int.
3398 if (BitWidth < IntSize)
3399 return IntTy;
3400
3401 if (BitWidth == IntSize)
3402 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3403
3404 // Types bigger than int are not subject to promotions, and therefore act
3405 // like the base type.
3406 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3407 // is ridiculous.
3408 return QualType();
3409}
3410
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003411/// getPromotedIntegerType - Returns the type that Promotable will
3412/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3413/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003414QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003415 assert(!Promotable.isNull());
3416 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003417 if (const EnumType *ET = Promotable->getAs<EnumType>())
3418 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003419 if (Promotable->isSignedIntegerType())
3420 return IntTy;
3421 uint64_t PromotableSize = getTypeSize(Promotable);
3422 uint64_t IntSize = getTypeSize(IntTy);
3423 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3424 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3425}
3426
Mike Stump11289f42009-09-09 15:08:12 +00003427/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003428/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003429/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003430int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003431 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3432 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003433 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003434
Chris Lattner76a00cf2008-04-06 22:59:24 +00003435 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3436 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003437
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003438 unsigned LHSRank = getIntegerRank(LHSC);
3439 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003440
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003441 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3442 if (LHSRank == RHSRank) return 0;
3443 return LHSRank > RHSRank ? 1 : -1;
3444 }
Mike Stump11289f42009-09-09 15:08:12 +00003445
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003446 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3447 if (LHSUnsigned) {
3448 // If the unsigned [LHS] type is larger, return it.
3449 if (LHSRank >= RHSRank)
3450 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003451
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003452 // If the signed type can represent all values of the unsigned type, it
3453 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003454 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003455 return -1;
3456 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003457
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003458 // If the unsigned [RHS] type is larger, return it.
3459 if (RHSRank >= LHSRank)
3460 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003461
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003462 // If the signed type can represent all values of the unsigned type, it
3463 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003464 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003465 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003466}
Anders Carlsson98f07902007-08-17 05:31:46 +00003467
Anders Carlsson6d417272009-11-14 21:45:58 +00003468static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003469CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3470 DeclContext *DC, IdentifierInfo *Id) {
3471 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003472 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003473 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003474 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003475 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003476}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003477
Mike Stump11289f42009-09-09 15:08:12 +00003478// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003479QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003480 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003481 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003482 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003483 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003484 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003485
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003486 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003487
Anders Carlsson98f07902007-08-17 05:31:46 +00003488 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003489 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003490 // int flags;
3491 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003492 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003493 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003494 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003495 FieldTypes[3] = LongTy;
3496
Anders Carlsson98f07902007-08-17 05:31:46 +00003497 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003498 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003499 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003500 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +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 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003507 }
3508
Douglas Gregord5058122010-02-11 01:19:42 +00003509 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003510 }
Mike Stump11289f42009-09-09 15:08:12 +00003511
Anders Carlsson98f07902007-08-17 05:31:46 +00003512 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003513}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003514
Douglas Gregor512b0772009-04-23 22:29:11 +00003515void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003516 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003517 assert(Rec && "Invalid CFConstantStringType");
3518 CFConstantStringTypeDecl = Rec->getDecl();
3519}
3520
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003521// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003522QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003523 if (!NSConstantStringTypeDecl) {
3524 NSConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003525 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003526 &Idents.get("__builtin_NSString"));
3527 NSConstantStringTypeDecl->startDefinition();
3528
3529 QualType FieldTypes[3];
3530
3531 // const int *isa;
3532 FieldTypes[0] = getPointerType(IntTy.withConst());
3533 // const char *str;
3534 FieldTypes[1] = getPointerType(CharTy.withConst());
3535 // unsigned int length;
3536 FieldTypes[2] = UnsignedIntTy;
3537
3538 // Create fields
3539 for (unsigned i = 0; i < 3; ++i) {
3540 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003541 SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003542 SourceLocation(), 0,
3543 FieldTypes[i], /*TInfo=*/0,
3544 /*BitWidth=*/0,
3545 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003546 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003547 NSConstantStringTypeDecl->addDecl(Field);
3548 }
3549
3550 NSConstantStringTypeDecl->completeDefinition();
3551 }
3552
3553 return getTagDeclType(NSConstantStringTypeDecl);
3554}
3555
3556void ASTContext::setNSConstantStringType(QualType T) {
3557 const RecordType *Rec = T->getAs<RecordType>();
3558 assert(Rec && "Invalid NSConstantStringType");
3559 NSConstantStringTypeDecl = Rec->getDecl();
3560}
3561
Jay Foad39c79802011-01-12 09:06:06 +00003562QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003563 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003564 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003565 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003566 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003567 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003568
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003569 QualType FieldTypes[] = {
3570 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003571 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003572 getPointerType(UnsignedLongTy),
3573 getConstantArrayType(UnsignedLongTy,
3574 llvm::APInt(32, 5), ArrayType::Normal, 0)
3575 };
Mike Stump11289f42009-09-09 15:08:12 +00003576
Douglas Gregor91f84212008-12-11 16:49:14 +00003577 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003578 FieldDecl *Field = FieldDecl::Create(*this,
3579 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003580 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003581 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003582 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003583 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003584 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003585 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003586 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003587 }
Mike Stump11289f42009-09-09 15:08:12 +00003588
Douglas Gregord5058122010-02-11 01:19:42 +00003589 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003590 }
Mike Stump11289f42009-09-09 15:08:12 +00003591
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003592 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3593}
3594
Jay Foad39c79802011-01-12 09:06:06 +00003595QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003596 if (BlockDescriptorType)
3597 return getTagDeclType(BlockDescriptorType);
3598
3599 RecordDecl *T;
3600 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003601 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003602 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003603 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003604
3605 QualType FieldTypes[] = {
3606 UnsignedLongTy,
3607 UnsignedLongTy,
3608 };
3609
3610 const char *FieldNames[] = {
3611 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003612 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003613 };
3614
3615 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003616 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003617 SourceLocation(),
3618 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003619 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003620 /*BitWidth=*/0,
3621 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003622 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003623 T->addDecl(Field);
3624 }
3625
Douglas Gregord5058122010-02-11 01:19:42 +00003626 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003627
3628 BlockDescriptorType = T;
3629
3630 return getTagDeclType(BlockDescriptorType);
3631}
3632
3633void ASTContext::setBlockDescriptorType(QualType T) {
3634 const RecordType *Rec = T->getAs<RecordType>();
3635 assert(Rec && "Invalid BlockDescriptorType");
3636 BlockDescriptorType = Rec->getDecl();
3637}
3638
Jay Foad39c79802011-01-12 09:06:06 +00003639QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003640 if (BlockDescriptorExtendedType)
3641 return getTagDeclType(BlockDescriptorExtendedType);
3642
3643 RecordDecl *T;
3644 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003645 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003646 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003647 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003648
3649 QualType FieldTypes[] = {
3650 UnsignedLongTy,
3651 UnsignedLongTy,
3652 getPointerType(VoidPtrTy),
3653 getPointerType(VoidPtrTy)
3654 };
3655
3656 const char *FieldNames[] = {
3657 "reserved",
3658 "Size",
3659 "CopyFuncPtr",
3660 "DestroyFuncPtr"
3661 };
3662
3663 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003664 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003665 SourceLocation(),
3666 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003667 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003668 /*BitWidth=*/0,
3669 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003670 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003671 T->addDecl(Field);
3672 }
3673
Douglas Gregord5058122010-02-11 01:19:42 +00003674 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003675
3676 BlockDescriptorExtendedType = T;
3677
3678 return getTagDeclType(BlockDescriptorExtendedType);
3679}
3680
3681void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3682 const RecordType *Rec = T->getAs<RecordType>();
3683 assert(Rec && "Invalid BlockDescriptorType");
3684 BlockDescriptorExtendedType = Rec->getDecl();
3685}
3686
Jay Foad39c79802011-01-12 09:06:06 +00003687bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003688 if (Ty->isBlockPointerType())
3689 return true;
3690 if (isObjCNSObjectType(Ty))
3691 return true;
3692 if (Ty->isObjCObjectPointerType())
3693 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003694 if (getLangOptions().CPlusPlus) {
3695 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3696 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3697 return RD->hasConstCopyConstructor(*this);
3698
3699 }
3700 }
Mike Stump94967902009-10-21 18:16:27 +00003701 return false;
3702}
3703
Jay Foad39c79802011-01-12 09:06:06 +00003704QualType
3705ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003706 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003707 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003708 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003709 // unsigned int __flags;
3710 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003711 // void *__copy_helper; // as needed
3712 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003713 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003714 // } *
3715
Mike Stump94967902009-10-21 18:16:27 +00003716 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3717
3718 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003719 llvm::SmallString<36> Name;
3720 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3721 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003722 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003723 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003724 T->startDefinition();
3725 QualType Int32Ty = IntTy;
3726 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3727 QualType FieldTypes[] = {
3728 getPointerType(VoidPtrTy),
3729 getPointerType(getTagDeclType(T)),
3730 Int32Ty,
3731 Int32Ty,
3732 getPointerType(VoidPtrTy),
3733 getPointerType(VoidPtrTy),
3734 Ty
3735 };
3736
Daniel Dunbar56df9772010-08-17 22:39:59 +00003737 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003738 "__isa",
3739 "__forwarding",
3740 "__flags",
3741 "__size",
3742 "__copy_helper",
3743 "__destroy_helper",
3744 DeclName,
3745 };
3746
3747 for (size_t i = 0; i < 7; ++i) {
3748 if (!HasCopyAndDispose && i >=4 && i <= 5)
3749 continue;
3750 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003751 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003752 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003753 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003754 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003755 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003756 T->addDecl(Field);
3757 }
3758
Douglas Gregord5058122010-02-11 01:19:42 +00003759 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003760
3761 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003762}
3763
Douglas Gregor512b0772009-04-23 22:29:11 +00003764void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003765 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003766 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3767 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3768}
3769
Anders Carlsson18acd442007-10-29 06:33:42 +00003770// This returns true if a type has been typedefed to BOOL:
3771// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003772static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003773 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003774 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3775 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003776
Anders Carlssond8499822007-10-29 05:01:08 +00003777 return false;
3778}
3779
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003780/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003781/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003782CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003783 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003784
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003785 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003786 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003787 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003788 // Treat arrays as pointers, since that's how they're passed in.
3789 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003790 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003791 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003792}
3793
3794static inline
3795std::string charUnitsToString(const CharUnits &CU) {
3796 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003797}
3798
John McCall351762c2011-02-07 10:33:21 +00003799/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003800/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003801std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3802 std::string S;
3803
David Chisnall950a9512009-11-17 19:33:30 +00003804 const BlockDecl *Decl = Expr->getBlockDecl();
3805 QualType BlockTy =
3806 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3807 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003808 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003809 // Compute size of all parameters.
3810 // Start with computing size of a pointer in number of bytes.
3811 // FIXME: There might(should) be a better way of doing this computation!
3812 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003813 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3814 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003815 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003816 E = Decl->param_end(); PI != E; ++PI) {
3817 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003818 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003819 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003820 ParmOffset += sz;
3821 }
3822 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003823 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003824 // Block pointer and offset.
3825 S += "@?0";
3826 ParmOffset = PtrSize;
3827
3828 // Argument types.
3829 ParmOffset = PtrSize;
3830 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3831 Decl->param_end(); PI != E; ++PI) {
3832 ParmVarDecl *PVDecl = *PI;
3833 QualType PType = PVDecl->getOriginalType();
3834 if (const ArrayType *AT =
3835 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3836 // Use array's original type only if it has known number of
3837 // elements.
3838 if (!isa<ConstantArrayType>(AT))
3839 PType = PVDecl->getType();
3840 } else if (PType->isFunctionType())
3841 PType = PVDecl->getType();
3842 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003843 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003844 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003845 }
John McCall351762c2011-02-07 10:33:21 +00003846
3847 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003848}
3849
David Chisnall50e4eba2010-12-30 14:05:53 +00003850void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3851 std::string& S) {
3852 // Encode result type.
3853 getObjCEncodingForType(Decl->getResultType(), S);
3854 CharUnits ParmOffset;
3855 // Compute size of all parameters.
3856 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3857 E = Decl->param_end(); PI != E; ++PI) {
3858 QualType PType = (*PI)->getType();
3859 CharUnits sz = getObjCEncodingTypeSize(PType);
3860 assert (sz.isPositive() &&
3861 "getObjCEncodingForMethodDecl - Incomplete param type");
3862 ParmOffset += sz;
3863 }
3864 S += charUnitsToString(ParmOffset);
3865 ParmOffset = CharUnits::Zero();
3866
3867 // Argument types.
3868 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3869 E = Decl->param_end(); PI != E; ++PI) {
3870 ParmVarDecl *PVDecl = *PI;
3871 QualType PType = PVDecl->getOriginalType();
3872 if (const ArrayType *AT =
3873 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3874 // Use array's original type only if it has known number of
3875 // elements.
3876 if (!isa<ConstantArrayType>(AT))
3877 PType = PVDecl->getType();
3878 } else if (PType->isFunctionType())
3879 PType = PVDecl->getType();
3880 getObjCEncodingForType(PType, S);
3881 S += charUnitsToString(ParmOffset);
3882 ParmOffset += getObjCEncodingTypeSize(PType);
3883 }
3884}
3885
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003886/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003887/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003888void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003889 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003890 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003891 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003892 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003893 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003894 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003895 // Compute size of all parameters.
3896 // Start with computing size of a pointer in number of bytes.
3897 // FIXME: There might(should) be a better way of doing this computation!
3898 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003899 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003900 // The first two arguments (self and _cmd) are pointers; account for
3901 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003902 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003903 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003904 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003905 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003906 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003907 assert (sz.isPositive() &&
3908 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003909 ParmOffset += sz;
3910 }
Ken Dyck40775002010-01-11 17:06:35 +00003911 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003912 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003913 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003914
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003915 // Argument types.
3916 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003917 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003918 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003919 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003920 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003921 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003922 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3923 // Use array's original type only if it has known number of
3924 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003925 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003926 PType = PVDecl->getType();
3927 } else if (PType->isFunctionType())
3928 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003929 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003930 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003931 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003932 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003933 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003934 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003935 }
3936}
3937
Daniel Dunbar4932b362008-08-28 04:38:10 +00003938/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003939/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003940/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3941/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003942/// Property attributes are stored as a comma-delimited C string. The simple
3943/// attributes readonly and bycopy are encoded as single characters. The
3944/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3945/// encoded as single characters, followed by an identifier. Property types
3946/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003947/// these attributes are defined by the following enumeration:
3948/// @code
3949/// enum PropertyAttributes {
3950/// kPropertyReadOnly = 'R', // property is read-only.
3951/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3952/// kPropertyByref = '&', // property is a reference to the value last assigned
3953/// kPropertyDynamic = 'D', // property is dynamic
3954/// kPropertyGetter = 'G', // followed by getter selector name
3955/// kPropertySetter = 'S', // followed by setter selector name
3956/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3957/// kPropertyType = 't' // followed by old-style type encoding.
3958/// kPropertyWeak = 'W' // 'weak' property
3959/// kPropertyStrong = 'P' // property GC'able
3960/// kPropertyNonAtomic = 'N' // property non-atomic
3961/// };
3962/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003963void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003964 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003965 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003966 // Collect information from the property implementation decl(s).
3967 bool Dynamic = false;
3968 ObjCPropertyImplDecl *SynthesizePID = 0;
3969
3970 // FIXME: Duplicated code due to poor abstraction.
3971 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003972 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003973 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3974 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003975 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003976 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003977 ObjCPropertyImplDecl *PID = *i;
3978 if (PID->getPropertyDecl() == PD) {
3979 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3980 Dynamic = true;
3981 } else {
3982 SynthesizePID = PID;
3983 }
3984 }
3985 }
3986 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003987 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003988 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003989 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003990 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003991 ObjCPropertyImplDecl *PID = *i;
3992 if (PID->getPropertyDecl() == PD) {
3993 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3994 Dynamic = true;
3995 } else {
3996 SynthesizePID = PID;
3997 }
3998 }
Mike Stump11289f42009-09-09 15:08:12 +00003999 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004000 }
4001 }
4002
4003 // FIXME: This is not very efficient.
4004 S = "T";
4005
4006 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004007 // GCC has some special rules regarding encoding of properties which
4008 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004009 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004010 true /* outermost type */,
4011 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004012
4013 if (PD->isReadOnly()) {
4014 S += ",R";
4015 } else {
4016 switch (PD->getSetterKind()) {
4017 case ObjCPropertyDecl::Assign: break;
4018 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004019 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004020 }
4021 }
4022
4023 // It really isn't clear at all what this means, since properties
4024 // are "dynamic by default".
4025 if (Dynamic)
4026 S += ",D";
4027
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004028 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4029 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004030
Daniel Dunbar4932b362008-08-28 04:38:10 +00004031 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4032 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004033 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004034 }
4035
4036 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4037 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004038 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004039 }
4040
4041 if (SynthesizePID) {
4042 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4043 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004044 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004045 }
4046
4047 // FIXME: OBJCGC: weak & strong
4048}
4049
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004050/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004051/// Another legacy compatibility encoding: 32-bit longs are encoded as
4052/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004053/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4054///
4055void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004056 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004057 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004058 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004059 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004060 else
Jay Foad39c79802011-01-12 09:06:06 +00004061 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004062 PointeeTy = IntTy;
4063 }
4064 }
4065}
4066
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004067void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004068 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004069 // We follow the behavior of gcc, expanding structures which are
4070 // directly pointed to, and expanding embedded structures. Note that
4071 // these rules are sufficient to prevent recursive encoding of the
4072 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004073 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004074 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004075}
4076
David Chisnallb190a2c2010-06-04 01:10:52 +00004077static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4078 switch (T->getAs<BuiltinType>()->getKind()) {
4079 default: assert(0 && "Unhandled builtin type kind");
4080 case BuiltinType::Void: return 'v';
4081 case BuiltinType::Bool: return 'B';
4082 case BuiltinType::Char_U:
4083 case BuiltinType::UChar: return 'C';
4084 case BuiltinType::UShort: return 'S';
4085 case BuiltinType::UInt: return 'I';
4086 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004087 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004088 case BuiltinType::UInt128: return 'T';
4089 case BuiltinType::ULongLong: return 'Q';
4090 case BuiltinType::Char_S:
4091 case BuiltinType::SChar: return 'c';
4092 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004093 case BuiltinType::WChar_S:
4094 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004095 case BuiltinType::Int: return 'i';
4096 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004097 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004098 case BuiltinType::LongLong: return 'q';
4099 case BuiltinType::Int128: return 't';
4100 case BuiltinType::Float: return 'f';
4101 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004102 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004103 }
4104}
4105
Jay Foad39c79802011-01-12 09:06:06 +00004106static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004107 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004108 const Expr *E = FD->getBitWidth();
4109 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004110 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004111 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4112 // The GNU runtime requires more information; bitfields are encoded as b,
4113 // then the offset (in bits) of the first element, then the type of the
4114 // bitfield, then the size in bits. For example, in this structure:
4115 //
4116 // struct
4117 // {
4118 // int integer;
4119 // int flags:2;
4120 // };
4121 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4122 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4123 // information is not especially sensible, but we're stuck with it for
4124 // compatibility with GCC, although providing it breaks anything that
4125 // actually uses runtime introspection and wants to work on both runtimes...
4126 if (!Ctx->getLangOptions().NeXTRuntime) {
4127 const RecordDecl *RD = FD->getParent();
4128 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4129 // FIXME: This same linear search is also used in ExprConstant - it might
4130 // be better if the FieldDecl stored its offset. We'd be increasing the
4131 // size of the object slightly, but saving some time every time it is used.
4132 unsigned i = 0;
4133 for (RecordDecl::field_iterator Field = RD->field_begin(),
4134 FieldEnd = RD->field_end();
4135 Field != FieldEnd; (void)++Field, ++i) {
4136 if (*Field == FD)
4137 break;
4138 }
4139 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004140 if (T->isEnumeralType())
4141 S += 'i';
4142 else
Jay Foad39c79802011-01-12 09:06:06 +00004143 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004144 }
4145 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004146 S += llvm::utostr(N);
4147}
4148
Daniel Dunbar07d07852009-10-18 21:17:35 +00004149// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004150void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4151 bool ExpandPointedToStructures,
4152 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004153 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004154 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00004155 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004156 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004157 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004158 return EncodeBitField(this, S, T, FD);
4159 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004160 return;
4161 }
Mike Stump11289f42009-09-09 15:08:12 +00004162
John McCall9dd450b2009-09-21 23:43:11 +00004163 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004164 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004165 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004166 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004167 return;
4168 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004169
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004170 // encoding for pointer or r3eference types.
4171 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004172 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004173 if (PT->isObjCSelType()) {
4174 S += ':';
4175 return;
4176 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004177 PointeeTy = PT->getPointeeType();
4178 }
4179 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4180 PointeeTy = RT->getPointeeType();
4181 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004182 bool isReadOnly = false;
4183 // For historical/compatibility reasons, the read-only qualifier of the
4184 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4185 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004186 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004187 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004188 if (OutermostType && T.isConstQualified()) {
4189 isReadOnly = true;
4190 S += 'r';
4191 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004192 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004193 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004194 while (P->getAs<PointerType>())
4195 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004196 if (P.isConstQualified()) {
4197 isReadOnly = true;
4198 S += 'r';
4199 }
4200 }
4201 if (isReadOnly) {
4202 // Another legacy compatibility encoding. Some ObjC qualifier and type
4203 // combinations need to be rearranged.
4204 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004205 if (llvm::StringRef(S).endswith("nr"))
4206 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004207 }
Mike Stump11289f42009-09-09 15:08:12 +00004208
Anders Carlssond8499822007-10-29 05:01:08 +00004209 if (PointeeTy->isCharType()) {
4210 // char pointer types should be encoded as '*' unless it is a
4211 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004212 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004213 S += '*';
4214 return;
4215 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004216 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004217 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4218 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4219 S += '#';
4220 return;
4221 }
4222 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4223 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4224 S += '@';
4225 return;
4226 }
4227 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004228 }
Anders Carlssond8499822007-10-29 05:01:08 +00004229 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004230 getLegacyIntegralTypeEncoding(PointeeTy);
4231
Mike Stump11289f42009-09-09 15:08:12 +00004232 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004233 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004234 return;
4235 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004236
Chris Lattnere7cabb92009-07-13 00:10:46 +00004237 if (const ArrayType *AT =
4238 // Ignore type qualifiers etc.
4239 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004240 if (isa<IncompleteArrayType>(AT)) {
4241 // Incomplete arrays are encoded as a pointer to the array element.
4242 S += '^';
4243
Mike Stump11289f42009-09-09 15:08:12 +00004244 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004245 false, ExpandStructures, FD);
4246 } else {
4247 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004248
Anders Carlssond05f44b2009-02-22 01:38:57 +00004249 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4250 S += llvm::utostr(CAT->getSize().getZExtValue());
4251 else {
4252 //Variable length arrays are encoded as a regular array with 0 elements.
4253 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4254 S += '0';
4255 }
Mike Stump11289f42009-09-09 15:08:12 +00004256
4257 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004258 false, ExpandStructures, FD);
4259 S += ']';
4260 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004261 return;
4262 }
Mike Stump11289f42009-09-09 15:08:12 +00004263
John McCall9dd450b2009-09-21 23:43:11 +00004264 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004265 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004266 return;
4267 }
Mike Stump11289f42009-09-09 15:08:12 +00004268
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004269 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004270 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004271 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004272 // Anonymous structures print as '?'
4273 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4274 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004275 if (ClassTemplateSpecializationDecl *Spec
4276 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4277 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4278 std::string TemplateArgsStr
4279 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004280 TemplateArgs.data(),
4281 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004282 (*this).PrintingPolicy);
4283
4284 S += TemplateArgsStr;
4285 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004286 } else {
4287 S += '?';
4288 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004289 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004290 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004291 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4292 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004293 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004294 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004295 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004296 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004297 S += '"';
4298 }
Mike Stump11289f42009-09-09 15:08:12 +00004299
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004300 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004301 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004302 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004303 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004304 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004305 QualType qt = Field->getType();
4306 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004307 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004308 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004309 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004310 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004311 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004312 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004313 return;
4314 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004315
Chris Lattnere7cabb92009-07-13 00:10:46 +00004316 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004317 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004318 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004319 else
4320 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004321 return;
4322 }
Mike Stump11289f42009-09-09 15:08:12 +00004323
Chris Lattnere7cabb92009-07-13 00:10:46 +00004324 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004325 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004326 return;
4327 }
Mike Stump11289f42009-09-09 15:08:12 +00004328
John McCall8b07ec22010-05-15 11:32:37 +00004329 // Ignore protocol qualifiers when mangling at this level.
4330 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4331 T = OT->getBaseType();
4332
John McCall8ccfcb52009-09-24 19:53:00 +00004333 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004334 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004335 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004336 S += '{';
4337 const IdentifierInfo *II = OI->getIdentifier();
4338 S += II->getName();
4339 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004340 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4341 DeepCollectObjCIvars(OI, true, Ivars);
4342 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4343 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4344 if (Field->isBitField())
4345 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004346 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004347 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004348 }
4349 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004350 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004351 }
Mike Stump11289f42009-09-09 15:08:12 +00004352
John McCall9dd450b2009-09-21 23:43:11 +00004353 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004354 if (OPT->isObjCIdType()) {
4355 S += '@';
4356 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004357 }
Mike Stump11289f42009-09-09 15:08:12 +00004358
Steve Narofff0c86112009-10-28 22:03:49 +00004359 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4360 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4361 // Since this is a binary compatibility issue, need to consult with runtime
4362 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004363 S += '#';
4364 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004365 }
Mike Stump11289f42009-09-09 15:08:12 +00004366
Chris Lattnere7cabb92009-07-13 00:10:46 +00004367 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004368 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004369 ExpandPointedToStructures,
4370 ExpandStructures, FD);
4371 if (FD || EncodingProperty) {
4372 // Note that we do extended encoding of protocol qualifer list
4373 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004374 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004375 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4376 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004377 S += '<';
4378 S += (*I)->getNameAsString();
4379 S += '>';
4380 }
4381 S += '"';
4382 }
4383 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004384 }
Mike Stump11289f42009-09-09 15:08:12 +00004385
Chris Lattnere7cabb92009-07-13 00:10:46 +00004386 QualType PointeeTy = OPT->getPointeeType();
4387 if (!EncodingProperty &&
4388 isa<TypedefType>(PointeeTy.getTypePtr())) {
4389 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004390 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004391 // {...};
4392 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004393 getObjCEncodingForTypeImpl(PointeeTy, S,
4394 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004395 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004396 return;
4397 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004398
4399 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004400 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004401 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004402 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004403 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4404 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004405 S += '<';
4406 S += (*I)->getNameAsString();
4407 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004408 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004409 S += '"';
4410 }
4411 return;
4412 }
Mike Stump11289f42009-09-09 15:08:12 +00004413
John McCalla9e6e8d2010-05-17 23:56:34 +00004414 // gcc just blithely ignores member pointers.
4415 // TODO: maybe there should be a mangling for these
4416 if (T->getAs<MemberPointerType>())
4417 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004418
4419 if (T->isVectorType()) {
4420 // This matches gcc's encoding, even though technically it is
4421 // insufficient.
4422 // FIXME. We should do a better job than gcc.
4423 return;
4424 }
4425
Chris Lattnere7cabb92009-07-13 00:10:46 +00004426 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004427}
4428
Mike Stump11289f42009-09-09 15:08:12 +00004429void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004430 std::string& S) const {
4431 if (QT & Decl::OBJC_TQ_In)
4432 S += 'n';
4433 if (QT & Decl::OBJC_TQ_Inout)
4434 S += 'N';
4435 if (QT & Decl::OBJC_TQ_Out)
4436 S += 'o';
4437 if (QT & Decl::OBJC_TQ_Bycopy)
4438 S += 'O';
4439 if (QT & Decl::OBJC_TQ_Byref)
4440 S += 'R';
4441 if (QT & Decl::OBJC_TQ_Oneway)
4442 S += 'V';
4443}
4444
Chris Lattnere7cabb92009-07-13 00:10:46 +00004445void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004446 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004447
Anders Carlsson87c149b2007-10-11 01:00:40 +00004448 BuiltinVaListType = T;
4449}
4450
Chris Lattnere7cabb92009-07-13 00:10:46 +00004451void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004452 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004453}
4454
Chris Lattnere7cabb92009-07-13 00:10:46 +00004455void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004456 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004457}
4458
Chris Lattnere7cabb92009-07-13 00:10:46 +00004459void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004460 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004461}
4462
Chris Lattnere7cabb92009-07-13 00:10:46 +00004463void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004464 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004465}
4466
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004467void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004468 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004469 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004470
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004471 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004472}
4473
John McCalld28ae272009-12-02 08:04:21 +00004474/// \brief Retrieve the template name that corresponds to a non-empty
4475/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004476TemplateName
4477ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4478 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004479 unsigned size = End - Begin;
4480 assert(size > 1 && "set is not overloaded!");
4481
4482 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4483 size * sizeof(FunctionTemplateDecl*));
4484 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4485
4486 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004487 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004488 NamedDecl *D = *I;
4489 assert(isa<FunctionTemplateDecl>(D) ||
4490 (isa<UsingShadowDecl>(D) &&
4491 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4492 *Storage++ = D;
4493 }
4494
4495 return TemplateName(OT);
4496}
4497
Douglas Gregordc572a32009-03-30 22:58:21 +00004498/// \brief Retrieve the template name that represents a qualified
4499/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004500TemplateName
4501ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4502 bool TemplateKeyword,
4503 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004504 assert(NNS && "Missing nested-name-specifier in qualified template name");
4505
Douglas Gregorc42075a2010-02-04 18:10:26 +00004506 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004507 llvm::FoldingSetNodeID ID;
4508 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4509
4510 void *InsertPos = 0;
4511 QualifiedTemplateName *QTN =
4512 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4513 if (!QTN) {
4514 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4515 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4516 }
4517
4518 return TemplateName(QTN);
4519}
4520
4521/// \brief Retrieve the template name that represents a dependent
4522/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004523TemplateName
4524ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4525 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004526 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004527 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004528
4529 llvm::FoldingSetNodeID ID;
4530 DependentTemplateName::Profile(ID, NNS, Name);
4531
4532 void *InsertPos = 0;
4533 DependentTemplateName *QTN =
4534 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4535
4536 if (QTN)
4537 return TemplateName(QTN);
4538
4539 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4540 if (CanonNNS == NNS) {
4541 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4542 } else {
4543 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4544 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004545 DependentTemplateName *CheckQTN =
4546 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4547 assert(!CheckQTN && "Dependent type name canonicalization broken");
4548 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004549 }
4550
4551 DependentTemplateNames.InsertNode(QTN, InsertPos);
4552 return TemplateName(QTN);
4553}
4554
Douglas Gregor71395fa2009-11-04 00:56:37 +00004555/// \brief Retrieve the template name that represents a dependent
4556/// template name such as \c MetaFun::template operator+.
4557TemplateName
4558ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004559 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004560 assert((!NNS || NNS->isDependent()) &&
4561 "Nested name specifier must be dependent");
4562
4563 llvm::FoldingSetNodeID ID;
4564 DependentTemplateName::Profile(ID, NNS, Operator);
4565
4566 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004567 DependentTemplateName *QTN
4568 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004569
4570 if (QTN)
4571 return TemplateName(QTN);
4572
4573 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4574 if (CanonNNS == NNS) {
4575 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4576 } else {
4577 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4578 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004579
4580 DependentTemplateName *CheckQTN
4581 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4582 assert(!CheckQTN && "Dependent template name canonicalization broken");
4583 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004584 }
4585
4586 DependentTemplateNames.InsertNode(QTN, InsertPos);
4587 return TemplateName(QTN);
4588}
4589
Douglas Gregor5590be02011-01-15 06:45:20 +00004590TemplateName
4591ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4592 const TemplateArgument &ArgPack) const {
4593 ASTContext &Self = const_cast<ASTContext &>(*this);
4594 llvm::FoldingSetNodeID ID;
4595 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4596
4597 void *InsertPos = 0;
4598 SubstTemplateTemplateParmPackStorage *Subst
4599 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4600
4601 if (!Subst) {
4602 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4603 ArgPack.pack_size(),
4604 ArgPack.pack_begin());
4605 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4606 }
4607
4608 return TemplateName(Subst);
4609}
4610
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004611/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004612/// TargetInfo, produce the corresponding type. The unsigned @p Type
4613/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004614CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004615 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004616 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004617 case TargetInfo::SignedShort: return ShortTy;
4618 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4619 case TargetInfo::SignedInt: return IntTy;
4620 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4621 case TargetInfo::SignedLong: return LongTy;
4622 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4623 case TargetInfo::SignedLongLong: return LongLongTy;
4624 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4625 }
4626
4627 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004628 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004629}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004630
4631//===----------------------------------------------------------------------===//
4632// Type Predicates.
4633//===----------------------------------------------------------------------===//
4634
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004635/// isObjCNSObjectType - Return true if this is an NSObject object using
4636/// NSObject attribute on a c-style pointer type.
4637/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004638/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004639///
4640bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCall424cec92011-01-19 06:33:43 +00004641 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Richard Smithdda56e42011-04-15 14:24:37 +00004642 if (TypedefNameDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004643 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004644 return true;
4645 }
Mike Stump11289f42009-09-09 15:08:12 +00004646 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004647}
4648
Fariborz Jahanian96207692009-02-18 21:49:28 +00004649/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4650/// garbage collection attribute.
4651///
John McCall553d45a2011-01-12 00:34:59 +00004652Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4653 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4654 return Qualifiers::GCNone;
4655
4656 assert(getLangOptions().ObjC1);
4657 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4658
4659 // Default behaviour under objective-C's gc is for ObjC pointers
4660 // (or pointers to them) be treated as though they were declared
4661 // as __strong.
4662 if (GCAttrs == Qualifiers::GCNone) {
4663 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4664 return Qualifiers::Strong;
4665 else if (Ty->isPointerType())
4666 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4667 } else {
4668 // It's not valid to set GC attributes on anything that isn't a
4669 // pointer.
4670#ifndef NDEBUG
4671 QualType CT = Ty->getCanonicalTypeInternal();
4672 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4673 CT = AT->getElementType();
4674 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4675#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004676 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004677 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004678}
4679
Chris Lattner49af6a42008-04-07 06:51:04 +00004680//===----------------------------------------------------------------------===//
4681// Type Compatibility Testing
4682//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004683
Mike Stump11289f42009-09-09 15:08:12 +00004684/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004685/// compatible.
4686static bool areCompatVectorTypes(const VectorType *LHS,
4687 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004688 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004689 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004690 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004691}
4692
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004693bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4694 QualType SecondVec) {
4695 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4696 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4697
4698 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4699 return true;
4700
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004701 // Treat Neon vector types and most AltiVec vector types as if they are the
4702 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004703 const VectorType *First = FirstVec->getAs<VectorType>();
4704 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004705 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004706 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004707 First->getVectorKind() != VectorType::AltiVecPixel &&
4708 First->getVectorKind() != VectorType::AltiVecBool &&
4709 Second->getVectorKind() != VectorType::AltiVecPixel &&
4710 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004711 return true;
4712
4713 return false;
4714}
4715
Steve Naroff8e6aee52009-07-23 01:01:38 +00004716//===----------------------------------------------------------------------===//
4717// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4718//===----------------------------------------------------------------------===//
4719
4720/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4721/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004722bool
4723ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4724 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004725 if (lProto == rProto)
4726 return true;
4727 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4728 E = rProto->protocol_end(); PI != E; ++PI)
4729 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4730 return true;
4731 return false;
4732}
4733
Steve Naroff8e6aee52009-07-23 01:01:38 +00004734/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4735/// return true if lhs's protocols conform to rhs's protocol; false
4736/// otherwise.
4737bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4738 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4739 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4740 return false;
4741}
4742
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004743/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4744/// Class<p1, ...>.
4745bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4746 QualType rhs) {
4747 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4748 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4749 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4750
4751 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4752 E = lhsQID->qual_end(); I != E; ++I) {
4753 bool match = false;
4754 ObjCProtocolDecl *lhsProto = *I;
4755 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4756 E = rhsOPT->qual_end(); J != E; ++J) {
4757 ObjCProtocolDecl *rhsProto = *J;
4758 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4759 match = true;
4760 break;
4761 }
4762 }
4763 if (!match)
4764 return false;
4765 }
4766 return true;
4767}
4768
Steve Naroff8e6aee52009-07-23 01:01:38 +00004769/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4770/// ObjCQualifiedIDType.
4771bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4772 bool compare) {
4773 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004774 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004775 lhs->isObjCIdType() || lhs->isObjCClassType())
4776 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004777 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004778 rhs->isObjCIdType() || rhs->isObjCClassType())
4779 return true;
4780
4781 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004782 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004783
Steve Naroff8e6aee52009-07-23 01:01:38 +00004784 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004785
Steve Naroff8e6aee52009-07-23 01:01:38 +00004786 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004787 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004788 // make sure we check the class hierarchy.
4789 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4790 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4791 E = lhsQID->qual_end(); I != E; ++I) {
4792 // when comparing an id<P> on lhs with a static type on rhs,
4793 // see if static class implements all of id's protocols, directly or
4794 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004795 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004796 return false;
4797 }
4798 }
4799 // If there are no qualifiers and no interface, we have an 'id'.
4800 return true;
4801 }
Mike Stump11289f42009-09-09 15:08:12 +00004802 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004803 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4804 E = lhsQID->qual_end(); I != E; ++I) {
4805 ObjCProtocolDecl *lhsProto = *I;
4806 bool match = false;
4807
4808 // when comparing an id<P> on lhs with a static type on rhs,
4809 // see if static class implements all of id's protocols, directly or
4810 // through its super class and categories.
4811 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4812 E = rhsOPT->qual_end(); J != E; ++J) {
4813 ObjCProtocolDecl *rhsProto = *J;
4814 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4815 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4816 match = true;
4817 break;
4818 }
4819 }
Mike Stump11289f42009-09-09 15:08:12 +00004820 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004821 // make sure we check the class hierarchy.
4822 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4823 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4824 E = lhsQID->qual_end(); I != E; ++I) {
4825 // when comparing an id<P> on lhs with a static type on rhs,
4826 // see if static class implements all of id's protocols, directly or
4827 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004828 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004829 match = true;
4830 break;
4831 }
4832 }
4833 }
4834 if (!match)
4835 return false;
4836 }
Mike Stump11289f42009-09-09 15:08:12 +00004837
Steve Naroff8e6aee52009-07-23 01:01:38 +00004838 return true;
4839 }
Mike Stump11289f42009-09-09 15:08:12 +00004840
Steve Naroff8e6aee52009-07-23 01:01:38 +00004841 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4842 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4843
Mike Stump11289f42009-09-09 15:08:12 +00004844 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004845 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004846 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004847 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4848 E = lhsOPT->qual_end(); I != E; ++I) {
4849 ObjCProtocolDecl *lhsProto = *I;
4850 bool match = false;
4851
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004852 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004853 // see if static class implements all of id's protocols, directly or
4854 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004855 // First, lhs protocols in the qualifier list must be found, direct
4856 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004857 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4858 E = rhsQID->qual_end(); J != E; ++J) {
4859 ObjCProtocolDecl *rhsProto = *J;
4860 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4861 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4862 match = true;
4863 break;
4864 }
4865 }
4866 if (!match)
4867 return false;
4868 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004869
4870 // Static class's protocols, or its super class or category protocols
4871 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4872 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4873 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4874 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4875 // This is rather dubious but matches gcc's behavior. If lhs has
4876 // no type qualifier and its class has no static protocol(s)
4877 // assume that it is mismatch.
4878 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4879 return false;
4880 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4881 LHSInheritedProtocols.begin(),
4882 E = LHSInheritedProtocols.end(); I != E; ++I) {
4883 bool match = false;
4884 ObjCProtocolDecl *lhsProto = (*I);
4885 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4886 E = rhsQID->qual_end(); J != E; ++J) {
4887 ObjCProtocolDecl *rhsProto = *J;
4888 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4889 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4890 match = true;
4891 break;
4892 }
4893 }
4894 if (!match)
4895 return false;
4896 }
4897 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004898 return true;
4899 }
4900 return false;
4901}
4902
Eli Friedman47f77112008-08-22 00:56:42 +00004903/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004904/// compatible for assignment from RHS to LHS. This handles validation of any
4905/// protocol qualifiers on the LHS or RHS.
4906///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004907bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4908 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004909 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4910 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4911
Steve Naroff1329fa02009-07-15 18:40:39 +00004912 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004913 if (LHS->isObjCUnqualifiedIdOrClass() ||
4914 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004915 return true;
4916
John McCall8b07ec22010-05-15 11:32:37 +00004917 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004918 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4919 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004920 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004921
4922 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4923 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4924 QualType(RHSOPT,0));
4925
John McCall8b07ec22010-05-15 11:32:37 +00004926 // If we have 2 user-defined types, fall into that path.
4927 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004928 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004929
Steve Naroff8e6aee52009-07-23 01:01:38 +00004930 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004931}
4932
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004933/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00004934/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004935/// arguments in block literals. When passed as arguments, passing 'A*' where
4936/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4937/// not OK. For the return type, the opposite is not OK.
4938bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4939 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004940 const ObjCObjectPointerType *RHSOPT,
4941 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004942 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004943 return true;
4944
4945 if (LHSOPT->isObjCBuiltinType()) {
4946 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4947 }
4948
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004949 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004950 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4951 QualType(RHSOPT,0),
4952 false);
4953
4954 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4955 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4956 if (LHS && RHS) { // We have 2 user-defined types.
4957 if (LHS != RHS) {
4958 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004959 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004960 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004961 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004962 }
4963 else
4964 return true;
4965 }
4966 return false;
4967}
4968
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004969/// getIntersectionOfProtocols - This routine finds the intersection of set
4970/// of protocols inherited from two distinct objective-c pointer objects.
4971/// It is used to build composite qualifier list of the composite type of
4972/// the conditional expression involving two objective-c pointer objects.
4973static
4974void getIntersectionOfProtocols(ASTContext &Context,
4975 const ObjCObjectPointerType *LHSOPT,
4976 const ObjCObjectPointerType *RHSOPT,
4977 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4978
John McCall8b07ec22010-05-15 11:32:37 +00004979 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4980 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4981 assert(LHS->getInterface() && "LHS must have an interface base");
4982 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004983
4984 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4985 unsigned LHSNumProtocols = LHS->getNumProtocols();
4986 if (LHSNumProtocols > 0)
4987 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4988 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004989 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004990 Context.CollectInheritedProtocols(LHS->getInterface(),
4991 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004992 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4993 LHSInheritedProtocols.end());
4994 }
4995
4996 unsigned RHSNumProtocols = RHS->getNumProtocols();
4997 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004998 ObjCProtocolDecl **RHSProtocols =
4999 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005000 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5001 if (InheritedProtocolSet.count(RHSProtocols[i]))
5002 IntersectionOfProtocols.push_back(RHSProtocols[i]);
5003 }
5004 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005005 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005006 Context.CollectInheritedProtocols(RHS->getInterface(),
5007 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005008 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5009 RHSInheritedProtocols.begin(),
5010 E = RHSInheritedProtocols.end(); I != E; ++I)
5011 if (InheritedProtocolSet.count((*I)))
5012 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005013 }
5014}
5015
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005016/// areCommonBaseCompatible - Returns common base class of the two classes if
5017/// one found. Note that this is O'2 algorithm. But it will be called as the
5018/// last type comparison in a ?-exp of ObjC pointer types before a
5019/// warning is issued. So, its invokation is extremely rare.
5020QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005021 const ObjCObjectPointerType *Lptr,
5022 const ObjCObjectPointerType *Rptr) {
5023 const ObjCObjectType *LHS = Lptr->getObjectType();
5024 const ObjCObjectType *RHS = Rptr->getObjectType();
5025 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5026 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005027 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005028 return QualType();
5029
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005030 do {
John McCall8b07ec22010-05-15 11:32:37 +00005031 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005032 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00005033 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
5034 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5035
5036 QualType Result = QualType(LHS, 0);
5037 if (!Protocols.empty())
5038 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5039 Result = getObjCObjectPointerType(Result);
5040 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005041 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005042 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005043
5044 return QualType();
5045}
5046
John McCall8b07ec22010-05-15 11:32:37 +00005047bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5048 const ObjCObjectType *RHS) {
5049 assert(LHS->getInterface() && "LHS is not an interface type");
5050 assert(RHS->getInterface() && "RHS is not an interface type");
5051
Chris Lattner49af6a42008-04-07 06:51:04 +00005052 // Verify that the base decls are compatible: the RHS must be a subclass of
5053 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005054 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005055 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005056
Chris Lattner49af6a42008-04-07 06:51:04 +00005057 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5058 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005059 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005060 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005061
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005062 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5063 // more detailed analysis is required.
5064 if (RHS->getNumProtocols() == 0) {
5065 // OK, if LHS is a superclass of RHS *and*
5066 // this superclass is assignment compatible with LHS.
5067 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005068 bool IsSuperClass =
5069 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5070 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005071 // OK if conversion of LHS to SuperClass results in narrowing of types
5072 // ; i.e., SuperClass may implement at least one of the protocols
5073 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5074 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5075 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005076 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005077 // If super class has no protocols, it is not a match.
5078 if (SuperClassInheritedProtocols.empty())
5079 return false;
5080
5081 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5082 LHSPE = LHS->qual_end();
5083 LHSPI != LHSPE; LHSPI++) {
5084 bool SuperImplementsProtocol = false;
5085 ObjCProtocolDecl *LHSProto = (*LHSPI);
5086
5087 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5088 SuperClassInheritedProtocols.begin(),
5089 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5090 ObjCProtocolDecl *SuperClassProto = (*I);
5091 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5092 SuperImplementsProtocol = true;
5093 break;
5094 }
5095 }
5096 if (!SuperImplementsProtocol)
5097 return false;
5098 }
5099 return true;
5100 }
5101 return false;
5102 }
Mike Stump11289f42009-09-09 15:08:12 +00005103
John McCall8b07ec22010-05-15 11:32:37 +00005104 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5105 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005106 LHSPI != LHSPE; LHSPI++) {
5107 bool RHSImplementsProtocol = false;
5108
5109 // If the RHS doesn't implement the protocol on the left, the types
5110 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005111 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5112 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005113 RHSPI != RHSPE; RHSPI++) {
5114 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005115 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005116 break;
5117 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005118 }
5119 // FIXME: For better diagnostics, consider passing back the protocol name.
5120 if (!RHSImplementsProtocol)
5121 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005122 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005123 // The RHS implements all protocols listed on the LHS.
5124 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005125}
5126
Steve Naroffb7605152009-02-12 17:52:19 +00005127bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5128 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005129 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5130 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005131
Steve Naroff7cae42b2009-07-10 23:34:53 +00005132 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005133 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005134
5135 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5136 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005137}
5138
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005139bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5140 return canAssignObjCInterfaces(
5141 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5142 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5143}
5144
Mike Stump11289f42009-09-09 15:08:12 +00005145/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005146/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005147/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005148/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005149bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5150 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005151 if (getLangOptions().CPlusPlus)
5152 return hasSameType(LHS, RHS);
5153
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005154 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005155}
5156
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005157bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5158 return !mergeTypes(LHS, RHS, true).isNull();
5159}
5160
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005161/// mergeTransparentUnionType - if T is a transparent union type and a member
5162/// of T is compatible with SubType, return the merged type, else return
5163/// QualType()
5164QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5165 bool OfBlockPointer,
5166 bool Unqualified) {
5167 if (const RecordType *UT = T->getAsUnionType()) {
5168 RecordDecl *UD = UT->getDecl();
5169 if (UD->hasAttr<TransparentUnionAttr>()) {
5170 for (RecordDecl::field_iterator it = UD->field_begin(),
5171 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005172 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005173 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5174 if (!MT.isNull())
5175 return MT;
5176 }
5177 }
5178 }
5179
5180 return QualType();
5181}
5182
5183/// mergeFunctionArgumentTypes - merge two types which appear as function
5184/// argument types
5185QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5186 bool OfBlockPointer,
5187 bool Unqualified) {
5188 // GNU extension: two types are compatible if they appear as a function
5189 // argument, one of the types is a transparent union type and the other
5190 // type is compatible with a union member
5191 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5192 Unqualified);
5193 if (!lmerge.isNull())
5194 return lmerge;
5195
5196 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5197 Unqualified);
5198 if (!rmerge.isNull())
5199 return rmerge;
5200
5201 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5202}
5203
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005204QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005205 bool OfBlockPointer,
5206 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005207 const FunctionType *lbase = lhs->getAs<FunctionType>();
5208 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005209 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5210 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005211 bool allLTypes = true;
5212 bool allRTypes = true;
5213
5214 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005215 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005216 if (OfBlockPointer) {
5217 QualType RHS = rbase->getResultType();
5218 QualType LHS = lbase->getResultType();
5219 bool UnqualifiedResult = Unqualified;
5220 if (!UnqualifiedResult)
5221 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005222 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005223 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005224 else
John McCall8c6b56f2010-12-15 01:06:38 +00005225 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5226 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005227 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005228
5229 if (Unqualified)
5230 retType = retType.getUnqualifiedType();
5231
5232 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5233 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5234 if (Unqualified) {
5235 LRetType = LRetType.getUnqualifiedType();
5236 RRetType = RRetType.getUnqualifiedType();
5237 }
5238
5239 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005240 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005241 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005242 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005243
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005244 // FIXME: double check this
5245 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5246 // rbase->getRegParmAttr() != 0 &&
5247 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005248 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5249 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005250
Douglas Gregor8c940862010-01-18 17:14:39 +00005251 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005252 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005253 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005254
John McCall8c6b56f2010-12-15 01:06:38 +00005255 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005256 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5257 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005258 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5259 return QualType();
5260
5261 // It's noreturn if either type is.
5262 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5263 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5264 if (NoReturn != lbaseInfo.getNoReturn())
5265 allLTypes = false;
5266 if (NoReturn != rbaseInfo.getNoReturn())
5267 allRTypes = false;
5268
5269 FunctionType::ExtInfo einfo(NoReturn,
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005270 lbaseInfo.getHasRegParm(),
John McCall8c6b56f2010-12-15 01:06:38 +00005271 lbaseInfo.getRegParm(),
5272 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00005273
Eli Friedman47f77112008-08-22 00:56:42 +00005274 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005275 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5276 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005277 unsigned lproto_nargs = lproto->getNumArgs();
5278 unsigned rproto_nargs = rproto->getNumArgs();
5279
5280 // Compatible functions must have the same number of arguments
5281 if (lproto_nargs != rproto_nargs)
5282 return QualType();
5283
5284 // Variadic and non-variadic functions aren't compatible
5285 if (lproto->isVariadic() != rproto->isVariadic())
5286 return QualType();
5287
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005288 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5289 return QualType();
5290
Eli Friedman47f77112008-08-22 00:56:42 +00005291 // Check argument compatibility
5292 llvm::SmallVector<QualType, 10> types;
5293 for (unsigned i = 0; i < lproto_nargs; i++) {
5294 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5295 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005296 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5297 OfBlockPointer,
5298 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005299 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005300
5301 if (Unqualified)
5302 argtype = argtype.getUnqualifiedType();
5303
Eli Friedman47f77112008-08-22 00:56:42 +00005304 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005305 if (Unqualified) {
5306 largtype = largtype.getUnqualifiedType();
5307 rargtype = rargtype.getUnqualifiedType();
5308 }
5309
Chris Lattner465fa322008-10-05 17:34:18 +00005310 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5311 allLTypes = false;
5312 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5313 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005314 }
5315 if (allLTypes) return lhs;
5316 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005317
5318 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5319 EPI.ExtInfo = einfo;
5320 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005321 }
5322
5323 if (lproto) allRTypes = false;
5324 if (rproto) allLTypes = false;
5325
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005326 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005327 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005328 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005329 if (proto->isVariadic()) return QualType();
5330 // Check that the types are compatible with the types that
5331 // would result from default argument promotions (C99 6.7.5.3p15).
5332 // The only types actually affected are promotable integer
5333 // types and floats, which would be passed as a different
5334 // type depending on whether the prototype is visible.
5335 unsigned proto_nargs = proto->getNumArgs();
5336 for (unsigned i = 0; i < proto_nargs; ++i) {
5337 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005338
5339 // Look at the promotion type of enum types, since that is the type used
5340 // to pass enum values.
5341 if (const EnumType *Enum = argTy->getAs<EnumType>())
5342 argTy = Enum->getDecl()->getPromotionType();
5343
Eli Friedman47f77112008-08-22 00:56:42 +00005344 if (argTy->isPromotableIntegerType() ||
5345 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5346 return QualType();
5347 }
5348
5349 if (allLTypes) return lhs;
5350 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005351
5352 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5353 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005354 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005355 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005356 }
5357
5358 if (allLTypes) return lhs;
5359 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005360 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005361}
5362
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005363QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005364 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005365 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005366 // C++ [expr]: If an expression initially has the type "reference to T", the
5367 // type is adjusted to "T" prior to any further analysis, the expression
5368 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005369 // expression is an lvalue unless the reference is an rvalue reference and
5370 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005371 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5372 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005373
5374 if (Unqualified) {
5375 LHS = LHS.getUnqualifiedType();
5376 RHS = RHS.getUnqualifiedType();
5377 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005378
Eli Friedman47f77112008-08-22 00:56:42 +00005379 QualType LHSCan = getCanonicalType(LHS),
5380 RHSCan = getCanonicalType(RHS);
5381
5382 // If two types are identical, they are compatible.
5383 if (LHSCan == RHSCan)
5384 return LHS;
5385
John McCall8ccfcb52009-09-24 19:53:00 +00005386 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005387 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5388 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005389 if (LQuals != RQuals) {
5390 // If any of these qualifiers are different, we have a type
5391 // mismatch.
5392 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5393 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5394 return QualType();
5395
5396 // Exactly one GC qualifier difference is allowed: __strong is
5397 // okay if the other type has no GC qualifier but is an Objective
5398 // C object pointer (i.e. implicitly strong by default). We fix
5399 // this by pretending that the unqualified type was actually
5400 // qualified __strong.
5401 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5402 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5403 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5404
5405 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5406 return QualType();
5407
5408 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5409 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5410 }
5411 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5412 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5413 }
Eli Friedman47f77112008-08-22 00:56:42 +00005414 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005415 }
5416
5417 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005418
Eli Friedmandcca6332009-06-01 01:22:52 +00005419 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5420 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005421
Chris Lattnerfd652912008-01-14 05:45:46 +00005422 // We want to consider the two function types to be the same for these
5423 // comparisons, just force one to the other.
5424 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5425 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005426
5427 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005428 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5429 LHSClass = Type::ConstantArray;
5430 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5431 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005432
John McCall8b07ec22010-05-15 11:32:37 +00005433 // ObjCInterfaces are just specialized ObjCObjects.
5434 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5435 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5436
Nate Begemance4d7fc2008-04-18 23:10:10 +00005437 // Canonicalize ExtVector -> Vector.
5438 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5439 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005440
Chris Lattner95554662008-04-07 05:43:21 +00005441 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005442 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005443 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005444 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005445 // Compatibility is based on the underlying type, not the promotion
5446 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005447 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005448 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5449 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005450 }
John McCall9dd450b2009-09-21 23:43:11 +00005451 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005452 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5453 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005454 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005455
Eli Friedman47f77112008-08-22 00:56:42 +00005456 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005457 }
Eli Friedman47f77112008-08-22 00:56:42 +00005458
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005459 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005460 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005461#define TYPE(Class, Base)
5462#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005463#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005464#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5465#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5466#include "clang/AST/TypeNodes.def"
5467 assert(false && "Non-canonical and dependent types shouldn't get here");
5468 return QualType();
5469
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005470 case Type::LValueReference:
5471 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005472 case Type::MemberPointer:
5473 assert(false && "C++ should never be in mergeTypes");
5474 return QualType();
5475
John McCall8b07ec22010-05-15 11:32:37 +00005476 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005477 case Type::IncompleteArray:
5478 case Type::VariableArray:
5479 case Type::FunctionProto:
5480 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005481 assert(false && "Types are eliminated above");
5482 return QualType();
5483
Chris Lattnerfd652912008-01-14 05:45:46 +00005484 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005485 {
5486 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005487 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5488 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005489 if (Unqualified) {
5490 LHSPointee = LHSPointee.getUnqualifiedType();
5491 RHSPointee = RHSPointee.getUnqualifiedType();
5492 }
5493 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5494 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005495 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005496 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005497 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005498 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005499 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005500 return getPointerType(ResultType);
5501 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005502 case Type::BlockPointer:
5503 {
5504 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005505 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5506 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005507 if (Unqualified) {
5508 LHSPointee = LHSPointee.getUnqualifiedType();
5509 RHSPointee = RHSPointee.getUnqualifiedType();
5510 }
5511 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5512 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005513 if (ResultType.isNull()) return QualType();
5514 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5515 return LHS;
5516 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5517 return RHS;
5518 return getBlockPointerType(ResultType);
5519 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005520 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005521 {
5522 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5523 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5524 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5525 return QualType();
5526
5527 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5528 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005529 if (Unqualified) {
5530 LHSElem = LHSElem.getUnqualifiedType();
5531 RHSElem = RHSElem.getUnqualifiedType();
5532 }
5533
5534 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005535 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005536 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5537 return LHS;
5538 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5539 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005540 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5541 ArrayType::ArraySizeModifier(), 0);
5542 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5543 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005544 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5545 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005546 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5547 return LHS;
5548 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5549 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005550 if (LVAT) {
5551 // FIXME: This isn't correct! But tricky to implement because
5552 // the array's size has to be the size of LHS, but the type
5553 // has to be different.
5554 return LHS;
5555 }
5556 if (RVAT) {
5557 // FIXME: This isn't correct! But tricky to implement because
5558 // the array's size has to be the size of RHS, but the type
5559 // has to be different.
5560 return RHS;
5561 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005562 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5563 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005564 return getIncompleteArrayType(ResultType,
5565 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005566 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005567 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005568 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005569 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005570 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005571 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005572 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005573 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005574 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005575 case Type::Complex:
5576 // Distinct complex types are incompatible.
5577 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005578 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005579 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005580 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5581 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005582 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005583 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005584 case Type::ObjCObject: {
5585 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005586 // FIXME: This should be type compatibility, e.g. whether
5587 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005588 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5589 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5590 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005591 return LHS;
5592
Eli Friedman47f77112008-08-22 00:56:42 +00005593 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005594 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005595 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005596 if (OfBlockPointer) {
5597 if (canAssignObjCInterfacesInBlockPointer(
5598 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005599 RHS->getAs<ObjCObjectPointerType>(),
5600 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005601 return LHS;
5602 return QualType();
5603 }
John McCall9dd450b2009-09-21 23:43:11 +00005604 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5605 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005606 return LHS;
5607
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005608 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005609 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005610 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005611
5612 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005613}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005614
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005615/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5616/// 'RHS' attributes and returns the merged version; including for function
5617/// return types.
5618QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5619 QualType LHSCan = getCanonicalType(LHS),
5620 RHSCan = getCanonicalType(RHS);
5621 // If two types are identical, they are compatible.
5622 if (LHSCan == RHSCan)
5623 return LHS;
5624 if (RHSCan->isFunctionType()) {
5625 if (!LHSCan->isFunctionType())
5626 return QualType();
5627 QualType OldReturnType =
5628 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5629 QualType NewReturnType =
5630 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5631 QualType ResReturnType =
5632 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5633 if (ResReturnType.isNull())
5634 return QualType();
5635 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5636 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5637 // In either case, use OldReturnType to build the new function type.
5638 const FunctionType *F = LHS->getAs<FunctionType>();
5639 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005640 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5641 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005642 QualType ResultType
5643 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005644 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005645 return ResultType;
5646 }
5647 }
5648 return QualType();
5649 }
5650
5651 // If the qualifiers are different, the types can still be merged.
5652 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5653 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5654 if (LQuals != RQuals) {
5655 // If any of these qualifiers are different, we have a type mismatch.
5656 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5657 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5658 return QualType();
5659
5660 // Exactly one GC qualifier difference is allowed: __strong is
5661 // okay if the other type has no GC qualifier but is an Objective
5662 // C object pointer (i.e. implicitly strong by default). We fix
5663 // this by pretending that the unqualified type was actually
5664 // qualified __strong.
5665 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5666 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5667 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5668
5669 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5670 return QualType();
5671
5672 if (GC_L == Qualifiers::Strong)
5673 return LHS;
5674 if (GC_R == Qualifiers::Strong)
5675 return RHS;
5676 return QualType();
5677 }
5678
5679 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5680 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5681 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5682 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5683 if (ResQT == LHSBaseQT)
5684 return LHS;
5685 if (ResQT == RHSBaseQT)
5686 return RHS;
5687 }
5688 return QualType();
5689}
5690
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005691//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005692// Integer Predicates
5693//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005694
Jay Foad39c79802011-01-12 09:06:06 +00005695unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005696 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005697 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005698 if (T->isBooleanType())
5699 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005700 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005701 return (unsigned)getTypeSize(T);
5702}
5703
5704QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005705 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005706
5707 // Turn <4 x signed int> -> <4 x unsigned int>
5708 if (const VectorType *VTy = T->getAs<VectorType>())
5709 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005710 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005711
5712 // For enums, we return the unsigned version of the base type.
5713 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005714 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005715
5716 const BuiltinType *BTy = T->getAs<BuiltinType>();
5717 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005718 switch (BTy->getKind()) {
5719 case BuiltinType::Char_S:
5720 case BuiltinType::SChar:
5721 return UnsignedCharTy;
5722 case BuiltinType::Short:
5723 return UnsignedShortTy;
5724 case BuiltinType::Int:
5725 return UnsignedIntTy;
5726 case BuiltinType::Long:
5727 return UnsignedLongTy;
5728 case BuiltinType::LongLong:
5729 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005730 case BuiltinType::Int128:
5731 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005732 default:
5733 assert(0 && "Unexpected signed integer type");
5734 return QualType();
5735 }
5736}
5737
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005738ASTMutationListener::~ASTMutationListener() { }
5739
Chris Lattnerecd79c62009-06-14 00:45:47 +00005740
5741//===----------------------------------------------------------------------===//
5742// Builtin Type Computation
5743//===----------------------------------------------------------------------===//
5744
5745/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005746/// pointer over the consumed characters. This returns the resultant type. If
5747/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5748/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5749/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005750///
5751/// RequiresICE is filled in on return to indicate whether the value is required
5752/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005753static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005754 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005755 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005756 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005757 // Modifiers.
5758 int HowLong = 0;
5759 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005760 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005761
Chris Lattnerdc226c22010-10-01 22:42:38 +00005762 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005763 bool Done = false;
5764 while (!Done) {
5765 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005766 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005767 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005768 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005769 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005770 case 'S':
5771 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5772 assert(!Signed && "Can't use 'S' modifier multiple times!");
5773 Signed = true;
5774 break;
5775 case 'U':
5776 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5777 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5778 Unsigned = true;
5779 break;
5780 case 'L':
5781 assert(HowLong <= 2 && "Can't have LLLL modifier");
5782 ++HowLong;
5783 break;
5784 }
5785 }
5786
5787 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005788
Chris Lattnerecd79c62009-06-14 00:45:47 +00005789 // Read the base type.
5790 switch (*Str++) {
5791 default: assert(0 && "Unknown builtin type letter!");
5792 case 'v':
5793 assert(HowLong == 0 && !Signed && !Unsigned &&
5794 "Bad modifiers used with 'v'!");
5795 Type = Context.VoidTy;
5796 break;
5797 case 'f':
5798 assert(HowLong == 0 && !Signed && !Unsigned &&
5799 "Bad modifiers used with 'f'!");
5800 Type = Context.FloatTy;
5801 break;
5802 case 'd':
5803 assert(HowLong < 2 && !Signed && !Unsigned &&
5804 "Bad modifiers used with 'd'!");
5805 if (HowLong)
5806 Type = Context.LongDoubleTy;
5807 else
5808 Type = Context.DoubleTy;
5809 break;
5810 case 's':
5811 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5812 if (Unsigned)
5813 Type = Context.UnsignedShortTy;
5814 else
5815 Type = Context.ShortTy;
5816 break;
5817 case 'i':
5818 if (HowLong == 3)
5819 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5820 else if (HowLong == 2)
5821 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5822 else if (HowLong == 1)
5823 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5824 else
5825 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5826 break;
5827 case 'c':
5828 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5829 if (Signed)
5830 Type = Context.SignedCharTy;
5831 else if (Unsigned)
5832 Type = Context.UnsignedCharTy;
5833 else
5834 Type = Context.CharTy;
5835 break;
5836 case 'b': // boolean
5837 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5838 Type = Context.BoolTy;
5839 break;
5840 case 'z': // size_t.
5841 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5842 Type = Context.getSizeType();
5843 break;
5844 case 'F':
5845 Type = Context.getCFConstantStringType();
5846 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005847 case 'G':
5848 Type = Context.getObjCIdType();
5849 break;
5850 case 'H':
5851 Type = Context.getObjCSelType();
5852 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005853 case 'a':
5854 Type = Context.getBuiltinVaListType();
5855 assert(!Type.isNull() && "builtin va list type not initialized!");
5856 break;
5857 case 'A':
5858 // This is a "reference" to a va_list; however, what exactly
5859 // this means depends on how va_list is defined. There are two
5860 // different kinds of va_list: ones passed by value, and ones
5861 // passed by reference. An example of a by-value va_list is
5862 // x86, where va_list is a char*. An example of by-ref va_list
5863 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5864 // we want this argument to be a char*&; for x86-64, we want
5865 // it to be a __va_list_tag*.
5866 Type = Context.getBuiltinVaListType();
5867 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005868 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005869 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005870 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005871 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005872 break;
5873 case 'V': {
5874 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005875 unsigned NumElements = strtoul(Str, &End, 10);
5876 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005877 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005878
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005879 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5880 RequiresICE, false);
5881 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005882
5883 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005884 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005885 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005886 break;
5887 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005888 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005889 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5890 false);
5891 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005892 Type = Context.getComplexType(ElementType);
5893 break;
5894 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005895 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005896 Type = Context.getFILEType();
5897 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005898 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005899 return QualType();
5900 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005901 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005902 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005903 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005904 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005905 else
5906 Type = Context.getjmp_bufType();
5907
Mike Stump2adb4da2009-07-28 23:47:15 +00005908 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005909 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005910 return QualType();
5911 }
5912 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005913 }
Mike Stump11289f42009-09-09 15:08:12 +00005914
Chris Lattnerdc226c22010-10-01 22:42:38 +00005915 // If there are modifiers and if we're allowed to parse them, go for it.
5916 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005917 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005918 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005919 default: Done = true; --Str; break;
5920 case '*':
5921 case '&': {
5922 // Both pointers and references can have their pointee types
5923 // qualified with an address space.
5924 char *End;
5925 unsigned AddrSpace = strtoul(Str, &End, 10);
5926 if (End != Str && AddrSpace != 0) {
5927 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5928 Str = End;
5929 }
5930 if (c == '*')
5931 Type = Context.getPointerType(Type);
5932 else
5933 Type = Context.getLValueReferenceType(Type);
5934 break;
5935 }
5936 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5937 case 'C':
5938 Type = Type.withConst();
5939 break;
5940 case 'D':
5941 Type = Context.getVolatileType(Type);
5942 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005943 }
5944 }
Chris Lattner84733392010-10-01 07:13:18 +00005945
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005946 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005947 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005948
Chris Lattnerecd79c62009-06-14 00:45:47 +00005949 return Type;
5950}
5951
5952/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005953QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005954 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005955 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005956 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005957
Chris Lattnerecd79c62009-06-14 00:45:47 +00005958 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005959
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005960 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005961 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005962 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5963 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005964 if (Error != GE_None)
5965 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005966
5967 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5968
Chris Lattnerecd79c62009-06-14 00:45:47 +00005969 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005970 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005971 if (Error != GE_None)
5972 return QualType();
5973
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005974 // If this argument is required to be an IntegerConstantExpression and the
5975 // caller cares, fill in the bitmask we return.
5976 if (RequiresICE && IntegerConstantArgs)
5977 *IntegerConstantArgs |= 1 << ArgTypes.size();
5978
Chris Lattnerecd79c62009-06-14 00:45:47 +00005979 // Do array -> pointer decay. The builtin should use the decayed type.
5980 if (Ty->isArrayType())
5981 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005982
Chris Lattnerecd79c62009-06-14 00:45:47 +00005983 ArgTypes.push_back(Ty);
5984 }
5985
5986 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5987 "'.' should only occur at end of builtin type list!");
5988
John McCall991eb4b2010-12-21 00:44:39 +00005989 FunctionType::ExtInfo EI;
5990 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5991
5992 bool Variadic = (TypeStr[0] == '.');
5993
5994 // We really shouldn't be making a no-proto type here, especially in C++.
5995 if (ArgTypes.empty() && Variadic)
5996 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005997
John McCalldb40c7f2010-12-14 08:05:40 +00005998 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005999 EPI.ExtInfo = EI;
6000 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006001
6002 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006003}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006004
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006005GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6006 GVALinkage External = GVA_StrongExternal;
6007
6008 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006009 switch (L) {
6010 case NoLinkage:
6011 case InternalLinkage:
6012 case UniqueExternalLinkage:
6013 return GVA_Internal;
6014
6015 case ExternalLinkage:
6016 switch (FD->getTemplateSpecializationKind()) {
6017 case TSK_Undeclared:
6018 case TSK_ExplicitSpecialization:
6019 External = GVA_StrongExternal;
6020 break;
6021
6022 case TSK_ExplicitInstantiationDefinition:
6023 return GVA_ExplicitTemplateInstantiation;
6024
6025 case TSK_ExplicitInstantiationDeclaration:
6026 case TSK_ImplicitInstantiation:
6027 External = GVA_TemplateInstantiation;
6028 break;
6029 }
6030 }
6031
6032 if (!FD->isInlined())
6033 return External;
6034
6035 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6036 // GNU or C99 inline semantics. Determine whether this symbol should be
6037 // externally visible.
6038 if (FD->isInlineDefinitionExternallyVisible())
6039 return External;
6040
6041 // C99 inline semantics, where the symbol is not externally visible.
6042 return GVA_C99Inline;
6043 }
6044
6045 // C++0x [temp.explicit]p9:
6046 // [ Note: The intent is that an inline function that is the subject of
6047 // an explicit instantiation declaration will still be implicitly
6048 // instantiated when used so that the body can be considered for
6049 // inlining, but that no out-of-line copy of the inline function would be
6050 // generated in the translation unit. -- end note ]
6051 if (FD->getTemplateSpecializationKind()
6052 == TSK_ExplicitInstantiationDeclaration)
6053 return GVA_C99Inline;
6054
6055 return GVA_CXXInline;
6056}
6057
6058GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6059 // If this is a static data member, compute the kind of template
6060 // specialization. Otherwise, this variable is not part of a
6061 // template.
6062 TemplateSpecializationKind TSK = TSK_Undeclared;
6063 if (VD->isStaticDataMember())
6064 TSK = VD->getTemplateSpecializationKind();
6065
6066 Linkage L = VD->getLinkage();
6067 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6068 VD->getType()->getLinkage() == UniqueExternalLinkage)
6069 L = UniqueExternalLinkage;
6070
6071 switch (L) {
6072 case NoLinkage:
6073 case InternalLinkage:
6074 case UniqueExternalLinkage:
6075 return GVA_Internal;
6076
6077 case ExternalLinkage:
6078 switch (TSK) {
6079 case TSK_Undeclared:
6080 case TSK_ExplicitSpecialization:
6081 return GVA_StrongExternal;
6082
6083 case TSK_ExplicitInstantiationDeclaration:
6084 llvm_unreachable("Variable should not be instantiated");
6085 // Fall through to treat this like any other instantiation.
6086
6087 case TSK_ExplicitInstantiationDefinition:
6088 return GVA_ExplicitTemplateInstantiation;
6089
6090 case TSK_ImplicitInstantiation:
6091 return GVA_TemplateInstantiation;
6092 }
6093 }
6094
6095 return GVA_StrongExternal;
6096}
6097
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006098bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006099 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6100 if (!VD->isFileVarDecl())
6101 return false;
6102 } else if (!isa<FunctionDecl>(D))
6103 return false;
6104
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006105 // Weak references don't produce any output by themselves.
6106 if (D->hasAttr<WeakRefAttr>())
6107 return false;
6108
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006109 // Aliases and used decls are required.
6110 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6111 return true;
6112
6113 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6114 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006115 if (!FD->doesThisDeclarationHaveABody())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006116 return false;
6117
6118 // Constructors and destructors are required.
6119 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6120 return true;
6121
6122 // The key function for a class is required.
6123 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6124 const CXXRecordDecl *RD = MD->getParent();
6125 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6126 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6127 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6128 return true;
6129 }
6130 }
6131
6132 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6133
6134 // static, static inline, always_inline, and extern inline functions can
6135 // always be deferred. Normal inline functions can be deferred in C99/C++.
6136 // Implicit template instantiations can also be deferred in C++.
6137 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6138 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6139 return false;
6140 return true;
6141 }
6142
6143 const VarDecl *VD = cast<VarDecl>(D);
6144 assert(VD->isFileVarDecl() && "Expected file scoped var");
6145
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006146 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6147 return false;
6148
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006149 // Structs that have non-trivial constructors or destructors are required.
6150
6151 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006152 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006153 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6154 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006155 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6156 RD->hasTrivialCopyConstructor() &&
6157 RD->hasTrivialMoveConstructor() &&
6158 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006159 return true;
6160 }
6161 }
6162
6163 GVALinkage L = GetGVALinkageForVariable(VD);
6164 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6165 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6166 return false;
6167 }
6168
6169 return true;
6170}
Charles Davis53c59df2010-08-16 03:33:14 +00006171
Charles Davis99202b32010-11-09 18:04:24 +00006172CallingConv ASTContext::getDefaultMethodCallConv() {
6173 // Pass through to the C++ ABI object
6174 return ABI->getDefaultMethodCallConv();
6175}
6176
Jay Foad39c79802011-01-12 09:06:06 +00006177bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006178 // Pass through to the C++ ABI object
6179 return ABI->isNearlyEmpty(RD);
6180}
6181
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006182MangleContext *ASTContext::createMangleContext() {
6183 switch (Target.getCXXABI()) {
6184 case CXXABI_ARM:
6185 case CXXABI_Itanium:
6186 return createItaniumMangleContext(*this, getDiagnostics());
6187 case CXXABI_Microsoft:
6188 return createMicrosoftMangleContext(*this, getDiagnostics());
6189 }
6190 assert(0 && "Unsupported ABI");
6191 return 0;
6192}
6193
Charles Davis53c59df2010-08-16 03:33:14 +00006194CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006195
6196size_t ASTContext::getSideTableAllocatedMemory() const {
6197 size_t bytes = 0;
6198 bytes += ASTRecordLayouts.getMemorySize();
6199 bytes += ObjCLayouts.getMemorySize();
6200 bytes += KeyFunctions.getMemorySize();
6201 bytes += ObjCImpls.getMemorySize();
6202 bytes += BlockVarCopyInits.getMemorySize();
6203 bytes += DeclAttrs.getMemorySize();
6204 bytes += InstantiatedFromStaticDataMember.getMemorySize();
6205 bytes += InstantiatedFromUsingDecl.getMemorySize();
6206 bytes += InstantiatedFromUsingShadowDecl.getMemorySize();
6207 bytes += InstantiatedFromUnnamedFieldDecl.getMemorySize();
6208 return bytes;
6209}
6210