blob: 07823e04081adeae3c618b3ceffd6ea460e6bb20 [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
Douglas Gregor832940b2010-03-02 23:58:15 +0000561ASTContext::overridden_cxx_method_iterator
562ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
563 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
564 = OverriddenMethods.find(Method);
565 if (Pos == OverriddenMethods.end())
566 return 0;
567
568 return Pos->second.begin();
569}
570
571ASTContext::overridden_cxx_method_iterator
572ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
573 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
574 = OverriddenMethods.find(Method);
575 if (Pos == OverriddenMethods.end())
576 return 0;
577
578 return Pos->second.end();
579}
580
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000581unsigned
582ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
583 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
584 = OverriddenMethods.find(Method);
585 if (Pos == OverriddenMethods.end())
586 return 0;
587
588 return Pos->second.size();
589}
590
Douglas Gregor832940b2010-03-02 23:58:15 +0000591void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
592 const CXXMethodDecl *Overridden) {
593 OverriddenMethods[Method].push_back(Overridden);
594}
595
Chris Lattner53cfe802007-07-18 17:52:12 +0000596//===----------------------------------------------------------------------===//
597// Type Sizing and Analysis
598//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000599
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000600/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
601/// scalar floating point type.
602const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000603 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000604 assert(BT && "Not a floating point type!");
605 switch (BT->getKind()) {
606 default: assert(0 && "Not a floating point type!");
607 case BuiltinType::Float: return Target.getFloatFormat();
608 case BuiltinType::Double: return Target.getDoubleFormat();
609 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
610 }
611}
612
Ken Dyck160146e2010-01-27 17:10:57 +0000613/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000614/// specified decl. Note that bitfields do not have a valid alignment, so
615/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000616/// If @p RefAsPointee, references are treated like their underlying type
617/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000618CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000619 unsigned Align = Target.getCharWidth();
620
John McCall94268702010-10-08 18:24:19 +0000621 bool UseAlignAttrOnly = false;
622 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
623 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000624
John McCall94268702010-10-08 18:24:19 +0000625 // __attribute__((aligned)) can increase or decrease alignment
626 // *except* on a struct or struct member, where it only increases
627 // alignment unless 'packed' is also specified.
628 //
629 // It is an error for [[align]] to decrease alignment, so we can
630 // ignore that possibility; Sema should diagnose it.
631 if (isa<FieldDecl>(D)) {
632 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
633 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
634 } else {
635 UseAlignAttrOnly = true;
636 }
637 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000638 else if (isa<FieldDecl>(D))
639 UseAlignAttrOnly =
640 D->hasAttr<PackedAttr>() ||
641 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000642
John McCall4e819612011-01-20 07:57:12 +0000643 // If we're using the align attribute only, just ignore everything
644 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000645 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000646 // do nothing
647
John McCall94268702010-10-08 18:24:19 +0000648 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000649 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000650 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000651 if (RefAsPointee)
652 T = RT->getPointeeType();
653 else
654 T = getPointerType(RT->getPointeeType());
655 }
656 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000657 // Adjust alignments of declarations with array type by the
658 // large-array alignment on the target.
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000659 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000660 const ArrayType *arrayType;
661 if (MinWidth && (arrayType = getAsArrayType(T))) {
662 if (isa<VariableArrayType>(arrayType))
663 Align = std::max(Align, Target.getLargeArrayAlign());
664 else if (isa<ConstantArrayType>(arrayType) &&
665 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
666 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000667
John McCall33ddac02011-01-19 10:06:00 +0000668 // Walk through any array types while we're at it.
669 T = getBaseElementType(arrayType);
670 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000671 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
672 }
John McCall4e819612011-01-20 07:57:12 +0000673
674 // Fields can be subject to extra alignment constraints, like if
675 // the field is packed, the struct is packed, or the struct has a
676 // a max-field-alignment constraint (#pragma pack). So calculate
677 // the actual alignment of the field within the struct, and then
678 // (as we're expected to) constrain that by the alignment of the type.
679 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
680 // So calculate the alignment of the field.
681 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
682
683 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000684 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000685
686 // Use the GCD of that and the offset within the record.
687 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
688 if (offset > 0) {
689 // Alignment is always a power of 2, so the GCD will be a power of 2,
690 // which means we get to do this crazy thing instead of Euclid's.
691 uint64_t lowBitOfOffset = offset & (~offset + 1);
692 if (lowBitOfOffset < fieldAlign)
693 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
694 }
695
696 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000697 }
Chris Lattner68061312009-01-24 21:53:27 +0000698 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000699
Ken Dyckcc56c542011-01-15 18:38:59 +0000700 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000701}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000702
John McCall87fe5d52010-05-20 01:18:31 +0000703std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000704ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000705 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000706 return std::make_pair(toCharUnitsFromBits(Info.first),
707 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000708}
709
710std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000711ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000712 return getTypeInfoInChars(T.getTypePtr());
713}
714
Chris Lattner983a8bb2007-07-13 22:13:22 +0000715/// getTypeSize - Return the size of the specified type, in bits. This method
716/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000717///
718/// FIXME: Pointers into different addr spaces could have different sizes and
719/// alignment requirements: getPointerInfo should take an AddrSpace, this
720/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000721std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000722ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000723 uint64_t Width=0;
724 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000725 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000726#define TYPE(Class, Base)
727#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000728#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000729#define DEPENDENT_TYPE(Class, Base) case Type::Class:
730#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000731 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000732 break;
733
Chris Lattner355332d2007-07-13 22:27:08 +0000734 case Type::FunctionNoProto:
735 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000736 // GCC extension: alignof(function) = 32 bits
737 Width = 0;
738 Align = 32;
739 break;
740
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000741 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000742 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000743 Width = 0;
744 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
745 break;
746
Steve Naroff5c131802007-08-30 01:06:46 +0000747 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000748 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000749
Chris Lattner37e05872008-03-05 18:54:05 +0000750 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000751 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000752 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000753 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000754 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000755 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000756 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000757 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000758 const VectorType *VT = cast<VectorType>(T);
759 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
760 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000761 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000762 // If the alignment is not a power of 2, round up to the next power of 2.
763 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000764 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000765 Align = llvm::NextPowerOf2(Align);
766 Width = llvm::RoundUpToAlignment(Width, Align);
767 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000768 break;
769 }
Chris Lattner647fb222007-07-18 18:26:58 +0000770
Chris Lattner7570e9c2008-03-08 08:52:55 +0000771 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000772 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000773 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000774 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000775 // GCC extension: alignof(void) = 8 bits.
776 Width = 0;
777 Align = 8;
778 break;
779
Chris Lattner6a4f7452007-12-19 19:23:28 +0000780 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000781 Width = Target.getBoolWidth();
782 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000783 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000784 case BuiltinType::Char_S:
785 case BuiltinType::Char_U:
786 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000787 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000788 Width = Target.getCharWidth();
789 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000790 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000791 case BuiltinType::WChar_S:
792 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000793 Width = Target.getWCharWidth();
794 Align = Target.getWCharAlign();
795 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000796 case BuiltinType::Char16:
797 Width = Target.getChar16Width();
798 Align = Target.getChar16Align();
799 break;
800 case BuiltinType::Char32:
801 Width = Target.getChar32Width();
802 Align = Target.getChar32Align();
803 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000804 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000805 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000806 Width = Target.getShortWidth();
807 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000808 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000809 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000810 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000811 Width = Target.getIntWidth();
812 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000813 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000814 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000815 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000816 Width = Target.getLongWidth();
817 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000818 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000819 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000820 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000821 Width = Target.getLongLongWidth();
822 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000823 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000824 case BuiltinType::Int128:
825 case BuiltinType::UInt128:
826 Width = 128;
827 Align = 128; // int128_t is 128-bit aligned on all targets.
828 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000829 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000830 Width = Target.getFloatWidth();
831 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000832 break;
833 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000834 Width = Target.getDoubleWidth();
835 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000836 break;
837 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000838 Width = Target.getLongDoubleWidth();
839 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000840 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000841 case BuiltinType::NullPtr:
842 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
843 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000844 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000845 case BuiltinType::ObjCId:
846 case BuiltinType::ObjCClass:
847 case BuiltinType::ObjCSel:
848 Width = Target.getPointerWidth(0);
849 Align = Target.getPointerAlign(0);
850 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000851 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000852 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000853 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000854 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000855 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000856 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000857 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000858 unsigned AS = getTargetAddressSpace(
859 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff921a45c2008-09-24 15:05:44 +0000860 Width = Target.getPointerWidth(AS);
861 Align = Target.getPointerAlign(AS);
862 break;
863 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000864 case Type::LValueReference:
865 case Type::RValueReference: {
866 // alignof and sizeof should never enter this code path here, so we go
867 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000868 unsigned AS = getTargetAddressSpace(
869 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000870 Width = Target.getPointerWidth(AS);
871 Align = Target.getPointerAlign(AS);
872 break;
873 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000874 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000875 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000876 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000877 Align = Target.getPointerAlign(AS);
878 break;
879 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000880 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000881 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000882 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000883 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000884 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000885 Align = PtrDiffInfo.second;
886 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000887 }
Chris Lattner647fb222007-07-18 18:26:58 +0000888 case Type::Complex: {
889 // Complex types have the same alignment as their elements, but twice the
890 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000891 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000892 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000893 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000894 Align = EltInfo.second;
895 break;
896 }
John McCall8b07ec22010-05-15 11:32:37 +0000897 case Type::ObjCObject:
898 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000899 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000900 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000901 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000902 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000903 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000904 break;
905 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000906 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000907 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000908 const TagType *TT = cast<TagType>(T);
909
910 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +0000911 Width = 8;
912 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +0000913 break;
914 }
Mike Stump11289f42009-09-09 15:08:12 +0000915
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000916 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000917 return getTypeInfo(ET->getDecl()->getIntegerType());
918
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000919 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000920 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000921 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000922 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +0000923 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000924 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000925
Chris Lattner63d2b362009-10-22 05:17:15 +0000926 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000927 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
928 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000929
Richard Smith30482bc2011-02-20 03:19:35 +0000930 case Type::Auto: {
931 const AutoType *A = cast<AutoType>(T);
932 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +0000933 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +0000934 }
935
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000936 case Type::Paren:
937 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
938
Douglas Gregoref462e62009-04-30 17:32:17 +0000939 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +0000940 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000941 std::pair<uint64_t, unsigned> Info
942 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +0000943 // If the typedef has an aligned attribute on it, it overrides any computed
944 // alignment we have. This violates the GCC documentation (which says that
945 // attribute(aligned) can only round up) but matches its implementation.
946 if (unsigned AttrAlign = Typedef->getMaxAlignment())
947 Align = AttrAlign;
948 else
949 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +0000950 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000951 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000952 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000953
954 case Type::TypeOfExpr:
955 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
956 .getTypePtr());
957
958 case Type::TypeOf:
959 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
960
Anders Carlsson81df7b82009-06-24 19:06:50 +0000961 case Type::Decltype:
962 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
963 .getTypePtr());
964
Abramo Bagnara6150c882010-05-11 21:36:43 +0000965 case Type::Elaborated:
966 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000967
John McCall81904512011-01-06 01:58:22 +0000968 case Type::Attributed:
969 return getTypeInfo(
970 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
971
Richard Smith3f1b5d02011-05-05 21:57:07 +0000972 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +0000973 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000974 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +0000975 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
976 // A type alias template specialization may refer to a typedef with the
977 // aligned attribute on it.
978 if (TST->isTypeAlias())
979 return getTypeInfo(TST->getAliasedType().getTypePtr());
980 else
981 return getTypeInfo(getCanonicalType(T));
982 }
983
Douglas Gregoref462e62009-04-30 17:32:17 +0000984 }
Mike Stump11289f42009-09-09 15:08:12 +0000985
Chris Lattner53cfe802007-07-18 17:52:12 +0000986 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000987 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000988}
989
Ken Dyckcc56c542011-01-15 18:38:59 +0000990/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
991CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
992 return CharUnits::fromQuantity(BitSize / getCharWidth());
993}
994
Ken Dyckb0fcc592011-02-11 01:54:29 +0000995/// toBits - Convert a size in characters to a size in characters.
996int64_t ASTContext::toBits(CharUnits CharSize) const {
997 return CharSize.getQuantity() * getCharWidth();
998}
999
Ken Dyck8c89d592009-12-22 14:23:30 +00001000/// getTypeSizeInChars - Return the size of the specified type, in characters.
1001/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001002CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001003 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001004}
Jay Foad39c79802011-01-12 09:06:06 +00001005CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001006 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001007}
1008
Ken Dycka6046ab2010-01-26 17:25:18 +00001009/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001010/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001011CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001012 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001013}
Jay Foad39c79802011-01-12 09:06:06 +00001014CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001015 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001016}
1017
Chris Lattnera3402cd2009-01-27 18:08:34 +00001018/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1019/// type for the current target in bits. This can be different than the ABI
1020/// alignment in cases where it is beneficial for performance to overalign
1021/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001022unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001023 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001024
1025 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001026 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001027 T = CT->getElementType().getTypePtr();
1028 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1029 T->isSpecificBuiltinType(BuiltinType::LongLong))
1030 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1031
Chris Lattnera3402cd2009-01-27 18:08:34 +00001032 return ABIAlign;
1033}
1034
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001035/// ShallowCollectObjCIvars -
1036/// Collect all ivars, including those synthesized, in the current class.
1037///
1038void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +00001039 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001040 // FIXME. This need be removed but there are two many places which
1041 // assume const-ness of ObjCInterfaceDecl
1042 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1043 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1044 Iv= Iv->getNextIvar())
1045 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001046}
1047
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001048/// DeepCollectObjCIvars -
1049/// This routine first collects all declared, but not synthesized, ivars in
1050/// super class and then collects all ivars, including those synthesized for
1051/// current class. This routine is used for implementation of current class
1052/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001053///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001054void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1055 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +00001056 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001057 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1058 DeepCollectObjCIvars(SuperClass, false, Ivars);
1059 if (!leafClass) {
1060 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1061 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001062 Ivars.push_back(*I);
1063 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001064 else
1065 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001066}
1067
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001068/// CollectInheritedProtocols - Collect all protocols in current class and
1069/// those inherited by it.
1070void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001071 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001072 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001073 // We can use protocol_iterator here instead of
1074 // all_referenced_protocol_iterator since we are walking all categories.
1075 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1076 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001077 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001078 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001079 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001080 PE = Proto->protocol_end(); P != PE; ++P) {
1081 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001082 CollectInheritedProtocols(*P, Protocols);
1083 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001084 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001085
1086 // Categories of this Interface.
1087 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1088 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1089 CollectInheritedProtocols(CDeclChain, Protocols);
1090 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1091 while (SD) {
1092 CollectInheritedProtocols(SD, Protocols);
1093 SD = SD->getSuperClass();
1094 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001095 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001096 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001097 PE = OC->protocol_end(); P != PE; ++P) {
1098 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001099 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001100 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1101 PE = Proto->protocol_end(); P != PE; ++P)
1102 CollectInheritedProtocols(*P, Protocols);
1103 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001104 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001105 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1106 PE = OP->protocol_end(); P != PE; ++P) {
1107 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001108 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001109 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1110 PE = Proto->protocol_end(); P != PE; ++P)
1111 CollectInheritedProtocols(*P, Protocols);
1112 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001113 }
1114}
1115
Jay Foad39c79802011-01-12 09:06:06 +00001116unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001117 unsigned count = 0;
1118 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001119 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1120 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001121 count += CDecl->ivar_size();
1122
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001123 // Count ivar defined in this class's implementation. This
1124 // includes synthesized ivars.
1125 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001126 count += ImplDecl->ivar_size();
1127
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001128 return count;
1129}
1130
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001131/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1132ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1133 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1134 I = ObjCImpls.find(D);
1135 if (I != ObjCImpls.end())
1136 return cast<ObjCImplementationDecl>(I->second);
1137 return 0;
1138}
1139/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1140ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1141 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1142 I = ObjCImpls.find(D);
1143 if (I != ObjCImpls.end())
1144 return cast<ObjCCategoryImplDecl>(I->second);
1145 return 0;
1146}
1147
1148/// \brief Set the implementation of ObjCInterfaceDecl.
1149void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1150 ObjCImplementationDecl *ImplD) {
1151 assert(IFaceD && ImplD && "Passed null params");
1152 ObjCImpls[IFaceD] = ImplD;
1153}
1154/// \brief Set the implementation of ObjCCategoryDecl.
1155void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1156 ObjCCategoryImplDecl *ImplD) {
1157 assert(CatD && ImplD && "Passed null params");
1158 ObjCImpls[CatD] = ImplD;
1159}
1160
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001161/// \brief Get the copy initialization expression of VarDecl,or NULL if
1162/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001163Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001164 assert(VD && "Passed null params");
1165 assert(VD->hasAttr<BlocksAttr>() &&
1166 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001167 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001168 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001169 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1170}
1171
1172/// \brief Set the copy inialization expression of a block var decl.
1173void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1174 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001175 assert(VD->hasAttr<BlocksAttr>() &&
1176 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001177 BlockVarCopyInits[VD] = Init;
1178}
1179
John McCallbcd03502009-12-07 02:54:59 +00001180/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001181///
John McCallbcd03502009-12-07 02:54:59 +00001182/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001183/// the TypeLoc wrappers.
1184///
1185/// \param T the type that will be the basis for type source info. This type
1186/// should refer to how the declarator was written in source code, not to
1187/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001188TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001189 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001190 if (!DataSize)
1191 DataSize = TypeLoc::getFullDataSizeForType(T);
1192 else
1193 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001194 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001195
John McCallbcd03502009-12-07 02:54:59 +00001196 TypeSourceInfo *TInfo =
1197 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1198 new (TInfo) TypeSourceInfo(T);
1199 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001200}
1201
John McCallbcd03502009-12-07 02:54:59 +00001202TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001203 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001204 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001205 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001206 return DI;
1207}
1208
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001209const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001210ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001211 return getObjCLayout(D, 0);
1212}
1213
1214const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001215ASTContext::getASTObjCImplementationLayout(
1216 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001217 return getObjCLayout(D->getClassInterface(), D);
1218}
1219
Chris Lattner983a8bb2007-07-13 22:13:22 +00001220//===----------------------------------------------------------------------===//
1221// Type creation/memoization methods
1222//===----------------------------------------------------------------------===//
1223
Jay Foad39c79802011-01-12 09:06:06 +00001224QualType
John McCall33ddac02011-01-19 10:06:00 +00001225ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1226 unsigned fastQuals = quals.getFastQualifiers();
1227 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001228
1229 // Check if we've already instantiated this type.
1230 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001231 ExtQuals::Profile(ID, baseType, quals);
1232 void *insertPos = 0;
1233 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1234 assert(eq->getQualifiers() == quals);
1235 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001236 }
1237
John McCall33ddac02011-01-19 10:06:00 +00001238 // If the base type is not canonical, make the appropriate canonical type.
1239 QualType canon;
1240 if (!baseType->isCanonicalUnqualified()) {
1241 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1242 canonSplit.second.addConsistentQualifiers(quals);
1243 canon = getExtQualType(canonSplit.first, canonSplit.second);
1244
1245 // Re-find the insert position.
1246 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1247 }
1248
1249 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1250 ExtQualNodes.InsertNode(eq, insertPos);
1251 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001252}
1253
Jay Foad39c79802011-01-12 09:06:06 +00001254QualType
1255ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001256 QualType CanT = getCanonicalType(T);
1257 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001258 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001259
John McCall8ccfcb52009-09-24 19:53:00 +00001260 // If we are composing extended qualifiers together, merge together
1261 // into one ExtQuals node.
1262 QualifierCollector Quals;
1263 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001264
John McCall8ccfcb52009-09-24 19:53:00 +00001265 // If this type already has an address space specified, it cannot get
1266 // another one.
1267 assert(!Quals.hasAddressSpace() &&
1268 "Type cannot be in multiple addr spaces!");
1269 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001270
John McCall8ccfcb52009-09-24 19:53:00 +00001271 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001272}
1273
Chris Lattnerd60183d2009-02-18 22:53:11 +00001274QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001275 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001276 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001277 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001278 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001279
John McCall53fa7142010-12-24 02:08:15 +00001280 if (const PointerType *ptr = T->getAs<PointerType>()) {
1281 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001282 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001283 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1284 return getPointerType(ResultType);
1285 }
1286 }
Mike Stump11289f42009-09-09 15:08:12 +00001287
John McCall8ccfcb52009-09-24 19:53:00 +00001288 // If we are composing extended qualifiers together, merge together
1289 // into one ExtQuals node.
1290 QualifierCollector Quals;
1291 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001292
John McCall8ccfcb52009-09-24 19:53:00 +00001293 // If this type already has an ObjCGC specified, it cannot get
1294 // another one.
1295 assert(!Quals.hasObjCGCAttr() &&
1296 "Type cannot have multiple ObjCGCs!");
1297 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001298
John McCall8ccfcb52009-09-24 19:53:00 +00001299 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001300}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001301
John McCall4f5019e2010-12-19 02:44:49 +00001302const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1303 FunctionType::ExtInfo Info) {
1304 if (T->getExtInfo() == Info)
1305 return T;
1306
1307 QualType Result;
1308 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1309 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1310 } else {
1311 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1312 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1313 EPI.ExtInfo = Info;
1314 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1315 FPT->getNumArgs(), EPI);
1316 }
1317
1318 return cast<FunctionType>(Result.getTypePtr());
1319}
1320
Chris Lattnerc6395932007-06-22 20:56:16 +00001321/// getComplexType - Return the uniqued reference to the type for a complex
1322/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001323QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001324 // Unique pointers, to guarantee there is only one pointer of a particular
1325 // structure.
1326 llvm::FoldingSetNodeID ID;
1327 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001328
Chris Lattnerc6395932007-06-22 20:56:16 +00001329 void *InsertPos = 0;
1330 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1331 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001332
Chris Lattnerc6395932007-06-22 20:56:16 +00001333 // If the pointee type isn't canonical, this won't be a canonical type either,
1334 // so fill in the canonical type field.
1335 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001336 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001337 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001338
Chris Lattnerc6395932007-06-22 20:56:16 +00001339 // Get the new insert position for the node we care about.
1340 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001341 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001342 }
John McCall90d1c2d2009-09-24 23:30:46 +00001343 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001344 Types.push_back(New);
1345 ComplexTypes.InsertNode(New, InsertPos);
1346 return QualType(New, 0);
1347}
1348
Chris Lattner970e54e2006-11-12 00:37:36 +00001349/// getPointerType - Return the uniqued reference to the type for a pointer to
1350/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001351QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001352 // Unique pointers, to guarantee there is only one pointer of a particular
1353 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001354 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001355 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001356
Chris Lattner67521df2007-01-27 01:29:36 +00001357 void *InsertPos = 0;
1358 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001359 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001360
Chris Lattner7ccecb92006-11-12 08:50:50 +00001361 // If the pointee type isn't canonical, this won't be a canonical type either,
1362 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001363 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001364 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001365 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001366
Chris Lattner67521df2007-01-27 01:29:36 +00001367 // Get the new insert position for the node we care about.
1368 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001369 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001370 }
John McCall90d1c2d2009-09-24 23:30:46 +00001371 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001372 Types.push_back(New);
1373 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001374 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001375}
1376
Mike Stump11289f42009-09-09 15:08:12 +00001377/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001378/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001379QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001380 assert(T->isFunctionType() && "block of function types only");
1381 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001382 // structure.
1383 llvm::FoldingSetNodeID ID;
1384 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001385
Steve Naroffec33ed92008-08-27 16:04:49 +00001386 void *InsertPos = 0;
1387 if (BlockPointerType *PT =
1388 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1389 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001390
1391 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001392 // type either so fill in the canonical type field.
1393 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001394 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001395 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001396
Steve Naroffec33ed92008-08-27 16:04:49 +00001397 // Get the new insert position for the node we care about.
1398 BlockPointerType *NewIP =
1399 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001400 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001401 }
John McCall90d1c2d2009-09-24 23:30:46 +00001402 BlockPointerType *New
1403 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001404 Types.push_back(New);
1405 BlockPointerTypes.InsertNode(New, InsertPos);
1406 return QualType(New, 0);
1407}
1408
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001409/// getLValueReferenceType - Return the uniqued reference to the type for an
1410/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001411QualType
1412ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001413 // Unique pointers, to guarantee there is only one pointer of a particular
1414 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001415 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001416 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001417
1418 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001419 if (LValueReferenceType *RT =
1420 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001421 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001422
John McCallfc93cf92009-10-22 22:37:11 +00001423 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1424
Bill Wendling3708c182007-05-27 10:15:43 +00001425 // If the referencee type isn't canonical, this won't be a canonical type
1426 // either, so fill in the canonical type field.
1427 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001428 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1429 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1430 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001431
Bill Wendling3708c182007-05-27 10:15:43 +00001432 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001433 LValueReferenceType *NewIP =
1434 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001435 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001436 }
1437
John McCall90d1c2d2009-09-24 23:30:46 +00001438 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001439 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1440 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001441 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001442 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001443
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001444 return QualType(New, 0);
1445}
1446
1447/// getRValueReferenceType - Return the uniqued reference to the type for an
1448/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001449QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001450 // Unique pointers, to guarantee there is only one pointer of a particular
1451 // structure.
1452 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001453 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001454
1455 void *InsertPos = 0;
1456 if (RValueReferenceType *RT =
1457 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1458 return QualType(RT, 0);
1459
John McCallfc93cf92009-10-22 22:37:11 +00001460 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1461
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001462 // If the referencee type isn't canonical, this won't be a canonical type
1463 // either, so fill in the canonical type field.
1464 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001465 if (InnerRef || !T.isCanonical()) {
1466 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1467 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001468
1469 // Get the new insert position for the node we care about.
1470 RValueReferenceType *NewIP =
1471 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001472 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001473 }
1474
John McCall90d1c2d2009-09-24 23:30:46 +00001475 RValueReferenceType *New
1476 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001477 Types.push_back(New);
1478 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001479 return QualType(New, 0);
1480}
1481
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001482/// getMemberPointerType - Return the uniqued reference to the type for a
1483/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001484QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001485 // Unique pointers, to guarantee there is only one pointer of a particular
1486 // structure.
1487 llvm::FoldingSetNodeID ID;
1488 MemberPointerType::Profile(ID, T, Cls);
1489
1490 void *InsertPos = 0;
1491 if (MemberPointerType *PT =
1492 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1493 return QualType(PT, 0);
1494
1495 // If the pointee or class type isn't canonical, this won't be a canonical
1496 // type either, so fill in the canonical type field.
1497 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001498 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001499 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1500
1501 // Get the new insert position for the node we care about.
1502 MemberPointerType *NewIP =
1503 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001504 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001505 }
John McCall90d1c2d2009-09-24 23:30:46 +00001506 MemberPointerType *New
1507 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001508 Types.push_back(New);
1509 MemberPointerTypes.InsertNode(New, InsertPos);
1510 return QualType(New, 0);
1511}
1512
Mike Stump11289f42009-09-09 15:08:12 +00001513/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001514/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001515QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001516 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001517 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001518 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001519 assert((EltTy->isDependentType() ||
1520 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001521 "Constant array of VLAs is illegal!");
1522
Chris Lattnere2df3f92009-05-13 04:12:56 +00001523 // Convert the array size into a canonical width matching the pointer size for
1524 // the target.
1525 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001526 ArySize =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001527 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001528
Chris Lattner23b7eb62007-06-15 23:05:46 +00001529 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001530 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001531
Chris Lattner36f8e652007-01-27 08:31:04 +00001532 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001533 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001534 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001535 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001536
John McCall33ddac02011-01-19 10:06:00 +00001537 // If the element type isn't canonical or has qualifiers, this won't
1538 // be a canonical type either, so fill in the canonical type field.
1539 QualType Canon;
1540 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1541 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1542 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001543 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001544 Canon = getQualifiedType(Canon, canonSplit.second);
1545
Chris Lattner36f8e652007-01-27 08:31:04 +00001546 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001547 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001548 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001549 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001550 }
Mike Stump11289f42009-09-09 15:08:12 +00001551
John McCall90d1c2d2009-09-24 23:30:46 +00001552 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001553 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001554 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001555 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001556 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001557}
1558
John McCall06549462011-01-18 08:40:38 +00001559/// getVariableArrayDecayedType - Turns the given type, which may be
1560/// variably-modified, into the corresponding type with all the known
1561/// sizes replaced with [*].
1562QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1563 // Vastly most common case.
1564 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001565
John McCall06549462011-01-18 08:40:38 +00001566 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001567
John McCall06549462011-01-18 08:40:38 +00001568 SplitQualType split = type.getSplitDesugaredType();
1569 const Type *ty = split.first;
1570 switch (ty->getTypeClass()) {
1571#define TYPE(Class, Base)
1572#define ABSTRACT_TYPE(Class, Base)
1573#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1574#include "clang/AST/TypeNodes.def"
1575 llvm_unreachable("didn't desugar past all non-canonical types?");
1576
1577 // These types should never be variably-modified.
1578 case Type::Builtin:
1579 case Type::Complex:
1580 case Type::Vector:
1581 case Type::ExtVector:
1582 case Type::DependentSizedExtVector:
1583 case Type::ObjCObject:
1584 case Type::ObjCInterface:
1585 case Type::ObjCObjectPointer:
1586 case Type::Record:
1587 case Type::Enum:
1588 case Type::UnresolvedUsing:
1589 case Type::TypeOfExpr:
1590 case Type::TypeOf:
1591 case Type::Decltype:
1592 case Type::DependentName:
1593 case Type::InjectedClassName:
1594 case Type::TemplateSpecialization:
1595 case Type::DependentTemplateSpecialization:
1596 case Type::TemplateTypeParm:
1597 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001598 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001599 case Type::PackExpansion:
1600 llvm_unreachable("type should never be variably-modified");
1601
1602 // These types can be variably-modified but should never need to
1603 // further decay.
1604 case Type::FunctionNoProto:
1605 case Type::FunctionProto:
1606 case Type::BlockPointer:
1607 case Type::MemberPointer:
1608 return type;
1609
1610 // These types can be variably-modified. All these modifications
1611 // preserve structure except as noted by comments.
1612 // TODO: if we ever care about optimizing VLAs, there are no-op
1613 // optimizations available here.
1614 case Type::Pointer:
1615 result = getPointerType(getVariableArrayDecayedType(
1616 cast<PointerType>(ty)->getPointeeType()));
1617 break;
1618
1619 case Type::LValueReference: {
1620 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1621 result = getLValueReferenceType(
1622 getVariableArrayDecayedType(lv->getPointeeType()),
1623 lv->isSpelledAsLValue());
1624 break;
1625 }
1626
1627 case Type::RValueReference: {
1628 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1629 result = getRValueReferenceType(
1630 getVariableArrayDecayedType(lv->getPointeeType()));
1631 break;
1632 }
1633
1634 case Type::ConstantArray: {
1635 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1636 result = getConstantArrayType(
1637 getVariableArrayDecayedType(cat->getElementType()),
1638 cat->getSize(),
1639 cat->getSizeModifier(),
1640 cat->getIndexTypeCVRQualifiers());
1641 break;
1642 }
1643
1644 case Type::DependentSizedArray: {
1645 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1646 result = getDependentSizedArrayType(
1647 getVariableArrayDecayedType(dat->getElementType()),
1648 dat->getSizeExpr(),
1649 dat->getSizeModifier(),
1650 dat->getIndexTypeCVRQualifiers(),
1651 dat->getBracketsRange());
1652 break;
1653 }
1654
1655 // Turn incomplete types into [*] types.
1656 case Type::IncompleteArray: {
1657 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1658 result = getVariableArrayType(
1659 getVariableArrayDecayedType(iat->getElementType()),
1660 /*size*/ 0,
1661 ArrayType::Normal,
1662 iat->getIndexTypeCVRQualifiers(),
1663 SourceRange());
1664 break;
1665 }
1666
1667 // Turn VLA types into [*] types.
1668 case Type::VariableArray: {
1669 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1670 result = getVariableArrayType(
1671 getVariableArrayDecayedType(vat->getElementType()),
1672 /*size*/ 0,
1673 ArrayType::Star,
1674 vat->getIndexTypeCVRQualifiers(),
1675 vat->getBracketsRange());
1676 break;
1677 }
1678 }
1679
1680 // Apply the top-level qualifiers from the original.
1681 return getQualifiedType(result, split.second);
1682}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001683
Steve Naroffcadebd02007-08-30 18:14:25 +00001684/// getVariableArrayType - Returns a non-unique reference to the type for a
1685/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001686QualType ASTContext::getVariableArrayType(QualType EltTy,
1687 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001688 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001689 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001690 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001691 // Since we don't unique expressions, it isn't possible to unique VLA's
1692 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001693 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001694
John McCall33ddac02011-01-19 10:06:00 +00001695 // Be sure to pull qualifiers off the element type.
1696 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1697 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1698 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001699 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001700 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001701 }
1702
John McCall90d1c2d2009-09-24 23:30:46 +00001703 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001704 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001705
1706 VariableArrayTypes.push_back(New);
1707 Types.push_back(New);
1708 return QualType(New, 0);
1709}
1710
Douglas Gregor4619e432008-12-05 23:32:09 +00001711/// getDependentSizedArrayType - Returns a non-unique reference to
1712/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001713/// type.
John McCall33ddac02011-01-19 10:06:00 +00001714QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1715 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001716 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001717 unsigned elementTypeQuals,
1718 SourceRange brackets) const {
1719 assert((!numElements || numElements->isTypeDependent() ||
1720 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001721 "Size must be type- or value-dependent!");
1722
John McCall33ddac02011-01-19 10:06:00 +00001723 // Dependently-sized array types that do not have a specified number
1724 // of elements will have their sizes deduced from a dependent
1725 // initializer. We do no canonicalization here at all, which is okay
1726 // because they can't be used in most locations.
1727 if (!numElements) {
1728 DependentSizedArrayType *newType
1729 = new (*this, TypeAlignment)
1730 DependentSizedArrayType(*this, elementType, QualType(),
1731 numElements, ASM, elementTypeQuals,
1732 brackets);
1733 Types.push_back(newType);
1734 return QualType(newType, 0);
1735 }
1736
1737 // Otherwise, we actually build a new type every time, but we
1738 // also build a canonical type.
1739
1740 SplitQualType canonElementType = getCanonicalType(elementType).split();
1741
1742 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001743 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001744 DependentSizedArrayType::Profile(ID, *this,
1745 QualType(canonElementType.first, 0),
1746 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001747
John McCall33ddac02011-01-19 10:06:00 +00001748 // Look for an existing type with these properties.
1749 DependentSizedArrayType *canonTy =
1750 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001751
John McCall33ddac02011-01-19 10:06:00 +00001752 // If we don't have one, build one.
1753 if (!canonTy) {
1754 canonTy = new (*this, TypeAlignment)
1755 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1756 QualType(), numElements, ASM, elementTypeQuals,
1757 brackets);
1758 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1759 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001760 }
1761
John McCall33ddac02011-01-19 10:06:00 +00001762 // Apply qualifiers from the element type to the array.
1763 QualType canon = getQualifiedType(QualType(canonTy,0),
1764 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001765
John McCall33ddac02011-01-19 10:06:00 +00001766 // If we didn't need extra canonicalization for the element type,
1767 // then just use that as our result.
1768 if (QualType(canonElementType.first, 0) == elementType)
1769 return canon;
1770
1771 // Otherwise, we need to build a type which follows the spelling
1772 // of the element type.
1773 DependentSizedArrayType *sugaredType
1774 = new (*this, TypeAlignment)
1775 DependentSizedArrayType(*this, elementType, canon, numElements,
1776 ASM, elementTypeQuals, brackets);
1777 Types.push_back(sugaredType);
1778 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001779}
1780
John McCall33ddac02011-01-19 10:06:00 +00001781QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001782 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001783 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001784 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001785 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001786
John McCall33ddac02011-01-19 10:06:00 +00001787 void *insertPos = 0;
1788 if (IncompleteArrayType *iat =
1789 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1790 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001791
1792 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001793 // either, so fill in the canonical type field. We also have to pull
1794 // qualifiers off the element type.
1795 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001796
John McCall33ddac02011-01-19 10:06:00 +00001797 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1798 SplitQualType canonSplit = getCanonicalType(elementType).split();
1799 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1800 ASM, elementTypeQuals);
1801 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001802
1803 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001804 IncompleteArrayType *existing =
1805 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1806 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001807 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001808
John McCall33ddac02011-01-19 10:06:00 +00001809 IncompleteArrayType *newType = new (*this, TypeAlignment)
1810 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001811
John McCall33ddac02011-01-19 10:06:00 +00001812 IncompleteArrayTypes.InsertNode(newType, insertPos);
1813 Types.push_back(newType);
1814 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001815}
1816
Steve Naroff91fcddb2007-07-18 18:00:27 +00001817/// getVectorType - Return the unique reference to a vector type of
1818/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001819QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001820 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001821 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001822
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001823 // Check if we've already instantiated a vector of this type.
1824 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001825 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001826
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001827 void *InsertPos = 0;
1828 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1829 return QualType(VTP, 0);
1830
1831 // If the element type isn't canonical, this won't be a canonical type either,
1832 // so fill in the canonical type field.
1833 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001834 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001835 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001836
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001837 // Get the new insert position for the node we care about.
1838 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001839 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001840 }
John McCall90d1c2d2009-09-24 23:30:46 +00001841 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001842 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001843 VectorTypes.InsertNode(New, InsertPos);
1844 Types.push_back(New);
1845 return QualType(New, 0);
1846}
1847
Nate Begemance4d7fc2008-04-18 23:10:10 +00001848/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001849/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001850QualType
1851ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall33ddac02011-01-19 10:06:00 +00001852 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001853
Steve Naroff91fcddb2007-07-18 18:00:27 +00001854 // Check if we've already instantiated a vector of this type.
1855 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001856 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001857 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001858 void *InsertPos = 0;
1859 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1860 return QualType(VTP, 0);
1861
1862 // If the element type isn't canonical, this won't be a canonical type either,
1863 // so fill in the canonical type field.
1864 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001865 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001866 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001867
Steve Naroff91fcddb2007-07-18 18:00:27 +00001868 // Get the new insert position for the node we care about.
1869 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001870 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001871 }
John McCall90d1c2d2009-09-24 23:30:46 +00001872 ExtVectorType *New = new (*this, TypeAlignment)
1873 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001874 VectorTypes.InsertNode(New, InsertPos);
1875 Types.push_back(New);
1876 return QualType(New, 0);
1877}
1878
Jay Foad39c79802011-01-12 09:06:06 +00001879QualType
1880ASTContext::getDependentSizedExtVectorType(QualType vecType,
1881 Expr *SizeExpr,
1882 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001883 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001884 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001885 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001886
Douglas Gregor352169a2009-07-31 03:54:25 +00001887 void *InsertPos = 0;
1888 DependentSizedExtVectorType *Canon
1889 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1890 DependentSizedExtVectorType *New;
1891 if (Canon) {
1892 // We already have a canonical version of this array type; use it as
1893 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001894 New = new (*this, TypeAlignment)
1895 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1896 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001897 } else {
1898 QualType CanonVecTy = getCanonicalType(vecType);
1899 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001900 New = new (*this, TypeAlignment)
1901 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1902 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001903
1904 DependentSizedExtVectorType *CanonCheck
1905 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1906 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1907 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001908 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1909 } else {
1910 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1911 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001912 New = new (*this, TypeAlignment)
1913 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001914 }
1915 }
Mike Stump11289f42009-09-09 15:08:12 +00001916
Douglas Gregor758a8692009-06-17 21:51:59 +00001917 Types.push_back(New);
1918 return QualType(New, 0);
1919}
1920
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001921/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001922///
Jay Foad39c79802011-01-12 09:06:06 +00001923QualType
1924ASTContext::getFunctionNoProtoType(QualType ResultTy,
1925 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00001926 const CallingConv DefaultCC = Info.getCC();
1927 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1928 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001929 // Unique functions, to guarantee there is only one function of a particular
1930 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001931 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001932 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001933
Chris Lattner47955de2007-01-27 08:37:20 +00001934 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001935 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001936 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001937 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001938
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001939 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001940 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001941 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001942 Canonical =
1943 getFunctionNoProtoType(getCanonicalType(ResultTy),
1944 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001945
Chris Lattner47955de2007-01-27 08:37:20 +00001946 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001947 FunctionNoProtoType *NewIP =
1948 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001949 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001950 }
Mike Stump11289f42009-09-09 15:08:12 +00001951
Roman Divacky65b88cd2011-03-01 17:40:53 +00001952 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00001953 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00001954 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00001955 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001956 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001957 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001958}
1959
1960/// getFunctionType - Return a normal function type with a typed argument
1961/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001962QualType
1963ASTContext::getFunctionType(QualType ResultTy,
1964 const QualType *ArgArray, unsigned NumArgs,
1965 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001966 // Unique functions, to guarantee there is only one function of a particular
1967 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001968 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00001969 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001970
1971 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001972 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001973 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001974 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001975
1976 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00001977 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001978 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001979 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001980 isCanonical = false;
1981
Roman Divacky65b88cd2011-03-01 17:40:53 +00001982 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
1983 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1984 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00001985
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001986 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001987 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001988 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001989 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001990 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001991 CanonicalArgs.reserve(NumArgs);
1992 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001993 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001994
John McCalldb40c7f2010-12-14 08:05:40 +00001995 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00001996 CanonicalEPI.ExceptionSpecType = EST_None;
1997 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00001998 CanonicalEPI.ExtInfo
1999 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2000
Chris Lattner76a00cf2008-04-06 22:59:24 +00002001 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002002 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002003 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002004
Chris Lattnerfd4de792007-01-27 01:15:32 +00002005 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002006 FunctionProtoType *NewIP =
2007 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002008 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002009 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002010
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002011 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002012 // for two variable size arrays (for parameter and exception types) at the
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002013 // end of them. Instead of the exception types, there could be a noexcept
2014 // expression and a context pointer.
John McCalldb40c7f2010-12-14 08:05:40 +00002015 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002016 NumArgs * sizeof(QualType);
2017 if (EPI.ExceptionSpecType == EST_Dynamic)
2018 Size += EPI.NumExceptions * sizeof(QualType);
2019 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002020 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002021 }
John McCalldb40c7f2010-12-14 08:05:40 +00002022 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002023 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2024 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002025 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002026 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002027 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002028 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002029}
Chris Lattneref51c202006-11-10 07:17:23 +00002030
John McCalle78aac42010-03-10 03:28:59 +00002031#ifndef NDEBUG
2032static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2033 if (!isa<CXXRecordDecl>(D)) return false;
2034 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2035 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2036 return true;
2037 if (RD->getDescribedClassTemplate() &&
2038 !isa<ClassTemplateSpecializationDecl>(RD))
2039 return true;
2040 return false;
2041}
2042#endif
2043
2044/// getInjectedClassNameType - Return the unique reference to the
2045/// injected class name type for the specified templated declaration.
2046QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002047 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002048 assert(NeedsInjectedClassNameType(Decl));
2049 if (Decl->TypeForDecl) {
2050 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002051 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002052 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2053 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2054 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2055 } else {
John McCall424cec92011-01-19 06:33:43 +00002056 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002057 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002058 Decl->TypeForDecl = newType;
2059 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002060 }
2061 return QualType(Decl->TypeForDecl, 0);
2062}
2063
Douglas Gregor83a586e2008-04-13 21:07:44 +00002064/// getTypeDeclType - Return the unique reference to the type for the
2065/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002066QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002067 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002068 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002069
Richard Smithdda56e42011-04-15 14:24:37 +00002070 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002071 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002072
John McCall96f0b5f2010-03-10 06:48:02 +00002073 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2074 "Template type parameter types are always available.");
2075
John McCall81e38502010-02-16 03:57:14 +00002076 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002077 assert(!Record->getPreviousDeclaration() &&
2078 "struct/union has previous declaration");
2079 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002080 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002081 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002082 assert(!Enum->getPreviousDeclaration() &&
2083 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002084 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002085 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002086 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002087 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2088 Decl->TypeForDecl = newType;
2089 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002090 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002091 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002092
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002093 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002094}
2095
Chris Lattner32d920b2007-01-26 02:01:53 +00002096/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002097/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002098QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002099ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2100 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002101 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002102
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002103 if (Canonical.isNull())
2104 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002105 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002106 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002107 Decl->TypeForDecl = newType;
2108 Types.push_back(newType);
2109 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002110}
2111
Jay Foad39c79802011-01-12 09:06:06 +00002112QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002113 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2114
2115 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2116 if (PrevDecl->TypeForDecl)
2117 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2118
John McCall424cec92011-01-19 06:33:43 +00002119 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2120 Decl->TypeForDecl = newType;
2121 Types.push_back(newType);
2122 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002123}
2124
Jay Foad39c79802011-01-12 09:06:06 +00002125QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002126 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2127
2128 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2129 if (PrevDecl->TypeForDecl)
2130 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2131
John McCall424cec92011-01-19 06:33:43 +00002132 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2133 Decl->TypeForDecl = newType;
2134 Types.push_back(newType);
2135 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002136}
2137
John McCall81904512011-01-06 01:58:22 +00002138QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2139 QualType modifiedType,
2140 QualType equivalentType) {
2141 llvm::FoldingSetNodeID id;
2142 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2143
2144 void *insertPos = 0;
2145 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2146 if (type) return QualType(type, 0);
2147
2148 QualType canon = getCanonicalType(equivalentType);
2149 type = new (*this, TypeAlignment)
2150 AttributedType(canon, attrKind, modifiedType, equivalentType);
2151
2152 Types.push_back(type);
2153 AttributedTypes.InsertNode(type, insertPos);
2154
2155 return QualType(type, 0);
2156}
2157
2158
John McCallcebee162009-10-18 09:09:24 +00002159/// \brief Retrieve a substitution-result type.
2160QualType
2161ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002162 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002163 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002164 && "replacement types must always be canonical");
2165
2166 llvm::FoldingSetNodeID ID;
2167 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2168 void *InsertPos = 0;
2169 SubstTemplateTypeParmType *SubstParm
2170 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2171
2172 if (!SubstParm) {
2173 SubstParm = new (*this, TypeAlignment)
2174 SubstTemplateTypeParmType(Parm, Replacement);
2175 Types.push_back(SubstParm);
2176 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2177 }
2178
2179 return QualType(SubstParm, 0);
2180}
2181
Douglas Gregorada4b792011-01-14 02:55:32 +00002182/// \brief Retrieve a
2183QualType ASTContext::getSubstTemplateTypeParmPackType(
2184 const TemplateTypeParmType *Parm,
2185 const TemplateArgument &ArgPack) {
2186#ifndef NDEBUG
2187 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2188 PEnd = ArgPack.pack_end();
2189 P != PEnd; ++P) {
2190 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2191 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2192 }
2193#endif
2194
2195 llvm::FoldingSetNodeID ID;
2196 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2197 void *InsertPos = 0;
2198 if (SubstTemplateTypeParmPackType *SubstParm
2199 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2200 return QualType(SubstParm, 0);
2201
2202 QualType Canon;
2203 if (!Parm->isCanonicalUnqualified()) {
2204 Canon = getCanonicalType(QualType(Parm, 0));
2205 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2206 ArgPack);
2207 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2208 }
2209
2210 SubstTemplateTypeParmPackType *SubstParm
2211 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2212 ArgPack);
2213 Types.push_back(SubstParm);
2214 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2215 return QualType(SubstParm, 0);
2216}
2217
Douglas Gregoreff93e02009-02-05 23:33:38 +00002218/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002219/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002220/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002221QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002222 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002223 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002224 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002225 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002226 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002227 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002228 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2229
2230 if (TypeParm)
2231 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002232
Chandler Carruth08836322011-05-01 00:51:33 +00002233 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002234 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002235 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002236
2237 TemplateTypeParmType *TypeCheck
2238 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2239 assert(!TypeCheck && "Template type parameter canonical type broken");
2240 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002241 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002242 TypeParm = new (*this, TypeAlignment)
2243 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002244
2245 Types.push_back(TypeParm);
2246 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2247
2248 return QualType(TypeParm, 0);
2249}
2250
John McCalle78aac42010-03-10 03:28:59 +00002251TypeSourceInfo *
2252ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2253 SourceLocation NameLoc,
2254 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002255 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002256 assert(!Name.getAsDependentTemplateName() &&
2257 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002258 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002259
2260 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2261 TemplateSpecializationTypeLoc TL
2262 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2263 TL.setTemplateNameLoc(NameLoc);
2264 TL.setLAngleLoc(Args.getLAngleLoc());
2265 TL.setRAngleLoc(Args.getRAngleLoc());
2266 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2267 TL.setArgLocInfo(i, Args[i].getLocInfo());
2268 return DI;
2269}
2270
Mike Stump11289f42009-09-09 15:08:12 +00002271QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002272ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002273 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002274 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002275 assert(!Template.getAsDependentTemplateName() &&
2276 "No dependent template names here!");
2277
John McCall6b51f282009-11-23 01:53:49 +00002278 unsigned NumArgs = Args.size();
2279
John McCall0ad16662009-10-29 08:12:44 +00002280 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2281 ArgVec.reserve(NumArgs);
2282 for (unsigned i = 0; i != NumArgs; ++i)
2283 ArgVec.push_back(Args[i].getArgument());
2284
John McCall2408e322010-04-27 00:57:59 +00002285 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002286 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002287}
2288
2289QualType
2290ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002291 const TemplateArgument *Args,
2292 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002293 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002294 assert(!Template.getAsDependentTemplateName() &&
2295 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002296 // Look through qualified template names.
2297 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2298 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002299
Richard Smith3f1b5d02011-05-05 21:57:07 +00002300 bool isTypeAlias =
2301 Template.getAsTemplateDecl() &&
2302 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2303
2304 QualType CanonType;
2305 if (!Underlying.isNull())
2306 CanonType = getCanonicalType(Underlying);
2307 else {
2308 assert(!isTypeAlias &&
2309 "Underlying type for template alias must be computed by caller");
2310 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2311 NumArgs);
2312 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002313
Douglas Gregora8e02e72009-07-28 23:00:59 +00002314 // Allocate the (non-canonical) template specialization type, but don't
2315 // try to unique it: these types typically have location information that
2316 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002317 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2318 sizeof(TemplateArgument) * NumArgs +
2319 (isTypeAlias ? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002320 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002321 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002322 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002323 Args, NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002324 CanonType,
2325 isTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002326
Douglas Gregor8bf42052009-02-09 18:46:07 +00002327 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002328 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002329}
2330
Mike Stump11289f42009-09-09 15:08:12 +00002331QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002332ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2333 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002334 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002335 assert(!Template.getAsDependentTemplateName() &&
2336 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002337 assert((!Template.getAsTemplateDecl() ||
2338 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2339 "Underlying type for template alias must be computed by caller");
2340
Douglas Gregore29139c2011-03-03 17:04:51 +00002341 // Look through qualified template names.
2342 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2343 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002344
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002345 // Build the canonical template specialization type.
2346 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2347 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2348 CanonArgs.reserve(NumArgs);
2349 for (unsigned I = 0; I != NumArgs; ++I)
2350 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2351
2352 // Determine whether this canonical template specialization type already
2353 // exists.
2354 llvm::FoldingSetNodeID ID;
2355 TemplateSpecializationType::Profile(ID, CanonTemplate,
2356 CanonArgs.data(), NumArgs, *this);
2357
2358 void *InsertPos = 0;
2359 TemplateSpecializationType *Spec
2360 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2361
2362 if (!Spec) {
2363 // Allocate a new canonical template specialization type.
2364 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2365 sizeof(TemplateArgument) * NumArgs),
2366 TypeAlignment);
2367 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2368 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002369 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002370 Types.push_back(Spec);
2371 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2372 }
2373
2374 assert(Spec->isDependentType() &&
2375 "Non-dependent template-id type must have a canonical type");
2376 return QualType(Spec, 0);
2377}
2378
2379QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002380ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2381 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002382 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002383 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002384 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002385
2386 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002387 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002388 if (T)
2389 return QualType(T, 0);
2390
Douglas Gregorc42075a2010-02-04 18:10:26 +00002391 QualType Canon = NamedType;
2392 if (!Canon.isCanonical()) {
2393 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002394 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2395 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002396 (void)CheckT;
2397 }
2398
Abramo Bagnara6150c882010-05-11 21:36:43 +00002399 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002400 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002401 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002402 return QualType(T, 0);
2403}
2404
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002405QualType
Jay Foad39c79802011-01-12 09:06:06 +00002406ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002407 llvm::FoldingSetNodeID ID;
2408 ParenType::Profile(ID, InnerType);
2409
2410 void *InsertPos = 0;
2411 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2412 if (T)
2413 return QualType(T, 0);
2414
2415 QualType Canon = InnerType;
2416 if (!Canon.isCanonical()) {
2417 Canon = getCanonicalType(InnerType);
2418 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2419 assert(!CheckT && "Paren canonical type broken");
2420 (void)CheckT;
2421 }
2422
2423 T = new (*this) ParenType(InnerType, Canon);
2424 Types.push_back(T);
2425 ParenTypes.InsertNode(T, InsertPos);
2426 return QualType(T, 0);
2427}
2428
Douglas Gregor02085352010-03-31 20:19:30 +00002429QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2430 NestedNameSpecifier *NNS,
2431 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002432 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002433 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2434
2435 if (Canon.isNull()) {
2436 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002437 ElaboratedTypeKeyword CanonKeyword = Keyword;
2438 if (Keyword == ETK_None)
2439 CanonKeyword = ETK_Typename;
2440
2441 if (CanonNNS != NNS || CanonKeyword != Keyword)
2442 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002443 }
2444
2445 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002446 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002447
2448 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002449 DependentNameType *T
2450 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002451 if (T)
2452 return QualType(T, 0);
2453
Douglas Gregor02085352010-03-31 20:19:30 +00002454 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002455 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002456 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002457 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002458}
2459
Mike Stump11289f42009-09-09 15:08:12 +00002460QualType
John McCallc392f372010-06-11 00:33:02 +00002461ASTContext::getDependentTemplateSpecializationType(
2462 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002463 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002464 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002465 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002466 // TODO: avoid this copy
2467 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2468 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2469 ArgCopy.push_back(Args[I].getArgument());
2470 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2471 ArgCopy.size(),
2472 ArgCopy.data());
2473}
2474
2475QualType
2476ASTContext::getDependentTemplateSpecializationType(
2477 ElaboratedTypeKeyword Keyword,
2478 NestedNameSpecifier *NNS,
2479 const IdentifierInfo *Name,
2480 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002481 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002482 assert((!NNS || NNS->isDependent()) &&
2483 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002484
Douglas Gregorc42075a2010-02-04 18:10:26 +00002485 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002486 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2487 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002488
2489 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002490 DependentTemplateSpecializationType *T
2491 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002492 if (T)
2493 return QualType(T, 0);
2494
John McCallc392f372010-06-11 00:33:02 +00002495 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002496
John McCallc392f372010-06-11 00:33:02 +00002497 ElaboratedTypeKeyword CanonKeyword = Keyword;
2498 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2499
2500 bool AnyNonCanonArgs = false;
2501 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2502 for (unsigned I = 0; I != NumArgs; ++I) {
2503 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2504 if (!CanonArgs[I].structurallyEquals(Args[I]))
2505 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002506 }
2507
John McCallc392f372010-06-11 00:33:02 +00002508 QualType Canon;
2509 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2510 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2511 Name, NumArgs,
2512 CanonArgs.data());
2513
2514 // Find the insert position again.
2515 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2516 }
2517
2518 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2519 sizeof(TemplateArgument) * NumArgs),
2520 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002521 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002522 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002523 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002524 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002525 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002526}
2527
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002528QualType ASTContext::getPackExpansionType(QualType Pattern,
2529 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002530 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002531 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002532
2533 assert(Pattern->containsUnexpandedParameterPack() &&
2534 "Pack expansions must expand one or more parameter packs");
2535 void *InsertPos = 0;
2536 PackExpansionType *T
2537 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2538 if (T)
2539 return QualType(T, 0);
2540
2541 QualType Canon;
2542 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002543 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002544
2545 // Find the insert position again.
2546 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2547 }
2548
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002549 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002550 Types.push_back(T);
2551 PackExpansionTypes.InsertNode(T, InsertPos);
2552 return QualType(T, 0);
2553}
2554
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002555/// CmpProtocolNames - Comparison predicate for sorting protocols
2556/// alphabetically.
2557static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2558 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002559 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002560}
2561
John McCall8b07ec22010-05-15 11:32:37 +00002562static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002563 unsigned NumProtocols) {
2564 if (NumProtocols == 0) return true;
2565
2566 for (unsigned i = 1; i != NumProtocols; ++i)
2567 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2568 return false;
2569 return true;
2570}
2571
2572static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002573 unsigned &NumProtocols) {
2574 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002575
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002576 // Sort protocols, keyed by name.
2577 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2578
2579 // Remove duplicates.
2580 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2581 NumProtocols = ProtocolsEnd-Protocols;
2582}
2583
John McCall8b07ec22010-05-15 11:32:37 +00002584QualType ASTContext::getObjCObjectType(QualType BaseType,
2585 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002586 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002587 // If the base type is an interface and there aren't any protocols
2588 // to add, then the interface type will do just fine.
2589 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2590 return BaseType;
2591
2592 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002593 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002594 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002595 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002596 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2597 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002598
John McCall8b07ec22010-05-15 11:32:37 +00002599 // Build the canonical type, which has the canonical base type and
2600 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002601 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002602 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2603 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2604 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002605 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2606 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002607 unsigned UniqueCount = NumProtocols;
2608
John McCallfc93cf92009-10-22 22:37:11 +00002609 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002610 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2611 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002612 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002613 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2614 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002615 }
2616
2617 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002618 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2619 }
2620
2621 unsigned Size = sizeof(ObjCObjectTypeImpl);
2622 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2623 void *Mem = Allocate(Size, TypeAlignment);
2624 ObjCObjectTypeImpl *T =
2625 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2626
2627 Types.push_back(T);
2628 ObjCObjectTypes.InsertNode(T, InsertPos);
2629 return QualType(T, 0);
2630}
2631
2632/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2633/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002634QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002635 llvm::FoldingSetNodeID ID;
2636 ObjCObjectPointerType::Profile(ID, ObjectT);
2637
2638 void *InsertPos = 0;
2639 if (ObjCObjectPointerType *QT =
2640 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2641 return QualType(QT, 0);
2642
2643 // Find the canonical object type.
2644 QualType Canonical;
2645 if (!ObjectT.isCanonical()) {
2646 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2647
2648 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002649 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2650 }
2651
Douglas Gregorf85bee62010-02-08 22:59:26 +00002652 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002653 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2654 ObjCObjectPointerType *QType =
2655 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002656
Steve Narofffb4330f2009-06-17 22:40:22 +00002657 Types.push_back(QType);
2658 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002659 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002660}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002661
Douglas Gregor1c283312010-08-11 12:19:30 +00002662/// getObjCInterfaceType - Return the unique reference to the type for the
2663/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002664QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002665 if (Decl->TypeForDecl)
2666 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002667
Douglas Gregor1c283312010-08-11 12:19:30 +00002668 // FIXME: redeclarations?
2669 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2670 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2671 Decl->TypeForDecl = T;
2672 Types.push_back(T);
2673 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002674}
2675
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002676/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2677/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002678/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002679/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002680/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002681QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002682 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002683 if (tofExpr->isTypeDependent()) {
2684 llvm::FoldingSetNodeID ID;
2685 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002686
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002687 void *InsertPos = 0;
2688 DependentTypeOfExprType *Canon
2689 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2690 if (Canon) {
2691 // We already have a "canonical" version of an identical, dependent
2692 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002693 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002694 QualType((TypeOfExprType*)Canon, 0));
2695 }
2696 else {
2697 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002698 Canon
2699 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002700 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2701 toe = Canon;
2702 }
2703 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002704 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002705 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002706 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002707 Types.push_back(toe);
2708 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002709}
2710
Steve Naroffa773cd52007-08-01 18:02:17 +00002711/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2712/// TypeOfType AST's. The only motivation to unique these nodes would be
2713/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002714/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002715/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002716QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002717 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002718 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002719 Types.push_back(tot);
2720 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002721}
2722
Anders Carlssonad6bd352009-06-24 21:24:56 +00002723/// getDecltypeForExpr - Given an expr, will return the decltype for that
2724/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002725static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002726 if (e->isTypeDependent())
2727 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002728
Anders Carlssonad6bd352009-06-24 21:24:56 +00002729 // If e is an id expression or a class member access, decltype(e) is defined
2730 // as the type of the entity named by e.
2731 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2732 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2733 return VD->getType();
2734 }
2735 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2736 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2737 return FD->getType();
2738 }
2739 // If e is a function call or an invocation of an overloaded operator,
2740 // (parentheses around e are ignored), decltype(e) is defined as the
2741 // return type of that function.
2742 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2743 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002744
Anders Carlssonad6bd352009-06-24 21:24:56 +00002745 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002746
2747 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002748 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002749 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002750 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002751
Anders Carlssonad6bd352009-06-24 21:24:56 +00002752 return T;
2753}
2754
Anders Carlsson81df7b82009-06-24 19:06:50 +00002755/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2756/// DecltypeType AST's. The only motivation to unique these nodes would be
2757/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002758/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002759/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002760QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002761 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002762 if (e->isTypeDependent()) {
2763 llvm::FoldingSetNodeID ID;
2764 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002765
Douglas Gregora21f6c32009-07-30 23:36:40 +00002766 void *InsertPos = 0;
2767 DependentDecltypeType *Canon
2768 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2769 if (Canon) {
2770 // We already have a "canonical" version of an equivalent, dependent
2771 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002772 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002773 QualType((DecltypeType*)Canon, 0));
2774 }
2775 else {
2776 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002777 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002778 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2779 dt = Canon;
2780 }
2781 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002782 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002783 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002784 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002785 Types.push_back(dt);
2786 return QualType(dt, 0);
2787}
2788
Richard Smithb2bc2e62011-02-21 20:05:19 +00002789/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002790QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002791 void *InsertPos = 0;
2792 if (!DeducedType.isNull()) {
2793 // Look in the folding set for an existing type.
2794 llvm::FoldingSetNodeID ID;
2795 AutoType::Profile(ID, DeducedType);
2796 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2797 return QualType(AT, 0);
2798 }
2799
2800 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2801 Types.push_back(AT);
2802 if (InsertPos)
2803 AutoTypes.InsertNode(AT, InsertPos);
2804 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002805}
2806
Richard Smith02e85f32011-04-14 22:09:26 +00002807/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2808QualType ASTContext::getAutoDeductType() const {
2809 if (AutoDeductTy.isNull())
2810 AutoDeductTy = getAutoType(QualType());
2811 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2812 return AutoDeductTy;
2813}
2814
2815/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2816QualType ASTContext::getAutoRRefDeductType() const {
2817 if (AutoRRefDeductTy.isNull())
2818 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2819 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2820 return AutoRRefDeductTy;
2821}
2822
Chris Lattnerfb072462007-01-23 05:45:31 +00002823/// getTagDeclType - Return the unique reference to the type for the
2824/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002825QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002826 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002827 // FIXME: What is the design on getTagDeclType when it requires casting
2828 // away const? mutable?
2829 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002830}
2831
Mike Stump11289f42009-09-09 15:08:12 +00002832/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2833/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2834/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002835CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002836 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002837}
Chris Lattnerfb072462007-01-23 05:45:31 +00002838
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002839/// getSignedWCharType - Return the type of "signed wchar_t".
2840/// Used when in C++, as a GCC extension.
2841QualType ASTContext::getSignedWCharType() const {
2842 // FIXME: derive from "Target" ?
2843 return WCharTy;
2844}
2845
2846/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2847/// Used when in C++, as a GCC extension.
2848QualType ASTContext::getUnsignedWCharType() const {
2849 // FIXME: derive from "Target" ?
2850 return UnsignedIntTy;
2851}
2852
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002853/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2854/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2855QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002856 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002857}
2858
Chris Lattnera21ad802008-04-02 05:18:44 +00002859//===----------------------------------------------------------------------===//
2860// Type Operators
2861//===----------------------------------------------------------------------===//
2862
Jay Foad39c79802011-01-12 09:06:06 +00002863CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002864 // Push qualifiers into arrays, and then discard any remaining
2865 // qualifiers.
2866 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002867 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002868 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002869 QualType Result;
2870 if (isa<ArrayType>(Ty)) {
2871 Result = getArrayDecayedType(QualType(Ty,0));
2872 } else if (isa<FunctionType>(Ty)) {
2873 Result = getPointerType(QualType(Ty, 0));
2874 } else {
2875 Result = QualType(Ty, 0);
2876 }
2877
2878 return CanQualType::CreateUnsafe(Result);
2879}
2880
Chris Lattner7adf0762008-08-04 07:31:14 +00002881
John McCall6c9dd522011-01-18 07:41:22 +00002882QualType ASTContext::getUnqualifiedArrayType(QualType type,
2883 Qualifiers &quals) {
2884 SplitQualType splitType = type.getSplitUnqualifiedType();
2885
2886 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2887 // the unqualified desugared type and then drops it on the floor.
2888 // We then have to strip that sugar back off with
2889 // getUnqualifiedDesugaredType(), which is silly.
2890 const ArrayType *AT =
2891 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2892
2893 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002894 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002895 quals = splitType.second;
2896 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002897 }
2898
John McCall6c9dd522011-01-18 07:41:22 +00002899 // Otherwise, recurse on the array's element type.
2900 QualType elementType = AT->getElementType();
2901 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2902
2903 // If that didn't change the element type, AT has no qualifiers, so we
2904 // can just use the results in splitType.
2905 if (elementType == unqualElementType) {
2906 assert(quals.empty()); // from the recursive call
2907 quals = splitType.second;
2908 return QualType(splitType.first, 0);
2909 }
2910
2911 // Otherwise, add in the qualifiers from the outermost type, then
2912 // build the type back up.
2913 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002914
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002915 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002916 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002917 CAT->getSizeModifier(), 0);
2918 }
2919
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002920 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002921 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002922 }
2923
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002924 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002925 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002926 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002927 VAT->getSizeModifier(),
2928 VAT->getIndexTypeCVRQualifiers(),
2929 VAT->getBracketsRange());
2930 }
2931
2932 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002933 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002934 DSAT->getSizeModifier(), 0,
2935 SourceRange());
2936}
2937
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002938/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2939/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2940/// they point to and return true. If T1 and T2 aren't pointer types
2941/// or pointer-to-member types, or if they are not similar at this
2942/// level, returns false and leaves T1 and T2 unchanged. Top-level
2943/// qualifiers on T1 and T2 are ignored. This function will typically
2944/// be called in a loop that successively "unwraps" pointer and
2945/// pointer-to-member types to compare them at each level.
2946bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2947 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2948 *T2PtrType = T2->getAs<PointerType>();
2949 if (T1PtrType && T2PtrType) {
2950 T1 = T1PtrType->getPointeeType();
2951 T2 = T2PtrType->getPointeeType();
2952 return true;
2953 }
2954
2955 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2956 *T2MPType = T2->getAs<MemberPointerType>();
2957 if (T1MPType && T2MPType &&
2958 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2959 QualType(T2MPType->getClass(), 0))) {
2960 T1 = T1MPType->getPointeeType();
2961 T2 = T2MPType->getPointeeType();
2962 return true;
2963 }
2964
2965 if (getLangOptions().ObjC1) {
2966 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2967 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2968 if (T1OPType && T2OPType) {
2969 T1 = T1OPType->getPointeeType();
2970 T2 = T2OPType->getPointeeType();
2971 return true;
2972 }
2973 }
2974
2975 // FIXME: Block pointers, too?
2976
2977 return false;
2978}
2979
Jay Foad39c79802011-01-12 09:06:06 +00002980DeclarationNameInfo
2981ASTContext::getNameForTemplate(TemplateName Name,
2982 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002983 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002984 // DNInfo work in progress: CHECKME: what about DNLoc?
2985 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2986
John McCall847e2a12009-11-24 18:42:40 +00002987 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002988 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002989 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002990 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2991 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002992 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002993 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2994 // DNInfo work in progress: FIXME: source locations?
2995 DeclarationNameLoc DNLoc;
2996 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2997 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2998 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002999 }
3000 }
3001
John McCalld28ae272009-12-02 08:04:21 +00003002 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3003 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003004 // DNInfo work in progress: CHECKME: what about DNLoc?
3005 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003006}
3007
Jay Foad39c79802011-01-12 09:06:06 +00003008TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003009 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3010 if (TemplateTemplateParmDecl *TTP
3011 = dyn_cast<TemplateTemplateParmDecl>(Template))
3012 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3013
3014 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003015 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003016 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003017
Douglas Gregor5590be02011-01-15 06:45:20 +00003018 if (SubstTemplateTemplateParmPackStorage *SubstPack
3019 = Name.getAsSubstTemplateTemplateParmPack()) {
3020 TemplateTemplateParmDecl *CanonParam
3021 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
3022 TemplateArgument CanonArgPack
3023 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
3024 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
3025 }
3026
John McCalld28ae272009-12-02 08:04:21 +00003027 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00003028
Douglas Gregor6bc50582009-05-07 06:41:52 +00003029 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3030 assert(DTN && "Non-dependent template names must refer to template decls.");
3031 return DTN->CanonicalTemplateName;
3032}
3033
Douglas Gregoradee3e32009-11-11 23:06:43 +00003034bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3035 X = getCanonicalTemplateName(X);
3036 Y = getCanonicalTemplateName(Y);
3037 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3038}
3039
Mike Stump11289f42009-09-09 15:08:12 +00003040TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003041ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003042 switch (Arg.getKind()) {
3043 case TemplateArgument::Null:
3044 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003045
Douglas Gregora8e02e72009-07-28 23:00:59 +00003046 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003047 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003048
Douglas Gregora8e02e72009-07-28 23:00:59 +00003049 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003050 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003051
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003052 case TemplateArgument::Template:
3053 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003054
3055 case TemplateArgument::TemplateExpansion:
3056 return TemplateArgument(getCanonicalTemplateName(
3057 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003058 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003059
Douglas Gregora8e02e72009-07-28 23:00:59 +00003060 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003061 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003062 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003063
Douglas Gregora8e02e72009-07-28 23:00:59 +00003064 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003065 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003066
Douglas Gregora8e02e72009-07-28 23:00:59 +00003067 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003068 if (Arg.pack_size() == 0)
3069 return Arg;
3070
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003071 TemplateArgument *CanonArgs
3072 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003073 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003074 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003075 AEnd = Arg.pack_end();
3076 A != AEnd; (void)++A, ++Idx)
3077 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003078
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003079 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003080 }
3081 }
3082
3083 // Silence GCC warning
3084 assert(false && "Unhandled template argument kind");
3085 return TemplateArgument();
3086}
3087
Douglas Gregor333489b2009-03-27 23:10:48 +00003088NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003089ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003090 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003091 return 0;
3092
3093 switch (NNS->getKind()) {
3094 case NestedNameSpecifier::Identifier:
3095 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003096 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003097 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3098 NNS->getAsIdentifier());
3099
3100 case NestedNameSpecifier::Namespace:
3101 // A namespace is canonical; build a nested-name-specifier with
3102 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003103 return NestedNameSpecifier::Create(*this, 0,
3104 NNS->getAsNamespace()->getOriginalNamespace());
3105
3106 case NestedNameSpecifier::NamespaceAlias:
3107 // A namespace is canonical; build a nested-name-specifier with
3108 // this namespace and no prefix.
3109 return NestedNameSpecifier::Create(*this, 0,
3110 NNS->getAsNamespaceAlias()->getNamespace()
3111 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003112
3113 case NestedNameSpecifier::TypeSpec:
3114 case NestedNameSpecifier::TypeSpecWithTemplate: {
3115 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003116
3117 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3118 // break it apart into its prefix and identifier, then reconsititute those
3119 // as the canonical nested-name-specifier. This is required to canonicalize
3120 // a dependent nested-name-specifier involving typedefs of dependent-name
3121 // types, e.g.,
3122 // typedef typename T::type T1;
3123 // typedef typename T1::type T2;
3124 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3125 NestedNameSpecifier *Prefix
3126 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3127 return NestedNameSpecifier::Create(*this, Prefix,
3128 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3129 }
3130
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003131 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003132 if (const DependentTemplateSpecializationType *DTST
3133 = T->getAs<DependentTemplateSpecializationType>()) {
3134 NestedNameSpecifier *Prefix
3135 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003136
3137 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3138 Prefix, DTST->getIdentifier(),
3139 DTST->getNumArgs(),
3140 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003141 T = getCanonicalType(T);
3142 }
3143
John McCall33ddac02011-01-19 10:06:00 +00003144 return NestedNameSpecifier::Create(*this, 0, false,
3145 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003146 }
3147
3148 case NestedNameSpecifier::Global:
3149 // The global specifier is canonical and unique.
3150 return NNS;
3151 }
3152
3153 // Required to silence a GCC warning
3154 return 0;
3155}
3156
Chris Lattner7adf0762008-08-04 07:31:14 +00003157
Jay Foad39c79802011-01-12 09:06:06 +00003158const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003159 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003160 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003161 // Handle the common positive case fast.
3162 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3163 return AT;
3164 }
Mike Stump11289f42009-09-09 15:08:12 +00003165
John McCall8ccfcb52009-09-24 19:53:00 +00003166 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003167 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003168 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003169
John McCall8ccfcb52009-09-24 19:53:00 +00003170 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003171 // implements C99 6.7.3p8: "If the specification of an array type includes
3172 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003173
Chris Lattner7adf0762008-08-04 07:31:14 +00003174 // If we get here, we either have type qualifiers on the type, or we have
3175 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003176 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003177
John McCall33ddac02011-01-19 10:06:00 +00003178 SplitQualType split = T.getSplitDesugaredType();
3179 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003180
Chris Lattner7adf0762008-08-04 07:31:14 +00003181 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003182 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3183 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003184 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003185
Chris Lattner7adf0762008-08-04 07:31:14 +00003186 // Otherwise, we have an array and we have qualifiers on it. Push the
3187 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003188 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003189
Chris Lattner7adf0762008-08-04 07:31:14 +00003190 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3191 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3192 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003193 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003194 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3195 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3196 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003197 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003198
Mike Stump11289f42009-09-09 15:08:12 +00003199 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003200 = dyn_cast<DependentSizedArrayType>(ATy))
3201 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003202 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003203 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003204 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003205 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003206 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003207
Chris Lattner7adf0762008-08-04 07:31:14 +00003208 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003209 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003210 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003211 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003212 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003213 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003214}
3215
Chris Lattnera21ad802008-04-02 05:18:44 +00003216/// getArrayDecayedType - Return the properly qualified result of decaying the
3217/// specified array type to a pointer. This operation is non-trivial when
3218/// handling typedefs etc. The canonical type of "T" must be an array type,
3219/// this returns a pointer to a properly qualified element of the array.
3220///
3221/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003222QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003223 // Get the element type with 'getAsArrayType' so that we don't lose any
3224 // typedefs in the element type of the array. This also handles propagation
3225 // of type qualifiers from the array type into the element type if present
3226 // (C99 6.7.3p8).
3227 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3228 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003229
Chris Lattner7adf0762008-08-04 07:31:14 +00003230 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003231
3232 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003233 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003234}
3235
John McCall33ddac02011-01-19 10:06:00 +00003236QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3237 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003238}
3239
John McCall33ddac02011-01-19 10:06:00 +00003240QualType ASTContext::getBaseElementType(QualType type) const {
3241 Qualifiers qs;
3242 while (true) {
3243 SplitQualType split = type.getSplitDesugaredType();
3244 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3245 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003246
John McCall33ddac02011-01-19 10:06:00 +00003247 type = array->getElementType();
3248 qs.addConsistentQualifiers(split.second);
3249 }
Mike Stump11289f42009-09-09 15:08:12 +00003250
John McCall33ddac02011-01-19 10:06:00 +00003251 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003252}
3253
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003254/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003255uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003256ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3257 uint64_t ElementCount = 1;
3258 do {
3259 ElementCount *= CA->getSize().getZExtValue();
3260 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3261 } while (CA);
3262 return ElementCount;
3263}
3264
Steve Naroff0af91202007-04-27 21:51:21 +00003265/// getFloatingRank - Return a relative rank for floating point types.
3266/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003267static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003268 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003269 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003270
John McCall9dd450b2009-09-21 23:43:11 +00003271 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3272 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003273 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003274 case BuiltinType::Float: return FloatRank;
3275 case BuiltinType::Double: return DoubleRank;
3276 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003277 }
3278}
3279
Mike Stump11289f42009-09-09 15:08:12 +00003280/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3281/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003282/// 'typeDomain' is a real floating point or complex type.
3283/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003284QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3285 QualType Domain) const {
3286 FloatingRank EltRank = getFloatingRank(Size);
3287 if (Domain->isComplexType()) {
3288 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003289 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003290 case FloatRank: return FloatComplexTy;
3291 case DoubleRank: return DoubleComplexTy;
3292 case LongDoubleRank: return LongDoubleComplexTy;
3293 }
Steve Naroff0af91202007-04-27 21:51:21 +00003294 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003295
3296 assert(Domain->isRealFloatingType() && "Unknown domain!");
3297 switch (EltRank) {
3298 default: assert(0 && "getFloatingRank(): illegal value for rank");
3299 case FloatRank: return FloatTy;
3300 case DoubleRank: return DoubleTy;
3301 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003302 }
Steve Naroffe4718892007-04-27 18:30:00 +00003303}
3304
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003305/// getFloatingTypeOrder - Compare the rank of the two specified floating
3306/// point types, ignoring the domain of the type (i.e. 'double' ==
3307/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003308/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003309int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003310 FloatingRank LHSR = getFloatingRank(LHS);
3311 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003312
Chris Lattnerb90739d2008-04-06 23:38:49 +00003313 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003314 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003315 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003316 return 1;
3317 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003318}
3319
Chris Lattner76a00cf2008-04-06 22:59:24 +00003320/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3321/// routine will assert if passed a built-in type that isn't an integer or enum,
3322/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003323unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003324 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003325 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003326 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003327
Chris Lattnerad3467e2010-12-25 23:25:43 +00003328 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3329 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003330 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3331
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003332 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3333 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3334
3335 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3336 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3337
Chris Lattner76a00cf2008-04-06 22:59:24 +00003338 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003339 default: assert(0 && "getIntegerRank(): not a built-in integer");
3340 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003341 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003342 case BuiltinType::Char_S:
3343 case BuiltinType::Char_U:
3344 case BuiltinType::SChar:
3345 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003346 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003347 case BuiltinType::Short:
3348 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003349 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003350 case BuiltinType::Int:
3351 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003352 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003353 case BuiltinType::Long:
3354 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003355 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003356 case BuiltinType::LongLong:
3357 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003358 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003359 case BuiltinType::Int128:
3360 case BuiltinType::UInt128:
3361 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003362 }
3363}
3364
Eli Friedman629ffb92009-08-20 04:21:42 +00003365/// \brief Whether this is a promotable bitfield reference according
3366/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3367///
3368/// \returns the type this bit-field will promote to, or NULL if no
3369/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003370QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003371 if (E->isTypeDependent() || E->isValueDependent())
3372 return QualType();
3373
Eli Friedman629ffb92009-08-20 04:21:42 +00003374 FieldDecl *Field = E->getBitField();
3375 if (!Field)
3376 return QualType();
3377
3378 QualType FT = Field->getType();
3379
3380 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3381 uint64_t BitWidth = BitWidthAP.getZExtValue();
3382 uint64_t IntSize = getTypeSize(IntTy);
3383 // GCC extension compatibility: if the bit-field size is less than or equal
3384 // to the size of int, it gets promoted no matter what its type is.
3385 // For instance, unsigned long bf : 4 gets promoted to signed int.
3386 if (BitWidth < IntSize)
3387 return IntTy;
3388
3389 if (BitWidth == IntSize)
3390 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3391
3392 // Types bigger than int are not subject to promotions, and therefore act
3393 // like the base type.
3394 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3395 // is ridiculous.
3396 return QualType();
3397}
3398
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003399/// getPromotedIntegerType - Returns the type that Promotable will
3400/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3401/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003402QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003403 assert(!Promotable.isNull());
3404 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003405 if (const EnumType *ET = Promotable->getAs<EnumType>())
3406 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003407 if (Promotable->isSignedIntegerType())
3408 return IntTy;
3409 uint64_t PromotableSize = getTypeSize(Promotable);
3410 uint64_t IntSize = getTypeSize(IntTy);
3411 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3412 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3413}
3414
Mike Stump11289f42009-09-09 15:08:12 +00003415/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003416/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003417/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003418int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003419 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3420 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003421 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003422
Chris Lattner76a00cf2008-04-06 22:59:24 +00003423 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3424 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003425
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003426 unsigned LHSRank = getIntegerRank(LHSC);
3427 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003428
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003429 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3430 if (LHSRank == RHSRank) return 0;
3431 return LHSRank > RHSRank ? 1 : -1;
3432 }
Mike Stump11289f42009-09-09 15:08:12 +00003433
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003434 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3435 if (LHSUnsigned) {
3436 // If the unsigned [LHS] type is larger, return it.
3437 if (LHSRank >= RHSRank)
3438 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003439
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003440 // If the signed type can represent all values of the unsigned type, it
3441 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003442 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003443 return -1;
3444 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003445
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003446 // If the unsigned [RHS] type is larger, return it.
3447 if (RHSRank >= LHSRank)
3448 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003449
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003450 // If the signed type can represent all values of the unsigned type, it
3451 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003452 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003453 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003454}
Anders Carlsson98f07902007-08-17 05:31:46 +00003455
Anders Carlsson6d417272009-11-14 21:45:58 +00003456static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003457CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3458 DeclContext *DC, IdentifierInfo *Id) {
3459 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003460 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003461 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003462 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003463 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003464}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003465
Mike Stump11289f42009-09-09 15:08:12 +00003466// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003467QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003468 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003469 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003470 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003471 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003472 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003473
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003474 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003475
Anders Carlsson98f07902007-08-17 05:31:46 +00003476 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003477 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003478 // int flags;
3479 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003480 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003481 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003482 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003483 FieldTypes[3] = LongTy;
3484
Anders Carlsson98f07902007-08-17 05:31:46 +00003485 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003486 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003487 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003488 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003489 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003490 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003491 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003492 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003493 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003494 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003495 }
3496
Douglas Gregord5058122010-02-11 01:19:42 +00003497 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003498 }
Mike Stump11289f42009-09-09 15:08:12 +00003499
Anders Carlsson98f07902007-08-17 05:31:46 +00003500 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003501}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003502
Douglas Gregor512b0772009-04-23 22:29:11 +00003503void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003504 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003505 assert(Rec && "Invalid CFConstantStringType");
3506 CFConstantStringTypeDecl = Rec->getDecl();
3507}
3508
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003509// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003510QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003511 if (!NSConstantStringTypeDecl) {
3512 NSConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003513 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003514 &Idents.get("__builtin_NSString"));
3515 NSConstantStringTypeDecl->startDefinition();
3516
3517 QualType FieldTypes[3];
3518
3519 // const int *isa;
3520 FieldTypes[0] = getPointerType(IntTy.withConst());
3521 // const char *str;
3522 FieldTypes[1] = getPointerType(CharTy.withConst());
3523 // unsigned int length;
3524 FieldTypes[2] = UnsignedIntTy;
3525
3526 // Create fields
3527 for (unsigned i = 0; i < 3; ++i) {
3528 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003529 SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003530 SourceLocation(), 0,
3531 FieldTypes[i], /*TInfo=*/0,
3532 /*BitWidth=*/0,
3533 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003534 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003535 NSConstantStringTypeDecl->addDecl(Field);
3536 }
3537
3538 NSConstantStringTypeDecl->completeDefinition();
3539 }
3540
3541 return getTagDeclType(NSConstantStringTypeDecl);
3542}
3543
3544void ASTContext::setNSConstantStringType(QualType T) {
3545 const RecordType *Rec = T->getAs<RecordType>();
3546 assert(Rec && "Invalid NSConstantStringType");
3547 NSConstantStringTypeDecl = Rec->getDecl();
3548}
3549
Jay Foad39c79802011-01-12 09:06:06 +00003550QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003551 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003552 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003553 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003554 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003555 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003556
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003557 QualType FieldTypes[] = {
3558 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003559 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003560 getPointerType(UnsignedLongTy),
3561 getConstantArrayType(UnsignedLongTy,
3562 llvm::APInt(32, 5), ArrayType::Normal, 0)
3563 };
Mike Stump11289f42009-09-09 15:08:12 +00003564
Douglas Gregor91f84212008-12-11 16:49:14 +00003565 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003566 FieldDecl *Field = FieldDecl::Create(*this,
3567 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003568 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003569 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003570 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003571 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003572 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003573 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003574 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003575 }
Mike Stump11289f42009-09-09 15:08:12 +00003576
Douglas Gregord5058122010-02-11 01:19:42 +00003577 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003578 }
Mike Stump11289f42009-09-09 15:08:12 +00003579
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003580 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3581}
3582
Jay Foad39c79802011-01-12 09:06:06 +00003583QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003584 if (BlockDescriptorType)
3585 return getTagDeclType(BlockDescriptorType);
3586
3587 RecordDecl *T;
3588 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003589 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003590 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003591 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003592
3593 QualType FieldTypes[] = {
3594 UnsignedLongTy,
3595 UnsignedLongTy,
3596 };
3597
3598 const char *FieldNames[] = {
3599 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003600 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003601 };
3602
3603 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003604 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003605 SourceLocation(),
3606 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003607 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003608 /*BitWidth=*/0,
3609 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003610 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003611 T->addDecl(Field);
3612 }
3613
Douglas Gregord5058122010-02-11 01:19:42 +00003614 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003615
3616 BlockDescriptorType = T;
3617
3618 return getTagDeclType(BlockDescriptorType);
3619}
3620
3621void ASTContext::setBlockDescriptorType(QualType T) {
3622 const RecordType *Rec = T->getAs<RecordType>();
3623 assert(Rec && "Invalid BlockDescriptorType");
3624 BlockDescriptorType = Rec->getDecl();
3625}
3626
Jay Foad39c79802011-01-12 09:06:06 +00003627QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003628 if (BlockDescriptorExtendedType)
3629 return getTagDeclType(BlockDescriptorExtendedType);
3630
3631 RecordDecl *T;
3632 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003633 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003634 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003635 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003636
3637 QualType FieldTypes[] = {
3638 UnsignedLongTy,
3639 UnsignedLongTy,
3640 getPointerType(VoidPtrTy),
3641 getPointerType(VoidPtrTy)
3642 };
3643
3644 const char *FieldNames[] = {
3645 "reserved",
3646 "Size",
3647 "CopyFuncPtr",
3648 "DestroyFuncPtr"
3649 };
3650
3651 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003652 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003653 SourceLocation(),
3654 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003655 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003656 /*BitWidth=*/0,
3657 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003658 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003659 T->addDecl(Field);
3660 }
3661
Douglas Gregord5058122010-02-11 01:19:42 +00003662 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003663
3664 BlockDescriptorExtendedType = T;
3665
3666 return getTagDeclType(BlockDescriptorExtendedType);
3667}
3668
3669void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3670 const RecordType *Rec = T->getAs<RecordType>();
3671 assert(Rec && "Invalid BlockDescriptorType");
3672 BlockDescriptorExtendedType = Rec->getDecl();
3673}
3674
Jay Foad39c79802011-01-12 09:06:06 +00003675bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003676 if (Ty->isBlockPointerType())
3677 return true;
3678 if (isObjCNSObjectType(Ty))
3679 return true;
3680 if (Ty->isObjCObjectPointerType())
3681 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003682 if (getLangOptions().CPlusPlus) {
3683 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3684 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3685 return RD->hasConstCopyConstructor(*this);
3686
3687 }
3688 }
Mike Stump94967902009-10-21 18:16:27 +00003689 return false;
3690}
3691
Jay Foad39c79802011-01-12 09:06:06 +00003692QualType
3693ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003694 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003695 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003696 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003697 // unsigned int __flags;
3698 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003699 // void *__copy_helper; // as needed
3700 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003701 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003702 // } *
3703
Mike Stump94967902009-10-21 18:16:27 +00003704 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3705
3706 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003707 llvm::SmallString<36> Name;
3708 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3709 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003710 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003711 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003712 T->startDefinition();
3713 QualType Int32Ty = IntTy;
3714 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3715 QualType FieldTypes[] = {
3716 getPointerType(VoidPtrTy),
3717 getPointerType(getTagDeclType(T)),
3718 Int32Ty,
3719 Int32Ty,
3720 getPointerType(VoidPtrTy),
3721 getPointerType(VoidPtrTy),
3722 Ty
3723 };
3724
Daniel Dunbar56df9772010-08-17 22:39:59 +00003725 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003726 "__isa",
3727 "__forwarding",
3728 "__flags",
3729 "__size",
3730 "__copy_helper",
3731 "__destroy_helper",
3732 DeclName,
3733 };
3734
3735 for (size_t i = 0; i < 7; ++i) {
3736 if (!HasCopyAndDispose && i >=4 && i <= 5)
3737 continue;
3738 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003739 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003740 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003741 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003742 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003743 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003744 T->addDecl(Field);
3745 }
3746
Douglas Gregord5058122010-02-11 01:19:42 +00003747 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003748
3749 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003750}
3751
Douglas Gregor512b0772009-04-23 22:29:11 +00003752void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003753 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003754 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3755 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3756}
3757
Anders Carlsson18acd442007-10-29 06:33:42 +00003758// This returns true if a type has been typedefed to BOOL:
3759// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003760static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003761 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003762 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3763 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003764
Anders Carlssond8499822007-10-29 05:01:08 +00003765 return false;
3766}
3767
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003768/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003769/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003770CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003771 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003772
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003773 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003774 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003775 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003776 // Treat arrays as pointers, since that's how they're passed in.
3777 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003778 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003779 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003780}
3781
3782static inline
3783std::string charUnitsToString(const CharUnits &CU) {
3784 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003785}
3786
John McCall351762c2011-02-07 10:33:21 +00003787/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003788/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003789std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3790 std::string S;
3791
David Chisnall950a9512009-11-17 19:33:30 +00003792 const BlockDecl *Decl = Expr->getBlockDecl();
3793 QualType BlockTy =
3794 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3795 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003796 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003797 // Compute size of all parameters.
3798 // Start with computing size of a pointer in number of bytes.
3799 // FIXME: There might(should) be a better way of doing this computation!
3800 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003801 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3802 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003803 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003804 E = Decl->param_end(); PI != E; ++PI) {
3805 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003806 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003807 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003808 ParmOffset += sz;
3809 }
3810 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003811 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003812 // Block pointer and offset.
3813 S += "@?0";
3814 ParmOffset = PtrSize;
3815
3816 // Argument types.
3817 ParmOffset = PtrSize;
3818 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3819 Decl->param_end(); PI != E; ++PI) {
3820 ParmVarDecl *PVDecl = *PI;
3821 QualType PType = PVDecl->getOriginalType();
3822 if (const ArrayType *AT =
3823 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3824 // Use array's original type only if it has known number of
3825 // elements.
3826 if (!isa<ConstantArrayType>(AT))
3827 PType = PVDecl->getType();
3828 } else if (PType->isFunctionType())
3829 PType = PVDecl->getType();
3830 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003831 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003832 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003833 }
John McCall351762c2011-02-07 10:33:21 +00003834
3835 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003836}
3837
David Chisnall50e4eba2010-12-30 14:05:53 +00003838void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3839 std::string& S) {
3840 // Encode result type.
3841 getObjCEncodingForType(Decl->getResultType(), S);
3842 CharUnits ParmOffset;
3843 // Compute size of all parameters.
3844 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3845 E = Decl->param_end(); PI != E; ++PI) {
3846 QualType PType = (*PI)->getType();
3847 CharUnits sz = getObjCEncodingTypeSize(PType);
3848 assert (sz.isPositive() &&
3849 "getObjCEncodingForMethodDecl - Incomplete param type");
3850 ParmOffset += sz;
3851 }
3852 S += charUnitsToString(ParmOffset);
3853 ParmOffset = CharUnits::Zero();
3854
3855 // Argument types.
3856 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3857 E = Decl->param_end(); PI != E; ++PI) {
3858 ParmVarDecl *PVDecl = *PI;
3859 QualType PType = PVDecl->getOriginalType();
3860 if (const ArrayType *AT =
3861 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3862 // Use array's original type only if it has known number of
3863 // elements.
3864 if (!isa<ConstantArrayType>(AT))
3865 PType = PVDecl->getType();
3866 } else if (PType->isFunctionType())
3867 PType = PVDecl->getType();
3868 getObjCEncodingForType(PType, S);
3869 S += charUnitsToString(ParmOffset);
3870 ParmOffset += getObjCEncodingTypeSize(PType);
3871 }
3872}
3873
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003874/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003875/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003876void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003877 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003878 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003879 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003880 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003881 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003882 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003883 // Compute size of all parameters.
3884 // Start with computing size of a pointer in number of bytes.
3885 // FIXME: There might(should) be a better way of doing this computation!
3886 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003887 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003888 // The first two arguments (self and _cmd) are pointers; account for
3889 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003890 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003891 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003892 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003893 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003894 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003895 assert (sz.isPositive() &&
3896 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003897 ParmOffset += sz;
3898 }
Ken Dyck40775002010-01-11 17:06:35 +00003899 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003900 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003901 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003902
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003903 // Argument types.
3904 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003905 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003906 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003907 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003908 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003909 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003910 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3911 // Use array's original type only if it has known number of
3912 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003913 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003914 PType = PVDecl->getType();
3915 } else if (PType->isFunctionType())
3916 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003917 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003918 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003919 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003920 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003921 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003922 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003923 }
3924}
3925
Daniel Dunbar4932b362008-08-28 04:38:10 +00003926/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003927/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003928/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3929/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003930/// Property attributes are stored as a comma-delimited C string. The simple
3931/// attributes readonly and bycopy are encoded as single characters. The
3932/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3933/// encoded as single characters, followed by an identifier. Property types
3934/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003935/// these attributes are defined by the following enumeration:
3936/// @code
3937/// enum PropertyAttributes {
3938/// kPropertyReadOnly = 'R', // property is read-only.
3939/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3940/// kPropertyByref = '&', // property is a reference to the value last assigned
3941/// kPropertyDynamic = 'D', // property is dynamic
3942/// kPropertyGetter = 'G', // followed by getter selector name
3943/// kPropertySetter = 'S', // followed by setter selector name
3944/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3945/// kPropertyType = 't' // followed by old-style type encoding.
3946/// kPropertyWeak = 'W' // 'weak' property
3947/// kPropertyStrong = 'P' // property GC'able
3948/// kPropertyNonAtomic = 'N' // property non-atomic
3949/// };
3950/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003951void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003952 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003953 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003954 // Collect information from the property implementation decl(s).
3955 bool Dynamic = false;
3956 ObjCPropertyImplDecl *SynthesizePID = 0;
3957
3958 // FIXME: Duplicated code due to poor abstraction.
3959 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003960 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003961 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3962 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003963 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003964 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003965 ObjCPropertyImplDecl *PID = *i;
3966 if (PID->getPropertyDecl() == PD) {
3967 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3968 Dynamic = true;
3969 } else {
3970 SynthesizePID = PID;
3971 }
3972 }
3973 }
3974 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003975 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003976 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003977 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003978 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003979 ObjCPropertyImplDecl *PID = *i;
3980 if (PID->getPropertyDecl() == PD) {
3981 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3982 Dynamic = true;
3983 } else {
3984 SynthesizePID = PID;
3985 }
3986 }
Mike Stump11289f42009-09-09 15:08:12 +00003987 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003988 }
3989 }
3990
3991 // FIXME: This is not very efficient.
3992 S = "T";
3993
3994 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003995 // GCC has some special rules regarding encoding of properties which
3996 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003997 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003998 true /* outermost type */,
3999 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004000
4001 if (PD->isReadOnly()) {
4002 S += ",R";
4003 } else {
4004 switch (PD->getSetterKind()) {
4005 case ObjCPropertyDecl::Assign: break;
4006 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004007 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004008 }
4009 }
4010
4011 // It really isn't clear at all what this means, since properties
4012 // are "dynamic by default".
4013 if (Dynamic)
4014 S += ",D";
4015
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004016 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4017 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004018
Daniel Dunbar4932b362008-08-28 04:38:10 +00004019 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4020 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004021 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004022 }
4023
4024 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4025 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004026 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004027 }
4028
4029 if (SynthesizePID) {
4030 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4031 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004032 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004033 }
4034
4035 // FIXME: OBJCGC: weak & strong
4036}
4037
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004038/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004039/// Another legacy compatibility encoding: 32-bit longs are encoded as
4040/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004041/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4042///
4043void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004044 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004045 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004046 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004047 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004048 else
Jay Foad39c79802011-01-12 09:06:06 +00004049 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004050 PointeeTy = IntTy;
4051 }
4052 }
4053}
4054
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004055void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004056 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004057 // We follow the behavior of gcc, expanding structures which are
4058 // directly pointed to, and expanding embedded structures. Note that
4059 // these rules are sufficient to prevent recursive encoding of the
4060 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004061 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004062 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004063}
4064
David Chisnallb190a2c2010-06-04 01:10:52 +00004065static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4066 switch (T->getAs<BuiltinType>()->getKind()) {
4067 default: assert(0 && "Unhandled builtin type kind");
4068 case BuiltinType::Void: return 'v';
4069 case BuiltinType::Bool: return 'B';
4070 case BuiltinType::Char_U:
4071 case BuiltinType::UChar: return 'C';
4072 case BuiltinType::UShort: return 'S';
4073 case BuiltinType::UInt: return 'I';
4074 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004075 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004076 case BuiltinType::UInt128: return 'T';
4077 case BuiltinType::ULongLong: return 'Q';
4078 case BuiltinType::Char_S:
4079 case BuiltinType::SChar: return 'c';
4080 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004081 case BuiltinType::WChar_S:
4082 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004083 case BuiltinType::Int: return 'i';
4084 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004085 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004086 case BuiltinType::LongLong: return 'q';
4087 case BuiltinType::Int128: return 't';
4088 case BuiltinType::Float: return 'f';
4089 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004090 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004091 }
4092}
4093
Jay Foad39c79802011-01-12 09:06:06 +00004094static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004095 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004096 const Expr *E = FD->getBitWidth();
4097 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004098 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004099 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4100 // The GNU runtime requires more information; bitfields are encoded as b,
4101 // then the offset (in bits) of the first element, then the type of the
4102 // bitfield, then the size in bits. For example, in this structure:
4103 //
4104 // struct
4105 // {
4106 // int integer;
4107 // int flags:2;
4108 // };
4109 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4110 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4111 // information is not especially sensible, but we're stuck with it for
4112 // compatibility with GCC, although providing it breaks anything that
4113 // actually uses runtime introspection and wants to work on both runtimes...
4114 if (!Ctx->getLangOptions().NeXTRuntime) {
4115 const RecordDecl *RD = FD->getParent();
4116 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4117 // FIXME: This same linear search is also used in ExprConstant - it might
4118 // be better if the FieldDecl stored its offset. We'd be increasing the
4119 // size of the object slightly, but saving some time every time it is used.
4120 unsigned i = 0;
4121 for (RecordDecl::field_iterator Field = RD->field_begin(),
4122 FieldEnd = RD->field_end();
4123 Field != FieldEnd; (void)++Field, ++i) {
4124 if (*Field == FD)
4125 break;
4126 }
4127 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004128 if (T->isEnumeralType())
4129 S += 'i';
4130 else
Jay Foad39c79802011-01-12 09:06:06 +00004131 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004132 }
4133 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004134 S += llvm::utostr(N);
4135}
4136
Daniel Dunbar07d07852009-10-18 21:17:35 +00004137// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004138void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4139 bool ExpandPointedToStructures,
4140 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004141 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004142 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00004143 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004144 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004145 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004146 return EncodeBitField(this, S, T, FD);
4147 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004148 return;
4149 }
Mike Stump11289f42009-09-09 15:08:12 +00004150
John McCall9dd450b2009-09-21 23:43:11 +00004151 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004152 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004153 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004154 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004155 return;
4156 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004157
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004158 // encoding for pointer or r3eference types.
4159 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004160 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004161 if (PT->isObjCSelType()) {
4162 S += ':';
4163 return;
4164 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004165 PointeeTy = PT->getPointeeType();
4166 }
4167 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4168 PointeeTy = RT->getPointeeType();
4169 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004170 bool isReadOnly = false;
4171 // For historical/compatibility reasons, the read-only qualifier of the
4172 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4173 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004174 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004175 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004176 if (OutermostType && T.isConstQualified()) {
4177 isReadOnly = true;
4178 S += 'r';
4179 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004180 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004181 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004182 while (P->getAs<PointerType>())
4183 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004184 if (P.isConstQualified()) {
4185 isReadOnly = true;
4186 S += 'r';
4187 }
4188 }
4189 if (isReadOnly) {
4190 // Another legacy compatibility encoding. Some ObjC qualifier and type
4191 // combinations need to be rearranged.
4192 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004193 if (llvm::StringRef(S).endswith("nr"))
4194 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004195 }
Mike Stump11289f42009-09-09 15:08:12 +00004196
Anders Carlssond8499822007-10-29 05:01:08 +00004197 if (PointeeTy->isCharType()) {
4198 // char pointer types should be encoded as '*' unless it is a
4199 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004200 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004201 S += '*';
4202 return;
4203 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004204 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004205 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4206 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4207 S += '#';
4208 return;
4209 }
4210 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4211 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4212 S += '@';
4213 return;
4214 }
4215 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004216 }
Anders Carlssond8499822007-10-29 05:01:08 +00004217 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004218 getLegacyIntegralTypeEncoding(PointeeTy);
4219
Mike Stump11289f42009-09-09 15:08:12 +00004220 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004221 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004222 return;
4223 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004224
Chris Lattnere7cabb92009-07-13 00:10:46 +00004225 if (const ArrayType *AT =
4226 // Ignore type qualifiers etc.
4227 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004228 if (isa<IncompleteArrayType>(AT)) {
4229 // Incomplete arrays are encoded as a pointer to the array element.
4230 S += '^';
4231
Mike Stump11289f42009-09-09 15:08:12 +00004232 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004233 false, ExpandStructures, FD);
4234 } else {
4235 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004236
Anders Carlssond05f44b2009-02-22 01:38:57 +00004237 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4238 S += llvm::utostr(CAT->getSize().getZExtValue());
4239 else {
4240 //Variable length arrays are encoded as a regular array with 0 elements.
4241 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4242 S += '0';
4243 }
Mike Stump11289f42009-09-09 15:08:12 +00004244
4245 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004246 false, ExpandStructures, FD);
4247 S += ']';
4248 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004249 return;
4250 }
Mike Stump11289f42009-09-09 15:08:12 +00004251
John McCall9dd450b2009-09-21 23:43:11 +00004252 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004253 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004254 return;
4255 }
Mike Stump11289f42009-09-09 15:08:12 +00004256
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004257 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004258 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004259 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004260 // Anonymous structures print as '?'
4261 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4262 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004263 if (ClassTemplateSpecializationDecl *Spec
4264 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4265 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4266 std::string TemplateArgsStr
4267 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004268 TemplateArgs.data(),
4269 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004270 (*this).PrintingPolicy);
4271
4272 S += TemplateArgsStr;
4273 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004274 } else {
4275 S += '?';
4276 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004277 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004278 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004279 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4280 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004281 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004282 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004283 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004284 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004285 S += '"';
4286 }
Mike Stump11289f42009-09-09 15:08:12 +00004287
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004288 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004289 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004290 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004291 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004292 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004293 QualType qt = Field->getType();
4294 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004295 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004296 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004297 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004298 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004299 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004300 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004301 return;
4302 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004303
Chris Lattnere7cabb92009-07-13 00:10:46 +00004304 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004305 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004306 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004307 else
4308 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004309 return;
4310 }
Mike Stump11289f42009-09-09 15:08:12 +00004311
Chris Lattnere7cabb92009-07-13 00:10:46 +00004312 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004313 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004314 return;
4315 }
Mike Stump11289f42009-09-09 15:08:12 +00004316
John McCall8b07ec22010-05-15 11:32:37 +00004317 // Ignore protocol qualifiers when mangling at this level.
4318 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4319 T = OT->getBaseType();
4320
John McCall8ccfcb52009-09-24 19:53:00 +00004321 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004322 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004323 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004324 S += '{';
4325 const IdentifierInfo *II = OI->getIdentifier();
4326 S += II->getName();
4327 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004328 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4329 DeepCollectObjCIvars(OI, true, Ivars);
4330 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4331 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4332 if (Field->isBitField())
4333 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004334 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004335 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004336 }
4337 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004338 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004339 }
Mike Stump11289f42009-09-09 15:08:12 +00004340
John McCall9dd450b2009-09-21 23:43:11 +00004341 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004342 if (OPT->isObjCIdType()) {
4343 S += '@';
4344 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004345 }
Mike Stump11289f42009-09-09 15:08:12 +00004346
Steve Narofff0c86112009-10-28 22:03:49 +00004347 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4348 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4349 // Since this is a binary compatibility issue, need to consult with runtime
4350 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004351 S += '#';
4352 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004353 }
Mike Stump11289f42009-09-09 15:08:12 +00004354
Chris Lattnere7cabb92009-07-13 00:10:46 +00004355 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004356 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004357 ExpandPointedToStructures,
4358 ExpandStructures, FD);
4359 if (FD || EncodingProperty) {
4360 // Note that we do extended encoding of protocol qualifer list
4361 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004362 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004363 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4364 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004365 S += '<';
4366 S += (*I)->getNameAsString();
4367 S += '>';
4368 }
4369 S += '"';
4370 }
4371 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004372 }
Mike Stump11289f42009-09-09 15:08:12 +00004373
Chris Lattnere7cabb92009-07-13 00:10:46 +00004374 QualType PointeeTy = OPT->getPointeeType();
4375 if (!EncodingProperty &&
4376 isa<TypedefType>(PointeeTy.getTypePtr())) {
4377 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004378 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004379 // {...};
4380 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004381 getObjCEncodingForTypeImpl(PointeeTy, S,
4382 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004383 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004384 return;
4385 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004386
4387 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004388 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004389 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004390 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004391 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4392 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004393 S += '<';
4394 S += (*I)->getNameAsString();
4395 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004396 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004397 S += '"';
4398 }
4399 return;
4400 }
Mike Stump11289f42009-09-09 15:08:12 +00004401
John McCalla9e6e8d2010-05-17 23:56:34 +00004402 // gcc just blithely ignores member pointers.
4403 // TODO: maybe there should be a mangling for these
4404 if (T->getAs<MemberPointerType>())
4405 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004406
4407 if (T->isVectorType()) {
4408 // This matches gcc's encoding, even though technically it is
4409 // insufficient.
4410 // FIXME. We should do a better job than gcc.
4411 return;
4412 }
4413
Chris Lattnere7cabb92009-07-13 00:10:46 +00004414 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004415}
4416
Mike Stump11289f42009-09-09 15:08:12 +00004417void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004418 std::string& S) const {
4419 if (QT & Decl::OBJC_TQ_In)
4420 S += 'n';
4421 if (QT & Decl::OBJC_TQ_Inout)
4422 S += 'N';
4423 if (QT & Decl::OBJC_TQ_Out)
4424 S += 'o';
4425 if (QT & Decl::OBJC_TQ_Bycopy)
4426 S += 'O';
4427 if (QT & Decl::OBJC_TQ_Byref)
4428 S += 'R';
4429 if (QT & Decl::OBJC_TQ_Oneway)
4430 S += 'V';
4431}
4432
Chris Lattnere7cabb92009-07-13 00:10:46 +00004433void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004434 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004435
Anders Carlsson87c149b2007-10-11 01:00:40 +00004436 BuiltinVaListType = T;
4437}
4438
Chris Lattnere7cabb92009-07-13 00:10:46 +00004439void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004440 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004441}
4442
Chris Lattnere7cabb92009-07-13 00:10:46 +00004443void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004444 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004445}
4446
Chris Lattnere7cabb92009-07-13 00:10:46 +00004447void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004448 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004449}
4450
Chris Lattnere7cabb92009-07-13 00:10:46 +00004451void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004452 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004453}
4454
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004455void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004456 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004457 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004458
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004459 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004460}
4461
John McCalld28ae272009-12-02 08:04:21 +00004462/// \brief Retrieve the template name that corresponds to a non-empty
4463/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004464TemplateName
4465ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4466 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004467 unsigned size = End - Begin;
4468 assert(size > 1 && "set is not overloaded!");
4469
4470 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4471 size * sizeof(FunctionTemplateDecl*));
4472 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4473
4474 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004475 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004476 NamedDecl *D = *I;
4477 assert(isa<FunctionTemplateDecl>(D) ||
4478 (isa<UsingShadowDecl>(D) &&
4479 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4480 *Storage++ = D;
4481 }
4482
4483 return TemplateName(OT);
4484}
4485
Douglas Gregordc572a32009-03-30 22:58:21 +00004486/// \brief Retrieve the template name that represents a qualified
4487/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004488TemplateName
4489ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4490 bool TemplateKeyword,
4491 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004492 assert(NNS && "Missing nested-name-specifier in qualified template name");
4493
Douglas Gregorc42075a2010-02-04 18:10:26 +00004494 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004495 llvm::FoldingSetNodeID ID;
4496 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4497
4498 void *InsertPos = 0;
4499 QualifiedTemplateName *QTN =
4500 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4501 if (!QTN) {
4502 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4503 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4504 }
4505
4506 return TemplateName(QTN);
4507}
4508
4509/// \brief Retrieve the template name that represents a dependent
4510/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004511TemplateName
4512ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4513 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004514 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004515 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004516
4517 llvm::FoldingSetNodeID ID;
4518 DependentTemplateName::Profile(ID, NNS, Name);
4519
4520 void *InsertPos = 0;
4521 DependentTemplateName *QTN =
4522 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4523
4524 if (QTN)
4525 return TemplateName(QTN);
4526
4527 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4528 if (CanonNNS == NNS) {
4529 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4530 } else {
4531 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4532 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004533 DependentTemplateName *CheckQTN =
4534 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4535 assert(!CheckQTN && "Dependent type name canonicalization broken");
4536 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004537 }
4538
4539 DependentTemplateNames.InsertNode(QTN, InsertPos);
4540 return TemplateName(QTN);
4541}
4542
Douglas Gregor71395fa2009-11-04 00:56:37 +00004543/// \brief Retrieve the template name that represents a dependent
4544/// template name such as \c MetaFun::template operator+.
4545TemplateName
4546ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004547 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004548 assert((!NNS || NNS->isDependent()) &&
4549 "Nested name specifier must be dependent");
4550
4551 llvm::FoldingSetNodeID ID;
4552 DependentTemplateName::Profile(ID, NNS, Operator);
4553
4554 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004555 DependentTemplateName *QTN
4556 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004557
4558 if (QTN)
4559 return TemplateName(QTN);
4560
4561 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4562 if (CanonNNS == NNS) {
4563 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4564 } else {
4565 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4566 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004567
4568 DependentTemplateName *CheckQTN
4569 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4570 assert(!CheckQTN && "Dependent template name canonicalization broken");
4571 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004572 }
4573
4574 DependentTemplateNames.InsertNode(QTN, InsertPos);
4575 return TemplateName(QTN);
4576}
4577
Douglas Gregor5590be02011-01-15 06:45:20 +00004578TemplateName
4579ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4580 const TemplateArgument &ArgPack) const {
4581 ASTContext &Self = const_cast<ASTContext &>(*this);
4582 llvm::FoldingSetNodeID ID;
4583 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4584
4585 void *InsertPos = 0;
4586 SubstTemplateTemplateParmPackStorage *Subst
4587 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4588
4589 if (!Subst) {
4590 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4591 ArgPack.pack_size(),
4592 ArgPack.pack_begin());
4593 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4594 }
4595
4596 return TemplateName(Subst);
4597}
4598
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004599/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004600/// TargetInfo, produce the corresponding type. The unsigned @p Type
4601/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004602CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004603 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004604 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004605 case TargetInfo::SignedShort: return ShortTy;
4606 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4607 case TargetInfo::SignedInt: return IntTy;
4608 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4609 case TargetInfo::SignedLong: return LongTy;
4610 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4611 case TargetInfo::SignedLongLong: return LongLongTy;
4612 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4613 }
4614
4615 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004616 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004617}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004618
4619//===----------------------------------------------------------------------===//
4620// Type Predicates.
4621//===----------------------------------------------------------------------===//
4622
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004623/// isObjCNSObjectType - Return true if this is an NSObject object using
4624/// NSObject attribute on a c-style pointer type.
4625/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004626/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004627///
4628bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCall424cec92011-01-19 06:33:43 +00004629 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Richard Smithdda56e42011-04-15 14:24:37 +00004630 if (TypedefNameDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004631 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004632 return true;
4633 }
Mike Stump11289f42009-09-09 15:08:12 +00004634 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004635}
4636
Fariborz Jahanian96207692009-02-18 21:49:28 +00004637/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4638/// garbage collection attribute.
4639///
John McCall553d45a2011-01-12 00:34:59 +00004640Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4641 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4642 return Qualifiers::GCNone;
4643
4644 assert(getLangOptions().ObjC1);
4645 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4646
4647 // Default behaviour under objective-C's gc is for ObjC pointers
4648 // (or pointers to them) be treated as though they were declared
4649 // as __strong.
4650 if (GCAttrs == Qualifiers::GCNone) {
4651 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4652 return Qualifiers::Strong;
4653 else if (Ty->isPointerType())
4654 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4655 } else {
4656 // It's not valid to set GC attributes on anything that isn't a
4657 // pointer.
4658#ifndef NDEBUG
4659 QualType CT = Ty->getCanonicalTypeInternal();
4660 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4661 CT = AT->getElementType();
4662 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4663#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004664 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004665 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004666}
4667
Chris Lattner49af6a42008-04-07 06:51:04 +00004668//===----------------------------------------------------------------------===//
4669// Type Compatibility Testing
4670//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004671
Mike Stump11289f42009-09-09 15:08:12 +00004672/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004673/// compatible.
4674static bool areCompatVectorTypes(const VectorType *LHS,
4675 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004676 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004677 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004678 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004679}
4680
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004681bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4682 QualType SecondVec) {
4683 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4684 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4685
4686 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4687 return true;
4688
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004689 // Treat Neon vector types and most AltiVec vector types as if they are the
4690 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004691 const VectorType *First = FirstVec->getAs<VectorType>();
4692 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004693 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004694 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004695 First->getVectorKind() != VectorType::AltiVecPixel &&
4696 First->getVectorKind() != VectorType::AltiVecBool &&
4697 Second->getVectorKind() != VectorType::AltiVecPixel &&
4698 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004699 return true;
4700
4701 return false;
4702}
4703
Steve Naroff8e6aee52009-07-23 01:01:38 +00004704//===----------------------------------------------------------------------===//
4705// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4706//===----------------------------------------------------------------------===//
4707
4708/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4709/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004710bool
4711ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4712 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004713 if (lProto == rProto)
4714 return true;
4715 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4716 E = rProto->protocol_end(); PI != E; ++PI)
4717 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4718 return true;
4719 return false;
4720}
4721
Steve Naroff8e6aee52009-07-23 01:01:38 +00004722/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4723/// return true if lhs's protocols conform to rhs's protocol; false
4724/// otherwise.
4725bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4726 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4727 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4728 return false;
4729}
4730
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004731/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4732/// Class<p1, ...>.
4733bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4734 QualType rhs) {
4735 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4736 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4737 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4738
4739 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4740 E = lhsQID->qual_end(); I != E; ++I) {
4741 bool match = false;
4742 ObjCProtocolDecl *lhsProto = *I;
4743 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4744 E = rhsOPT->qual_end(); J != E; ++J) {
4745 ObjCProtocolDecl *rhsProto = *J;
4746 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4747 match = true;
4748 break;
4749 }
4750 }
4751 if (!match)
4752 return false;
4753 }
4754 return true;
4755}
4756
Steve Naroff8e6aee52009-07-23 01:01:38 +00004757/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4758/// ObjCQualifiedIDType.
4759bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4760 bool compare) {
4761 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004762 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004763 lhs->isObjCIdType() || lhs->isObjCClassType())
4764 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004765 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004766 rhs->isObjCIdType() || rhs->isObjCClassType())
4767 return true;
4768
4769 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004770 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004771
Steve Naroff8e6aee52009-07-23 01:01:38 +00004772 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004773
Steve Naroff8e6aee52009-07-23 01:01:38 +00004774 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004775 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004776 // make sure we check the class hierarchy.
4777 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4778 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4779 E = lhsQID->qual_end(); I != E; ++I) {
4780 // when comparing an id<P> on lhs with a static type on rhs,
4781 // see if static class implements all of id's protocols, directly or
4782 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004783 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004784 return false;
4785 }
4786 }
4787 // If there are no qualifiers and no interface, we have an 'id'.
4788 return true;
4789 }
Mike Stump11289f42009-09-09 15:08:12 +00004790 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004791 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4792 E = lhsQID->qual_end(); I != E; ++I) {
4793 ObjCProtocolDecl *lhsProto = *I;
4794 bool match = false;
4795
4796 // when comparing an id<P> on lhs with a static type on rhs,
4797 // see if static class implements all of id's protocols, directly or
4798 // through its super class and categories.
4799 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4800 E = rhsOPT->qual_end(); J != E; ++J) {
4801 ObjCProtocolDecl *rhsProto = *J;
4802 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4803 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4804 match = true;
4805 break;
4806 }
4807 }
Mike Stump11289f42009-09-09 15:08:12 +00004808 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004809 // make sure we check the class hierarchy.
4810 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4811 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4812 E = lhsQID->qual_end(); I != E; ++I) {
4813 // when comparing an id<P> on lhs with a static type on rhs,
4814 // see if static class implements all of id's protocols, directly or
4815 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004816 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004817 match = true;
4818 break;
4819 }
4820 }
4821 }
4822 if (!match)
4823 return false;
4824 }
Mike Stump11289f42009-09-09 15:08:12 +00004825
Steve Naroff8e6aee52009-07-23 01:01:38 +00004826 return true;
4827 }
Mike Stump11289f42009-09-09 15:08:12 +00004828
Steve Naroff8e6aee52009-07-23 01:01:38 +00004829 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4830 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4831
Mike Stump11289f42009-09-09 15:08:12 +00004832 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004833 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004834 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004835 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4836 E = lhsOPT->qual_end(); I != E; ++I) {
4837 ObjCProtocolDecl *lhsProto = *I;
4838 bool match = false;
4839
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004840 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004841 // see if static class implements all of id's protocols, directly or
4842 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004843 // First, lhs protocols in the qualifier list must be found, direct
4844 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004845 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4846 E = rhsQID->qual_end(); J != E; ++J) {
4847 ObjCProtocolDecl *rhsProto = *J;
4848 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4849 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4850 match = true;
4851 break;
4852 }
4853 }
4854 if (!match)
4855 return false;
4856 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004857
4858 // Static class's protocols, or its super class or category protocols
4859 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4860 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4861 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4862 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4863 // This is rather dubious but matches gcc's behavior. If lhs has
4864 // no type qualifier and its class has no static protocol(s)
4865 // assume that it is mismatch.
4866 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4867 return false;
4868 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4869 LHSInheritedProtocols.begin(),
4870 E = LHSInheritedProtocols.end(); I != E; ++I) {
4871 bool match = false;
4872 ObjCProtocolDecl *lhsProto = (*I);
4873 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4874 E = rhsQID->qual_end(); J != E; ++J) {
4875 ObjCProtocolDecl *rhsProto = *J;
4876 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4877 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4878 match = true;
4879 break;
4880 }
4881 }
4882 if (!match)
4883 return false;
4884 }
4885 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004886 return true;
4887 }
4888 return false;
4889}
4890
Eli Friedman47f77112008-08-22 00:56:42 +00004891/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004892/// compatible for assignment from RHS to LHS. This handles validation of any
4893/// protocol qualifiers on the LHS or RHS.
4894///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004895bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4896 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004897 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4898 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4899
Steve Naroff1329fa02009-07-15 18:40:39 +00004900 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004901 if (LHS->isObjCUnqualifiedIdOrClass() ||
4902 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004903 return true;
4904
John McCall8b07ec22010-05-15 11:32:37 +00004905 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004906 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4907 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004908 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004909
4910 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4911 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4912 QualType(RHSOPT,0));
4913
John McCall8b07ec22010-05-15 11:32:37 +00004914 // If we have 2 user-defined types, fall into that path.
4915 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004916 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004917
Steve Naroff8e6aee52009-07-23 01:01:38 +00004918 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004919}
4920
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004921/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00004922/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004923/// arguments in block literals. When passed as arguments, passing 'A*' where
4924/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4925/// not OK. For the return type, the opposite is not OK.
4926bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4927 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004928 const ObjCObjectPointerType *RHSOPT,
4929 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004930 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004931 return true;
4932
4933 if (LHSOPT->isObjCBuiltinType()) {
4934 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4935 }
4936
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004937 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004938 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4939 QualType(RHSOPT,0),
4940 false);
4941
4942 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4943 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4944 if (LHS && RHS) { // We have 2 user-defined types.
4945 if (LHS != RHS) {
4946 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004947 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004948 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004949 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004950 }
4951 else
4952 return true;
4953 }
4954 return false;
4955}
4956
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004957/// getIntersectionOfProtocols - This routine finds the intersection of set
4958/// of protocols inherited from two distinct objective-c pointer objects.
4959/// It is used to build composite qualifier list of the composite type of
4960/// the conditional expression involving two objective-c pointer objects.
4961static
4962void getIntersectionOfProtocols(ASTContext &Context,
4963 const ObjCObjectPointerType *LHSOPT,
4964 const ObjCObjectPointerType *RHSOPT,
4965 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4966
John McCall8b07ec22010-05-15 11:32:37 +00004967 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4968 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4969 assert(LHS->getInterface() && "LHS must have an interface base");
4970 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004971
4972 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4973 unsigned LHSNumProtocols = LHS->getNumProtocols();
4974 if (LHSNumProtocols > 0)
4975 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4976 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004977 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004978 Context.CollectInheritedProtocols(LHS->getInterface(),
4979 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004980 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4981 LHSInheritedProtocols.end());
4982 }
4983
4984 unsigned RHSNumProtocols = RHS->getNumProtocols();
4985 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004986 ObjCProtocolDecl **RHSProtocols =
4987 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004988 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4989 if (InheritedProtocolSet.count(RHSProtocols[i]))
4990 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4991 }
4992 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004993 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004994 Context.CollectInheritedProtocols(RHS->getInterface(),
4995 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004996 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4997 RHSInheritedProtocols.begin(),
4998 E = RHSInheritedProtocols.end(); I != E; ++I)
4999 if (InheritedProtocolSet.count((*I)))
5000 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005001 }
5002}
5003
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005004/// areCommonBaseCompatible - Returns common base class of the two classes if
5005/// one found. Note that this is O'2 algorithm. But it will be called as the
5006/// last type comparison in a ?-exp of ObjC pointer types before a
5007/// warning is issued. So, its invokation is extremely rare.
5008QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005009 const ObjCObjectPointerType *Lptr,
5010 const ObjCObjectPointerType *Rptr) {
5011 const ObjCObjectType *LHS = Lptr->getObjectType();
5012 const ObjCObjectType *RHS = Rptr->getObjectType();
5013 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5014 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005015 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005016 return QualType();
5017
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005018 do {
John McCall8b07ec22010-05-15 11:32:37 +00005019 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005020 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00005021 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
5022 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5023
5024 QualType Result = QualType(LHS, 0);
5025 if (!Protocols.empty())
5026 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5027 Result = getObjCObjectPointerType(Result);
5028 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005029 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005030 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005031
5032 return QualType();
5033}
5034
John McCall8b07ec22010-05-15 11:32:37 +00005035bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5036 const ObjCObjectType *RHS) {
5037 assert(LHS->getInterface() && "LHS is not an interface type");
5038 assert(RHS->getInterface() && "RHS is not an interface type");
5039
Chris Lattner49af6a42008-04-07 06:51:04 +00005040 // Verify that the base decls are compatible: the RHS must be a subclass of
5041 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005042 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005043 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005044
Chris Lattner49af6a42008-04-07 06:51:04 +00005045 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5046 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005047 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005048 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005049
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005050 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5051 // more detailed analysis is required.
5052 if (RHS->getNumProtocols() == 0) {
5053 // OK, if LHS is a superclass of RHS *and*
5054 // this superclass is assignment compatible with LHS.
5055 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005056 bool IsSuperClass =
5057 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5058 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005059 // OK if conversion of LHS to SuperClass results in narrowing of types
5060 // ; i.e., SuperClass may implement at least one of the protocols
5061 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5062 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5063 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005064 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005065 // If super class has no protocols, it is not a match.
5066 if (SuperClassInheritedProtocols.empty())
5067 return false;
5068
5069 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5070 LHSPE = LHS->qual_end();
5071 LHSPI != LHSPE; LHSPI++) {
5072 bool SuperImplementsProtocol = false;
5073 ObjCProtocolDecl *LHSProto = (*LHSPI);
5074
5075 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5076 SuperClassInheritedProtocols.begin(),
5077 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5078 ObjCProtocolDecl *SuperClassProto = (*I);
5079 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5080 SuperImplementsProtocol = true;
5081 break;
5082 }
5083 }
5084 if (!SuperImplementsProtocol)
5085 return false;
5086 }
5087 return true;
5088 }
5089 return false;
5090 }
Mike Stump11289f42009-09-09 15:08:12 +00005091
John McCall8b07ec22010-05-15 11:32:37 +00005092 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5093 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005094 LHSPI != LHSPE; LHSPI++) {
5095 bool RHSImplementsProtocol = false;
5096
5097 // If the RHS doesn't implement the protocol on the left, the types
5098 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005099 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5100 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005101 RHSPI != RHSPE; RHSPI++) {
5102 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005103 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005104 break;
5105 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005106 }
5107 // FIXME: For better diagnostics, consider passing back the protocol name.
5108 if (!RHSImplementsProtocol)
5109 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005110 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005111 // The RHS implements all protocols listed on the LHS.
5112 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005113}
5114
Steve Naroffb7605152009-02-12 17:52:19 +00005115bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5116 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005117 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5118 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005119
Steve Naroff7cae42b2009-07-10 23:34:53 +00005120 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005121 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005122
5123 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5124 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005125}
5126
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005127bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5128 return canAssignObjCInterfaces(
5129 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5130 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5131}
5132
Mike Stump11289f42009-09-09 15:08:12 +00005133/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005134/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005135/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005136/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005137bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5138 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005139 if (getLangOptions().CPlusPlus)
5140 return hasSameType(LHS, RHS);
5141
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005142 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005143}
5144
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005145bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5146 return !mergeTypes(LHS, RHS, true).isNull();
5147}
5148
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005149/// mergeTransparentUnionType - if T is a transparent union type and a member
5150/// of T is compatible with SubType, return the merged type, else return
5151/// QualType()
5152QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5153 bool OfBlockPointer,
5154 bool Unqualified) {
5155 if (const RecordType *UT = T->getAsUnionType()) {
5156 RecordDecl *UD = UT->getDecl();
5157 if (UD->hasAttr<TransparentUnionAttr>()) {
5158 for (RecordDecl::field_iterator it = UD->field_begin(),
5159 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005160 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005161 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5162 if (!MT.isNull())
5163 return MT;
5164 }
5165 }
5166 }
5167
5168 return QualType();
5169}
5170
5171/// mergeFunctionArgumentTypes - merge two types which appear as function
5172/// argument types
5173QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5174 bool OfBlockPointer,
5175 bool Unqualified) {
5176 // GNU extension: two types are compatible if they appear as a function
5177 // argument, one of the types is a transparent union type and the other
5178 // type is compatible with a union member
5179 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5180 Unqualified);
5181 if (!lmerge.isNull())
5182 return lmerge;
5183
5184 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5185 Unqualified);
5186 if (!rmerge.isNull())
5187 return rmerge;
5188
5189 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5190}
5191
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005192QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005193 bool OfBlockPointer,
5194 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005195 const FunctionType *lbase = lhs->getAs<FunctionType>();
5196 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005197 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5198 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005199 bool allLTypes = true;
5200 bool allRTypes = true;
5201
5202 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005203 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005204 if (OfBlockPointer) {
5205 QualType RHS = rbase->getResultType();
5206 QualType LHS = lbase->getResultType();
5207 bool UnqualifiedResult = Unqualified;
5208 if (!UnqualifiedResult)
5209 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005210 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005211 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005212 else
John McCall8c6b56f2010-12-15 01:06:38 +00005213 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5214 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005215 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005216
5217 if (Unqualified)
5218 retType = retType.getUnqualifiedType();
5219
5220 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5221 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5222 if (Unqualified) {
5223 LRetType = LRetType.getUnqualifiedType();
5224 RRetType = RRetType.getUnqualifiedType();
5225 }
5226
5227 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005228 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005229 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005230 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005231
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005232 // FIXME: double check this
5233 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5234 // rbase->getRegParmAttr() != 0 &&
5235 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005236 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5237 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005238
Douglas Gregor8c940862010-01-18 17:14:39 +00005239 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005240 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005241 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005242
John McCall8c6b56f2010-12-15 01:06:38 +00005243 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005244 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5245 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005246 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5247 return QualType();
5248
5249 // It's noreturn if either type is.
5250 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5251 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5252 if (NoReturn != lbaseInfo.getNoReturn())
5253 allLTypes = false;
5254 if (NoReturn != rbaseInfo.getNoReturn())
5255 allRTypes = false;
5256
5257 FunctionType::ExtInfo einfo(NoReturn,
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005258 lbaseInfo.getHasRegParm(),
John McCall8c6b56f2010-12-15 01:06:38 +00005259 lbaseInfo.getRegParm(),
5260 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00005261
Eli Friedman47f77112008-08-22 00:56:42 +00005262 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005263 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5264 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005265 unsigned lproto_nargs = lproto->getNumArgs();
5266 unsigned rproto_nargs = rproto->getNumArgs();
5267
5268 // Compatible functions must have the same number of arguments
5269 if (lproto_nargs != rproto_nargs)
5270 return QualType();
5271
5272 // Variadic and non-variadic functions aren't compatible
5273 if (lproto->isVariadic() != rproto->isVariadic())
5274 return QualType();
5275
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005276 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5277 return QualType();
5278
Eli Friedman47f77112008-08-22 00:56:42 +00005279 // Check argument compatibility
5280 llvm::SmallVector<QualType, 10> types;
5281 for (unsigned i = 0; i < lproto_nargs; i++) {
5282 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5283 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005284 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5285 OfBlockPointer,
5286 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005287 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005288
5289 if (Unqualified)
5290 argtype = argtype.getUnqualifiedType();
5291
Eli Friedman47f77112008-08-22 00:56:42 +00005292 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005293 if (Unqualified) {
5294 largtype = largtype.getUnqualifiedType();
5295 rargtype = rargtype.getUnqualifiedType();
5296 }
5297
Chris Lattner465fa322008-10-05 17:34:18 +00005298 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5299 allLTypes = false;
5300 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5301 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005302 }
5303 if (allLTypes) return lhs;
5304 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005305
5306 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5307 EPI.ExtInfo = einfo;
5308 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005309 }
5310
5311 if (lproto) allRTypes = false;
5312 if (rproto) allLTypes = false;
5313
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005314 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005315 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005316 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005317 if (proto->isVariadic()) return QualType();
5318 // Check that the types are compatible with the types that
5319 // would result from default argument promotions (C99 6.7.5.3p15).
5320 // The only types actually affected are promotable integer
5321 // types and floats, which would be passed as a different
5322 // type depending on whether the prototype is visible.
5323 unsigned proto_nargs = proto->getNumArgs();
5324 for (unsigned i = 0; i < proto_nargs; ++i) {
5325 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005326
5327 // Look at the promotion type of enum types, since that is the type used
5328 // to pass enum values.
5329 if (const EnumType *Enum = argTy->getAs<EnumType>())
5330 argTy = Enum->getDecl()->getPromotionType();
5331
Eli Friedman47f77112008-08-22 00:56:42 +00005332 if (argTy->isPromotableIntegerType() ||
5333 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5334 return QualType();
5335 }
5336
5337 if (allLTypes) return lhs;
5338 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005339
5340 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5341 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005342 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005343 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005344 }
5345
5346 if (allLTypes) return lhs;
5347 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005348 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005349}
5350
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005351QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005352 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005353 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005354 // C++ [expr]: If an expression initially has the type "reference to T", the
5355 // type is adjusted to "T" prior to any further analysis, the expression
5356 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005357 // expression is an lvalue unless the reference is an rvalue reference and
5358 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005359 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5360 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005361
5362 if (Unqualified) {
5363 LHS = LHS.getUnqualifiedType();
5364 RHS = RHS.getUnqualifiedType();
5365 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005366
Eli Friedman47f77112008-08-22 00:56:42 +00005367 QualType LHSCan = getCanonicalType(LHS),
5368 RHSCan = getCanonicalType(RHS);
5369
5370 // If two types are identical, they are compatible.
5371 if (LHSCan == RHSCan)
5372 return LHS;
5373
John McCall8ccfcb52009-09-24 19:53:00 +00005374 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005375 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5376 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005377 if (LQuals != RQuals) {
5378 // If any of these qualifiers are different, we have a type
5379 // mismatch.
5380 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5381 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5382 return QualType();
5383
5384 // Exactly one GC qualifier difference is allowed: __strong is
5385 // okay if the other type has no GC qualifier but is an Objective
5386 // C object pointer (i.e. implicitly strong by default). We fix
5387 // this by pretending that the unqualified type was actually
5388 // qualified __strong.
5389 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5390 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5391 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5392
5393 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5394 return QualType();
5395
5396 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5397 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5398 }
5399 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5400 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5401 }
Eli Friedman47f77112008-08-22 00:56:42 +00005402 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005403 }
5404
5405 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005406
Eli Friedmandcca6332009-06-01 01:22:52 +00005407 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5408 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005409
Chris Lattnerfd652912008-01-14 05:45:46 +00005410 // We want to consider the two function types to be the same for these
5411 // comparisons, just force one to the other.
5412 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5413 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005414
5415 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005416 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5417 LHSClass = Type::ConstantArray;
5418 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5419 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005420
John McCall8b07ec22010-05-15 11:32:37 +00005421 // ObjCInterfaces are just specialized ObjCObjects.
5422 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5423 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5424
Nate Begemance4d7fc2008-04-18 23:10:10 +00005425 // Canonicalize ExtVector -> Vector.
5426 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5427 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005428
Chris Lattner95554662008-04-07 05:43:21 +00005429 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005430 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005431 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005432 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005433 // Compatibility is based on the underlying type, not the promotion
5434 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005435 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005436 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5437 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005438 }
John McCall9dd450b2009-09-21 23:43:11 +00005439 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005440 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5441 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005442 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005443
Eli Friedman47f77112008-08-22 00:56:42 +00005444 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005445 }
Eli Friedman47f77112008-08-22 00:56:42 +00005446
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005447 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005448 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005449#define TYPE(Class, Base)
5450#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005451#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005452#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5453#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5454#include "clang/AST/TypeNodes.def"
5455 assert(false && "Non-canonical and dependent types shouldn't get here");
5456 return QualType();
5457
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005458 case Type::LValueReference:
5459 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005460 case Type::MemberPointer:
5461 assert(false && "C++ should never be in mergeTypes");
5462 return QualType();
5463
John McCall8b07ec22010-05-15 11:32:37 +00005464 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005465 case Type::IncompleteArray:
5466 case Type::VariableArray:
5467 case Type::FunctionProto:
5468 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005469 assert(false && "Types are eliminated above");
5470 return QualType();
5471
Chris Lattnerfd652912008-01-14 05:45:46 +00005472 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005473 {
5474 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005475 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5476 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005477 if (Unqualified) {
5478 LHSPointee = LHSPointee.getUnqualifiedType();
5479 RHSPointee = RHSPointee.getUnqualifiedType();
5480 }
5481 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5482 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005483 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005484 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005485 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005486 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005487 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005488 return getPointerType(ResultType);
5489 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005490 case Type::BlockPointer:
5491 {
5492 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005493 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5494 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005495 if (Unqualified) {
5496 LHSPointee = LHSPointee.getUnqualifiedType();
5497 RHSPointee = RHSPointee.getUnqualifiedType();
5498 }
5499 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5500 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005501 if (ResultType.isNull()) return QualType();
5502 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5503 return LHS;
5504 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5505 return RHS;
5506 return getBlockPointerType(ResultType);
5507 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005508 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005509 {
5510 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5511 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5512 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5513 return QualType();
5514
5515 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5516 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005517 if (Unqualified) {
5518 LHSElem = LHSElem.getUnqualifiedType();
5519 RHSElem = RHSElem.getUnqualifiedType();
5520 }
5521
5522 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005523 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005524 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5525 return LHS;
5526 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5527 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005528 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5529 ArrayType::ArraySizeModifier(), 0);
5530 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5531 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005532 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5533 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005534 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5535 return LHS;
5536 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5537 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005538 if (LVAT) {
5539 // FIXME: This isn't correct! But tricky to implement because
5540 // the array's size has to be the size of LHS, but the type
5541 // has to be different.
5542 return LHS;
5543 }
5544 if (RVAT) {
5545 // FIXME: This isn't correct! But tricky to implement because
5546 // the array's size has to be the size of RHS, but the type
5547 // has to be different.
5548 return RHS;
5549 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005550 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5551 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005552 return getIncompleteArrayType(ResultType,
5553 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005554 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005555 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005556 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005557 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005558 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005559 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005560 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005561 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005562 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005563 case Type::Complex:
5564 // Distinct complex types are incompatible.
5565 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005566 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005567 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005568 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5569 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005570 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005571 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005572 case Type::ObjCObject: {
5573 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005574 // FIXME: This should be type compatibility, e.g. whether
5575 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005576 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5577 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5578 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005579 return LHS;
5580
Eli Friedman47f77112008-08-22 00:56:42 +00005581 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005582 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005583 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005584 if (OfBlockPointer) {
5585 if (canAssignObjCInterfacesInBlockPointer(
5586 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005587 RHS->getAs<ObjCObjectPointerType>(),
5588 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005589 return LHS;
5590 return QualType();
5591 }
John McCall9dd450b2009-09-21 23:43:11 +00005592 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5593 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005594 return LHS;
5595
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005596 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005597 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005598 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005599
5600 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005601}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005602
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005603/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5604/// 'RHS' attributes and returns the merged version; including for function
5605/// return types.
5606QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5607 QualType LHSCan = getCanonicalType(LHS),
5608 RHSCan = getCanonicalType(RHS);
5609 // If two types are identical, they are compatible.
5610 if (LHSCan == RHSCan)
5611 return LHS;
5612 if (RHSCan->isFunctionType()) {
5613 if (!LHSCan->isFunctionType())
5614 return QualType();
5615 QualType OldReturnType =
5616 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5617 QualType NewReturnType =
5618 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5619 QualType ResReturnType =
5620 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5621 if (ResReturnType.isNull())
5622 return QualType();
5623 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5624 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5625 // In either case, use OldReturnType to build the new function type.
5626 const FunctionType *F = LHS->getAs<FunctionType>();
5627 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005628 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5629 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005630 QualType ResultType
5631 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005632 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005633 return ResultType;
5634 }
5635 }
5636 return QualType();
5637 }
5638
5639 // If the qualifiers are different, the types can still be merged.
5640 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5641 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5642 if (LQuals != RQuals) {
5643 // If any of these qualifiers are different, we have a type mismatch.
5644 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5645 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5646 return QualType();
5647
5648 // Exactly one GC qualifier difference is allowed: __strong is
5649 // okay if the other type has no GC qualifier but is an Objective
5650 // C object pointer (i.e. implicitly strong by default). We fix
5651 // this by pretending that the unqualified type was actually
5652 // qualified __strong.
5653 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5654 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5655 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5656
5657 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5658 return QualType();
5659
5660 if (GC_L == Qualifiers::Strong)
5661 return LHS;
5662 if (GC_R == Qualifiers::Strong)
5663 return RHS;
5664 return QualType();
5665 }
5666
5667 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5668 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5669 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5670 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5671 if (ResQT == LHSBaseQT)
5672 return LHS;
5673 if (ResQT == RHSBaseQT)
5674 return RHS;
5675 }
5676 return QualType();
5677}
5678
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005679//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005680// Integer Predicates
5681//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005682
Jay Foad39c79802011-01-12 09:06:06 +00005683unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005684 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005685 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005686 if (T->isBooleanType())
5687 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005688 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005689 return (unsigned)getTypeSize(T);
5690}
5691
5692QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005693 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005694
5695 // Turn <4 x signed int> -> <4 x unsigned int>
5696 if (const VectorType *VTy = T->getAs<VectorType>())
5697 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005698 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005699
5700 // For enums, we return the unsigned version of the base type.
5701 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005702 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005703
5704 const BuiltinType *BTy = T->getAs<BuiltinType>();
5705 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005706 switch (BTy->getKind()) {
5707 case BuiltinType::Char_S:
5708 case BuiltinType::SChar:
5709 return UnsignedCharTy;
5710 case BuiltinType::Short:
5711 return UnsignedShortTy;
5712 case BuiltinType::Int:
5713 return UnsignedIntTy;
5714 case BuiltinType::Long:
5715 return UnsignedLongTy;
5716 case BuiltinType::LongLong:
5717 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005718 case BuiltinType::Int128:
5719 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005720 default:
5721 assert(0 && "Unexpected signed integer type");
5722 return QualType();
5723 }
5724}
5725
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005726ASTMutationListener::~ASTMutationListener() { }
5727
Chris Lattnerecd79c62009-06-14 00:45:47 +00005728
5729//===----------------------------------------------------------------------===//
5730// Builtin Type Computation
5731//===----------------------------------------------------------------------===//
5732
5733/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005734/// pointer over the consumed characters. This returns the resultant type. If
5735/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5736/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5737/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005738///
5739/// RequiresICE is filled in on return to indicate whether the value is required
5740/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005741static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005742 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005743 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005744 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005745 // Modifiers.
5746 int HowLong = 0;
5747 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005748 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005749
Chris Lattnerdc226c22010-10-01 22:42:38 +00005750 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005751 bool Done = false;
5752 while (!Done) {
5753 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005754 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005755 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005756 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005757 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005758 case 'S':
5759 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5760 assert(!Signed && "Can't use 'S' modifier multiple times!");
5761 Signed = true;
5762 break;
5763 case 'U':
5764 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5765 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5766 Unsigned = true;
5767 break;
5768 case 'L':
5769 assert(HowLong <= 2 && "Can't have LLLL modifier");
5770 ++HowLong;
5771 break;
5772 }
5773 }
5774
5775 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005776
Chris Lattnerecd79c62009-06-14 00:45:47 +00005777 // Read the base type.
5778 switch (*Str++) {
5779 default: assert(0 && "Unknown builtin type letter!");
5780 case 'v':
5781 assert(HowLong == 0 && !Signed && !Unsigned &&
5782 "Bad modifiers used with 'v'!");
5783 Type = Context.VoidTy;
5784 break;
5785 case 'f':
5786 assert(HowLong == 0 && !Signed && !Unsigned &&
5787 "Bad modifiers used with 'f'!");
5788 Type = Context.FloatTy;
5789 break;
5790 case 'd':
5791 assert(HowLong < 2 && !Signed && !Unsigned &&
5792 "Bad modifiers used with 'd'!");
5793 if (HowLong)
5794 Type = Context.LongDoubleTy;
5795 else
5796 Type = Context.DoubleTy;
5797 break;
5798 case 's':
5799 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5800 if (Unsigned)
5801 Type = Context.UnsignedShortTy;
5802 else
5803 Type = Context.ShortTy;
5804 break;
5805 case 'i':
5806 if (HowLong == 3)
5807 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5808 else if (HowLong == 2)
5809 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5810 else if (HowLong == 1)
5811 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5812 else
5813 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5814 break;
5815 case 'c':
5816 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5817 if (Signed)
5818 Type = Context.SignedCharTy;
5819 else if (Unsigned)
5820 Type = Context.UnsignedCharTy;
5821 else
5822 Type = Context.CharTy;
5823 break;
5824 case 'b': // boolean
5825 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5826 Type = Context.BoolTy;
5827 break;
5828 case 'z': // size_t.
5829 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5830 Type = Context.getSizeType();
5831 break;
5832 case 'F':
5833 Type = Context.getCFConstantStringType();
5834 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005835 case 'G':
5836 Type = Context.getObjCIdType();
5837 break;
5838 case 'H':
5839 Type = Context.getObjCSelType();
5840 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005841 case 'a':
5842 Type = Context.getBuiltinVaListType();
5843 assert(!Type.isNull() && "builtin va list type not initialized!");
5844 break;
5845 case 'A':
5846 // This is a "reference" to a va_list; however, what exactly
5847 // this means depends on how va_list is defined. There are two
5848 // different kinds of va_list: ones passed by value, and ones
5849 // passed by reference. An example of a by-value va_list is
5850 // x86, where va_list is a char*. An example of by-ref va_list
5851 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5852 // we want this argument to be a char*&; for x86-64, we want
5853 // it to be a __va_list_tag*.
5854 Type = Context.getBuiltinVaListType();
5855 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005856 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005857 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005858 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005859 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005860 break;
5861 case 'V': {
5862 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005863 unsigned NumElements = strtoul(Str, &End, 10);
5864 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005865 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005866
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005867 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5868 RequiresICE, false);
5869 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005870
5871 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005872 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005873 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005874 break;
5875 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005876 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005877 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5878 false);
5879 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005880 Type = Context.getComplexType(ElementType);
5881 break;
5882 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005883 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005884 Type = Context.getFILEType();
5885 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005886 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005887 return QualType();
5888 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005889 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005890 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005891 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005892 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005893 else
5894 Type = Context.getjmp_bufType();
5895
Mike Stump2adb4da2009-07-28 23:47:15 +00005896 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005897 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005898 return QualType();
5899 }
5900 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005901 }
Mike Stump11289f42009-09-09 15:08:12 +00005902
Chris Lattnerdc226c22010-10-01 22:42:38 +00005903 // If there are modifiers and if we're allowed to parse them, go for it.
5904 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005905 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005906 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005907 default: Done = true; --Str; break;
5908 case '*':
5909 case '&': {
5910 // Both pointers and references can have their pointee types
5911 // qualified with an address space.
5912 char *End;
5913 unsigned AddrSpace = strtoul(Str, &End, 10);
5914 if (End != Str && AddrSpace != 0) {
5915 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5916 Str = End;
5917 }
5918 if (c == '*')
5919 Type = Context.getPointerType(Type);
5920 else
5921 Type = Context.getLValueReferenceType(Type);
5922 break;
5923 }
5924 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5925 case 'C':
5926 Type = Type.withConst();
5927 break;
5928 case 'D':
5929 Type = Context.getVolatileType(Type);
5930 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005931 }
5932 }
Chris Lattner84733392010-10-01 07:13:18 +00005933
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005934 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005935 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005936
Chris Lattnerecd79c62009-06-14 00:45:47 +00005937 return Type;
5938}
5939
5940/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005941QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005942 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005943 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005944 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005945
Chris Lattnerecd79c62009-06-14 00:45:47 +00005946 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005947
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005948 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005949 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005950 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5951 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005952 if (Error != GE_None)
5953 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005954
5955 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5956
Chris Lattnerecd79c62009-06-14 00:45:47 +00005957 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005958 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005959 if (Error != GE_None)
5960 return QualType();
5961
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005962 // If this argument is required to be an IntegerConstantExpression and the
5963 // caller cares, fill in the bitmask we return.
5964 if (RequiresICE && IntegerConstantArgs)
5965 *IntegerConstantArgs |= 1 << ArgTypes.size();
5966
Chris Lattnerecd79c62009-06-14 00:45:47 +00005967 // Do array -> pointer decay. The builtin should use the decayed type.
5968 if (Ty->isArrayType())
5969 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005970
Chris Lattnerecd79c62009-06-14 00:45:47 +00005971 ArgTypes.push_back(Ty);
5972 }
5973
5974 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5975 "'.' should only occur at end of builtin type list!");
5976
John McCall991eb4b2010-12-21 00:44:39 +00005977 FunctionType::ExtInfo EI;
5978 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5979
5980 bool Variadic = (TypeStr[0] == '.');
5981
5982 // We really shouldn't be making a no-proto type here, especially in C++.
5983 if (ArgTypes.empty() && Variadic)
5984 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005985
John McCalldb40c7f2010-12-14 08:05:40 +00005986 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005987 EPI.ExtInfo = EI;
5988 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00005989
5990 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005991}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005992
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005993GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5994 GVALinkage External = GVA_StrongExternal;
5995
5996 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005997 switch (L) {
5998 case NoLinkage:
5999 case InternalLinkage:
6000 case UniqueExternalLinkage:
6001 return GVA_Internal;
6002
6003 case ExternalLinkage:
6004 switch (FD->getTemplateSpecializationKind()) {
6005 case TSK_Undeclared:
6006 case TSK_ExplicitSpecialization:
6007 External = GVA_StrongExternal;
6008 break;
6009
6010 case TSK_ExplicitInstantiationDefinition:
6011 return GVA_ExplicitTemplateInstantiation;
6012
6013 case TSK_ExplicitInstantiationDeclaration:
6014 case TSK_ImplicitInstantiation:
6015 External = GVA_TemplateInstantiation;
6016 break;
6017 }
6018 }
6019
6020 if (!FD->isInlined())
6021 return External;
6022
6023 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6024 // GNU or C99 inline semantics. Determine whether this symbol should be
6025 // externally visible.
6026 if (FD->isInlineDefinitionExternallyVisible())
6027 return External;
6028
6029 // C99 inline semantics, where the symbol is not externally visible.
6030 return GVA_C99Inline;
6031 }
6032
6033 // C++0x [temp.explicit]p9:
6034 // [ Note: The intent is that an inline function that is the subject of
6035 // an explicit instantiation declaration will still be implicitly
6036 // instantiated when used so that the body can be considered for
6037 // inlining, but that no out-of-line copy of the inline function would be
6038 // generated in the translation unit. -- end note ]
6039 if (FD->getTemplateSpecializationKind()
6040 == TSK_ExplicitInstantiationDeclaration)
6041 return GVA_C99Inline;
6042
6043 return GVA_CXXInline;
6044}
6045
6046GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6047 // If this is a static data member, compute the kind of template
6048 // specialization. Otherwise, this variable is not part of a
6049 // template.
6050 TemplateSpecializationKind TSK = TSK_Undeclared;
6051 if (VD->isStaticDataMember())
6052 TSK = VD->getTemplateSpecializationKind();
6053
6054 Linkage L = VD->getLinkage();
6055 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6056 VD->getType()->getLinkage() == UniqueExternalLinkage)
6057 L = UniqueExternalLinkage;
6058
6059 switch (L) {
6060 case NoLinkage:
6061 case InternalLinkage:
6062 case UniqueExternalLinkage:
6063 return GVA_Internal;
6064
6065 case ExternalLinkage:
6066 switch (TSK) {
6067 case TSK_Undeclared:
6068 case TSK_ExplicitSpecialization:
6069 return GVA_StrongExternal;
6070
6071 case TSK_ExplicitInstantiationDeclaration:
6072 llvm_unreachable("Variable should not be instantiated");
6073 // Fall through to treat this like any other instantiation.
6074
6075 case TSK_ExplicitInstantiationDefinition:
6076 return GVA_ExplicitTemplateInstantiation;
6077
6078 case TSK_ImplicitInstantiation:
6079 return GVA_TemplateInstantiation;
6080 }
6081 }
6082
6083 return GVA_StrongExternal;
6084}
6085
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006086bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006087 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6088 if (!VD->isFileVarDecl())
6089 return false;
6090 } else if (!isa<FunctionDecl>(D))
6091 return false;
6092
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006093 // Weak references don't produce any output by themselves.
6094 if (D->hasAttr<WeakRefAttr>())
6095 return false;
6096
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006097 // Aliases and used decls are required.
6098 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6099 return true;
6100
6101 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6102 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006103 if (!FD->doesThisDeclarationHaveABody())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006104 return false;
6105
6106 // Constructors and destructors are required.
6107 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6108 return true;
6109
6110 // The key function for a class is required.
6111 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6112 const CXXRecordDecl *RD = MD->getParent();
6113 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6114 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6115 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6116 return true;
6117 }
6118 }
6119
6120 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6121
6122 // static, static inline, always_inline, and extern inline functions can
6123 // always be deferred. Normal inline functions can be deferred in C99/C++.
6124 // Implicit template instantiations can also be deferred in C++.
6125 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6126 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6127 return false;
6128 return true;
6129 }
6130
6131 const VarDecl *VD = cast<VarDecl>(D);
6132 assert(VD->isFileVarDecl() && "Expected file scoped var");
6133
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006134 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6135 return false;
6136
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006137 // Structs that have non-trivial constructors or destructors are required.
6138
6139 // FIXME: Handle references.
6140 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6141 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006142 if (RD->hasDefinition() &&
6143 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006144 return true;
6145 }
6146 }
6147
6148 GVALinkage L = GetGVALinkageForVariable(VD);
6149 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6150 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6151 return false;
6152 }
6153
6154 return true;
6155}
Charles Davis53c59df2010-08-16 03:33:14 +00006156
Charles Davis99202b32010-11-09 18:04:24 +00006157CallingConv ASTContext::getDefaultMethodCallConv() {
6158 // Pass through to the C++ ABI object
6159 return ABI->getDefaultMethodCallConv();
6160}
6161
Jay Foad39c79802011-01-12 09:06:06 +00006162bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006163 // Pass through to the C++ ABI object
6164 return ABI->isNearlyEmpty(RD);
6165}
6166
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006167MangleContext *ASTContext::createMangleContext() {
6168 switch (Target.getCXXABI()) {
6169 case CXXABI_ARM:
6170 case CXXABI_Itanium:
6171 return createItaniumMangleContext(*this, getDiagnostics());
6172 case CXXABI_Microsoft:
6173 return createMicrosoftMangleContext(*this, getDiagnostics());
6174 }
6175 assert(0 && "Unsupported ABI");
6176 return 0;
6177}
6178
Charles Davis53c59df2010-08-16 03:33:14 +00006179CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006180
6181size_t ASTContext::getSideTableAllocatedMemory() const {
6182 size_t bytes = 0;
6183 bytes += ASTRecordLayouts.getMemorySize();
6184 bytes += ObjCLayouts.getMemorySize();
6185 bytes += KeyFunctions.getMemorySize();
6186 bytes += ObjCImpls.getMemorySize();
6187 bytes += BlockVarCopyInits.getMemorySize();
6188 bytes += DeclAttrs.getMemorySize();
6189 bytes += InstantiatedFromStaticDataMember.getMemorySize();
6190 bytes += InstantiatedFromUsingDecl.getMemorySize();
6191 bytes += InstantiatedFromUsingShadowDecl.getMemorySize();
6192 bytes += InstantiatedFromUnnamedFieldDecl.getMemorySize();
6193 return bytes;
6194}
6195