blob: 43c65cf7fba74a7341d3a7f784d1368591c1b860 [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(),
130 SourceLocation(),
131 NTTP->getDepth(),
132 NTTP->getPosition(), 0,
133 T,
134 TInfo,
135 ExpandedTypes.data(),
136 ExpandedTypes.size(),
137 ExpandedTInfos.data());
138 } else {
139 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
140 SourceLocation(),
141 NTTP->getDepth(),
142 NTTP->getPosition(), 0,
143 T,
144 NTTP->isParameterPack(),
145 TInfo);
146 }
147 CanonParams.push_back(Param);
148
149 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000150 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
151 cast<TemplateTemplateParmDecl>(*P)));
152 }
153
154 TemplateTemplateParmDecl *CanonTTP
155 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
156 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000157 TTP->getPosition(),
158 TTP->isParameterPack(),
159 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000160 TemplateParameterList::Create(*this, SourceLocation(),
161 SourceLocation(),
162 CanonParams.data(),
163 CanonParams.size(),
164 SourceLocation()));
165
166 // Get the new insert position for the node we care about.
167 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
168 assert(Canonical == 0 && "Shouldn't be in the map!");
169 (void)Canonical;
170
171 // Create the canonical template template parameter entry.
172 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
173 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
174 return CanonTTP;
175}
176
Charles Davis53c59df2010-08-16 03:33:14 +0000177CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000178 if (!LangOpts.CPlusPlus) return 0;
179
Charles Davis6bcb07a2010-08-19 02:18:14 +0000180 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000181 case CXXABI_ARM:
182 return CreateARMCXXABI(*this);
183 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000184 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000185 case CXXABI_Microsoft:
186 return CreateMicrosoftCXXABI(*this);
187 }
John McCall86353412010-08-21 22:46:04 +0000188 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000189}
190
Chris Lattner465fa322008-10-05 17:34:18 +0000191ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000192 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000193 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000194 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000195 unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000196 TemplateSpecializationTypes(this_()),
197 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000198 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
199 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000200 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000201 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +0000202 cudaConfigureCallDecl(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000203 NullTypeSourceInfo(QualType()),
Charles Davis53c59df2010-08-16 03:33:14 +0000204 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000205 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000206 BuiltinInfo(builtins),
207 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000208 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000209 LastSDM(0, 0),
John McCall147d0212011-02-22 22:38:33 +0000210 UniqueBlockByRefTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000211 ObjCIdRedefinitionType = QualType();
212 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000213 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000214 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000215 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000216 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000217}
218
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000219ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000220 // Release the DenseMaps associated with DeclContext objects.
221 // FIXME: Is this the ideal solution?
222 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000223
Douglas Gregor5b11d492010-07-25 17:53:33 +0000224 // Call all of the deallocation functions.
225 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
226 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000227
Douglas Gregor832940b2010-03-02 23:58:15 +0000228 // Release all of the memory associated with overridden C++ methods.
229 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
230 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
231 OM != OMEnd; ++OM)
232 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000233
Ted Kremenek076baeb2010-06-08 23:00:58 +0000234 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000235 // because they can contain DenseMaps.
236 for (llvm::DenseMap<const ObjCContainerDecl*,
237 const ASTRecordLayout*>::iterator
238 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
239 // Increment in loop to prevent using deallocated memory.
240 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
241 R->Destroy(*this);
242
Ted Kremenek076baeb2010-06-08 23:00:58 +0000243 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
244 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
245 // Increment in loop to prevent using deallocated memory.
246 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
247 R->Destroy(*this);
248 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000249
250 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
251 AEnd = DeclAttrs.end();
252 A != AEnd; ++A)
253 A->second->~AttrVec();
254}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000255
Douglas Gregor1a809332010-05-23 18:26:36 +0000256void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
257 Deallocations.push_back(std::make_pair(Callback, Data));
258}
259
Mike Stump11289f42009-09-09 15:08:12 +0000260void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000261ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
262 ExternalSource.reset(Source.take());
263}
264
Chris Lattner4eb445d2007-01-26 01:27:23 +0000265void ASTContext::PrintStats() const {
266 fprintf(stderr, "*** AST Context Stats:\n");
267 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000268
Douglas Gregora30d0462009-05-26 14:40:08 +0000269 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000270#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000271#define ABSTRACT_TYPE(Name, Parent)
272#include "clang/AST/TypeNodes.def"
273 0 // Extra
274 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000275
Chris Lattner4eb445d2007-01-26 01:27:23 +0000276 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
277 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000278 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000279 }
280
Douglas Gregora30d0462009-05-26 14:40:08 +0000281 unsigned Idx = 0;
282 unsigned TotalBytes = 0;
283#define TYPE(Name, Parent) \
284 if (counts[Idx]) \
285 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
286 TotalBytes += counts[Idx] * sizeof(Name##Type); \
287 ++Idx;
288#define ABSTRACT_TYPE(Name, Parent)
289#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000290
Douglas Gregora30d0462009-05-26 14:40:08 +0000291 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000292
Douglas Gregor7454c562010-07-02 20:37:36 +0000293 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000294 fprintf(stderr, " %u/%u implicit default constructors created\n",
295 NumImplicitDefaultConstructorsDeclared,
296 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000297 fprintf(stderr, " %u/%u implicit copy constructors created\n",
298 NumImplicitCopyConstructorsDeclared,
299 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000300 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
301 NumImplicitCopyAssignmentOperatorsDeclared,
302 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000303 fprintf(stderr, " %u/%u implicit destructors created\n",
304 NumImplicitDestructorsDeclared, NumImplicitDestructors);
305
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000306 if (ExternalSource.get()) {
307 fprintf(stderr, "\n");
308 ExternalSource->PrintStats();
309 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000310
Douglas Gregor5b11d492010-07-25 17:53:33 +0000311 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000312}
313
314
John McCall48f2d582009-10-23 23:03:21 +0000315void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000316 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000317 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000318 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000319}
320
Chris Lattner970e54e2006-11-12 00:37:36 +0000321void ASTContext::InitBuiltinTypes() {
322 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000323
Chris Lattner970e54e2006-11-12 00:37:36 +0000324 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000325 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000326
Chris Lattner970e54e2006-11-12 00:37:36 +0000327 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000328 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000329 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000330 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000331 InitBuiltinType(CharTy, BuiltinType::Char_S);
332 else
333 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000334 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000335 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
336 InitBuiltinType(ShortTy, BuiltinType::Short);
337 InitBuiltinType(IntTy, BuiltinType::Int);
338 InitBuiltinType(LongTy, BuiltinType::Long);
339 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000340
Chris Lattner970e54e2006-11-12 00:37:36 +0000341 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000342 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
343 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
344 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
345 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
346 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000347
Chris Lattner970e54e2006-11-12 00:37:36 +0000348 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000349 InitBuiltinType(FloatTy, BuiltinType::Float);
350 InitBuiltinType(DoubleTy, BuiltinType::Double);
351 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000352
Chris Lattnerf122cef2009-04-30 02:43:43 +0000353 // GNU extension, 128-bit integers.
354 InitBuiltinType(Int128Ty, BuiltinType::Int128);
355 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
356
Chris Lattnerad3467e2010-12-25 23:25:43 +0000357 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
358 if (!LangOpts.ShortWChar)
359 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
360 else // -fshort-wchar makes wchar_t be unsigned.
361 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
362 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000363 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000364
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000365 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
366 InitBuiltinType(Char16Ty, BuiltinType::Char16);
367 else // C99
368 Char16Ty = getFromTargetType(Target.getChar16Type());
369
370 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
371 InitBuiltinType(Char32Ty, BuiltinType::Char32);
372 else // C99
373 Char32Ty = getFromTargetType(Target.getChar32Type());
374
Douglas Gregor4619e432008-12-05 23:32:09 +0000375 // Placeholder type for type-dependent expressions whose type is
376 // completely unknown. No code should ever check a type against
377 // DependentTy and users should never see it; however, it is here to
378 // help diagnose failures to properly check for type-dependent
379 // expressions.
380 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000381
John McCall36e7fe32010-10-12 00:20:44 +0000382 // Placeholder type for functions.
383 InitBuiltinType(OverloadTy, BuiltinType::Overload);
384
Chris Lattner970e54e2006-11-12 00:37:36 +0000385 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000386 FloatComplexTy = getComplexType(FloatTy);
387 DoubleComplexTy = getComplexType(DoubleTy);
388 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000389
Steve Naroff66e9f332007-10-15 14:41:52 +0000390 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000391
Steve Naroff1329fa02009-07-15 18:40:39 +0000392 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
393 ObjCIdTypedefType = QualType();
394 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000395 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000396
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000397 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000398 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
399 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000400 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000401
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000402 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000403
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000404 // void * type
405 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000406
407 // nullptr type (C++0x 2.14.7)
408 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000409}
410
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000411Diagnostic &ASTContext::getDiagnostics() const {
412 return SourceMgr.getDiagnostics();
413}
414
Douglas Gregor561eceb2010-08-30 16:49:28 +0000415AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
416 AttrVec *&Result = DeclAttrs[D];
417 if (!Result) {
418 void *Mem = Allocate(sizeof(AttrVec));
419 Result = new (Mem) AttrVec;
420 }
421
422 return *Result;
423}
424
425/// \brief Erase the attributes corresponding to the given declaration.
426void ASTContext::eraseDeclAttrs(const Decl *D) {
427 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
428 if (Pos != DeclAttrs.end()) {
429 Pos->second->~AttrVec();
430 DeclAttrs.erase(Pos);
431 }
432}
433
434
Douglas Gregor86d142a2009-10-08 07:24:58 +0000435MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000436ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000437 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000438 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000439 = InstantiatedFromStaticDataMember.find(Var);
440 if (Pos == InstantiatedFromStaticDataMember.end())
441 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000442
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000443 return Pos->second;
444}
445
Mike Stump11289f42009-09-09 15:08:12 +0000446void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000447ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000448 TemplateSpecializationKind TSK,
449 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000450 assert(Inst->isStaticDataMember() && "Not a static data member");
451 assert(Tmpl->isStaticDataMember() && "Not a static data member");
452 assert(!InstantiatedFromStaticDataMember[Inst] &&
453 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000454 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000455 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000456}
457
John McCalle61f2ba2009-11-18 02:36:19 +0000458NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000459ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000460 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000461 = InstantiatedFromUsingDecl.find(UUD);
462 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000463 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000464
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000465 return Pos->second;
466}
467
468void
John McCallb96ec562009-12-04 22:46:56 +0000469ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
470 assert((isa<UsingDecl>(Pattern) ||
471 isa<UnresolvedUsingValueDecl>(Pattern) ||
472 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
473 "pattern decl is not a using decl");
474 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
475 InstantiatedFromUsingDecl[Inst] = Pattern;
476}
477
478UsingShadowDecl *
479ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
480 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
481 = InstantiatedFromUsingShadowDecl.find(Inst);
482 if (Pos == InstantiatedFromUsingShadowDecl.end())
483 return 0;
484
485 return Pos->second;
486}
487
488void
489ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
490 UsingShadowDecl *Pattern) {
491 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
492 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000493}
494
Anders Carlsson5da84842009-09-01 04:26:58 +0000495FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
496 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
497 = InstantiatedFromUnnamedFieldDecl.find(Field);
498 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
499 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000500
Anders Carlsson5da84842009-09-01 04:26:58 +0000501 return Pos->second;
502}
503
504void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
505 FieldDecl *Tmpl) {
506 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
507 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
508 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
509 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000510
Anders Carlsson5da84842009-09-01 04:26:58 +0000511 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
512}
513
Douglas Gregor832940b2010-03-02 23:58:15 +0000514ASTContext::overridden_cxx_method_iterator
515ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
516 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
517 = OverriddenMethods.find(Method);
518 if (Pos == OverriddenMethods.end())
519 return 0;
520
521 return Pos->second.begin();
522}
523
524ASTContext::overridden_cxx_method_iterator
525ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
526 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
527 = OverriddenMethods.find(Method);
528 if (Pos == OverriddenMethods.end())
529 return 0;
530
531 return Pos->second.end();
532}
533
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000534unsigned
535ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
536 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
537 = OverriddenMethods.find(Method);
538 if (Pos == OverriddenMethods.end())
539 return 0;
540
541 return Pos->second.size();
542}
543
Douglas Gregor832940b2010-03-02 23:58:15 +0000544void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
545 const CXXMethodDecl *Overridden) {
546 OverriddenMethods[Method].push_back(Overridden);
547}
548
Chris Lattner53cfe802007-07-18 17:52:12 +0000549//===----------------------------------------------------------------------===//
550// Type Sizing and Analysis
551//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000552
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000553/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
554/// scalar floating point type.
555const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000556 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000557 assert(BT && "Not a floating point type!");
558 switch (BT->getKind()) {
559 default: assert(0 && "Not a floating point type!");
560 case BuiltinType::Float: return Target.getFloatFormat();
561 case BuiltinType::Double: return Target.getDoubleFormat();
562 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
563 }
564}
565
Ken Dyck160146e2010-01-27 17:10:57 +0000566/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000567/// specified decl. Note that bitfields do not have a valid alignment, so
568/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000569/// If @p RefAsPointee, references are treated like their underlying type
570/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000571CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000572 unsigned Align = Target.getCharWidth();
573
John McCall94268702010-10-08 18:24:19 +0000574 bool UseAlignAttrOnly = false;
575 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
576 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000577
John McCall94268702010-10-08 18:24:19 +0000578 // __attribute__((aligned)) can increase or decrease alignment
579 // *except* on a struct or struct member, where it only increases
580 // alignment unless 'packed' is also specified.
581 //
582 // It is an error for [[align]] to decrease alignment, so we can
583 // ignore that possibility; Sema should diagnose it.
584 if (isa<FieldDecl>(D)) {
585 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
586 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
587 } else {
588 UseAlignAttrOnly = true;
589 }
590 }
591
John McCall4e819612011-01-20 07:57:12 +0000592 // If we're using the align attribute only, just ignore everything
593 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000594 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000595 // do nothing
596
John McCall94268702010-10-08 18:24:19 +0000597 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000598 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000599 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000600 if (RefAsPointee)
601 T = RT->getPointeeType();
602 else
603 T = getPointerType(RT->getPointeeType());
604 }
605 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000606 // Adjust alignments of declarations with array type by the
607 // large-array alignment on the target.
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000608 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000609 const ArrayType *arrayType;
610 if (MinWidth && (arrayType = getAsArrayType(T))) {
611 if (isa<VariableArrayType>(arrayType))
612 Align = std::max(Align, Target.getLargeArrayAlign());
613 else if (isa<ConstantArrayType>(arrayType) &&
614 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
615 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000616
John McCall33ddac02011-01-19 10:06:00 +0000617 // Walk through any array types while we're at it.
618 T = getBaseElementType(arrayType);
619 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000620 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
621 }
John McCall4e819612011-01-20 07:57:12 +0000622
623 // Fields can be subject to extra alignment constraints, like if
624 // the field is packed, the struct is packed, or the struct has a
625 // a max-field-alignment constraint (#pragma pack). So calculate
626 // the actual alignment of the field within the struct, and then
627 // (as we're expected to) constrain that by the alignment of the type.
628 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
629 // So calculate the alignment of the field.
630 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
631
632 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000633 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000634
635 // Use the GCD of that and the offset within the record.
636 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
637 if (offset > 0) {
638 // Alignment is always a power of 2, so the GCD will be a power of 2,
639 // which means we get to do this crazy thing instead of Euclid's.
640 uint64_t lowBitOfOffset = offset & (~offset + 1);
641 if (lowBitOfOffset < fieldAlign)
642 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
643 }
644
645 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000646 }
Chris Lattner68061312009-01-24 21:53:27 +0000647 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000648
Ken Dyckcc56c542011-01-15 18:38:59 +0000649 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000650}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000651
John McCall87fe5d52010-05-20 01:18:31 +0000652std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000653ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000654 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000655 return std::make_pair(toCharUnitsFromBits(Info.first),
656 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000657}
658
659std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000660ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000661 return getTypeInfoInChars(T.getTypePtr());
662}
663
Chris Lattner983a8bb2007-07-13 22:13:22 +0000664/// getTypeSize - Return the size of the specified type, in bits. This method
665/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000666///
667/// FIXME: Pointers into different addr spaces could have different sizes and
668/// alignment requirements: getPointerInfo should take an AddrSpace, this
669/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000670std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000671ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000672 uint64_t Width=0;
673 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000674 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000675#define TYPE(Class, Base)
676#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000677#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000678#define DEPENDENT_TYPE(Class, Base) case Type::Class:
679#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000680 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000681 break;
682
Chris Lattner355332d2007-07-13 22:27:08 +0000683 case Type::FunctionNoProto:
684 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000685 // GCC extension: alignof(function) = 32 bits
686 Width = 0;
687 Align = 32;
688 break;
689
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000690 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000691 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000692 Width = 0;
693 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
694 break;
695
Steve Naroff5c131802007-08-30 01:06:46 +0000696 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000697 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000698
Chris Lattner37e05872008-03-05 18:54:05 +0000699 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000700 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000701 Align = EltInfo.second;
702 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000703 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000704 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000705 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000706 const VectorType *VT = cast<VectorType>(T);
707 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
708 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000709 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000710 // If the alignment is not a power of 2, round up to the next power of 2.
711 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000712 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000713 Align = llvm::NextPowerOf2(Align);
714 Width = llvm::RoundUpToAlignment(Width, Align);
715 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000716 break;
717 }
Chris Lattner647fb222007-07-18 18:26:58 +0000718
Chris Lattner7570e9c2008-03-08 08:52:55 +0000719 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000720 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000721 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000722 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000723 // GCC extension: alignof(void) = 8 bits.
724 Width = 0;
725 Align = 8;
726 break;
727
Chris Lattner6a4f7452007-12-19 19:23:28 +0000728 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000729 Width = Target.getBoolWidth();
730 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000731 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000732 case BuiltinType::Char_S:
733 case BuiltinType::Char_U:
734 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000735 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000736 Width = Target.getCharWidth();
737 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000738 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000739 case BuiltinType::WChar_S:
740 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000741 Width = Target.getWCharWidth();
742 Align = Target.getWCharAlign();
743 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000744 case BuiltinType::Char16:
745 Width = Target.getChar16Width();
746 Align = Target.getChar16Align();
747 break;
748 case BuiltinType::Char32:
749 Width = Target.getChar32Width();
750 Align = Target.getChar32Align();
751 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000752 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000753 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000754 Width = Target.getShortWidth();
755 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000756 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000757 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000758 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000759 Width = Target.getIntWidth();
760 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000761 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000762 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000763 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000764 Width = Target.getLongWidth();
765 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000766 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000767 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000768 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000769 Width = Target.getLongLongWidth();
770 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000771 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000772 case BuiltinType::Int128:
773 case BuiltinType::UInt128:
774 Width = 128;
775 Align = 128; // int128_t is 128-bit aligned on all targets.
776 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000777 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000778 Width = Target.getFloatWidth();
779 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000780 break;
781 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000782 Width = Target.getDoubleWidth();
783 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000784 break;
785 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000786 Width = Target.getLongDoubleWidth();
787 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000788 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000789 case BuiltinType::NullPtr:
790 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
791 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000792 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000793 case BuiltinType::ObjCId:
794 case BuiltinType::ObjCClass:
795 case BuiltinType::ObjCSel:
796 Width = Target.getPointerWidth(0);
797 Align = Target.getPointerAlign(0);
798 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000799 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000800 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000801 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000802 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000803 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000804 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000805 case Type::BlockPointer: {
806 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
807 Width = Target.getPointerWidth(AS);
808 Align = Target.getPointerAlign(AS);
809 break;
810 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000811 case Type::LValueReference:
812 case Type::RValueReference: {
813 // alignof and sizeof should never enter this code path here, so we go
814 // the pointer route.
815 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
816 Width = Target.getPointerWidth(AS);
817 Align = Target.getPointerAlign(AS);
818 break;
819 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000820 case Type::Pointer: {
821 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000822 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000823 Align = Target.getPointerAlign(AS);
824 break;
825 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000826 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000827 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000828 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000829 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000830 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000831 Align = PtrDiffInfo.second;
832 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000833 }
Chris Lattner647fb222007-07-18 18:26:58 +0000834 case Type::Complex: {
835 // Complex types have the same alignment as their elements, but twice the
836 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000837 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000838 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000839 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000840 Align = EltInfo.second;
841 break;
842 }
John McCall8b07ec22010-05-15 11:32:37 +0000843 case Type::ObjCObject:
844 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000845 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000846 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000847 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000848 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000849 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000850 break;
851 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000852 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000853 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000854 const TagType *TT = cast<TagType>(T);
855
856 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000857 Width = 1;
858 Align = 1;
859 break;
860 }
Mike Stump11289f42009-09-09 15:08:12 +0000861
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000862 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000863 return getTypeInfo(ET->getDecl()->getIntegerType());
864
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000865 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000866 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000867 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000868 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +0000869 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000870 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000871
Chris Lattner63d2b362009-10-22 05:17:15 +0000872 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000873 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
874 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000875
Richard Smith30482bc2011-02-20 03:19:35 +0000876 case Type::Auto: {
877 const AutoType *A = cast<AutoType>(T);
878 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +0000879 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +0000880 }
881
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000882 case Type::Paren:
883 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
884
Douglas Gregoref462e62009-04-30 17:32:17 +0000885 case Type::Typedef: {
886 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000887 std::pair<uint64_t, unsigned> Info
888 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +0000889 // If the typedef has an aligned attribute on it, it overrides any computed
890 // alignment we have. This violates the GCC documentation (which says that
891 // attribute(aligned) can only round up) but matches its implementation.
892 if (unsigned AttrAlign = Typedef->getMaxAlignment())
893 Align = AttrAlign;
894 else
895 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +0000896 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000897 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000898 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000899
900 case Type::TypeOfExpr:
901 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
902 .getTypePtr());
903
904 case Type::TypeOf:
905 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
906
Anders Carlsson81df7b82009-06-24 19:06:50 +0000907 case Type::Decltype:
908 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
909 .getTypePtr());
910
Abramo Bagnara6150c882010-05-11 21:36:43 +0000911 case Type::Elaborated:
912 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000913
John McCall81904512011-01-06 01:58:22 +0000914 case Type::Attributed:
915 return getTypeInfo(
916 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
917
Douglas Gregoref462e62009-04-30 17:32:17 +0000918 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000919 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000920 "Cannot request the size of a dependent type");
921 // FIXME: this is likely to be wrong once we support template
922 // aliases, since a template alias could refer to a typedef that
923 // has an __aligned__ attribute on it.
924 return getTypeInfo(getCanonicalType(T));
925 }
Mike Stump11289f42009-09-09 15:08:12 +0000926
Chris Lattner53cfe802007-07-18 17:52:12 +0000927 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000928 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000929}
930
Ken Dyckcc56c542011-01-15 18:38:59 +0000931/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
932CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
933 return CharUnits::fromQuantity(BitSize / getCharWidth());
934}
935
Ken Dyckb0fcc592011-02-11 01:54:29 +0000936/// toBits - Convert a size in characters to a size in characters.
937int64_t ASTContext::toBits(CharUnits CharSize) const {
938 return CharSize.getQuantity() * getCharWidth();
939}
940
Ken Dyck8c89d592009-12-22 14:23:30 +0000941/// getTypeSizeInChars - Return the size of the specified type, in characters.
942/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000943CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000944 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000945}
Jay Foad39c79802011-01-12 09:06:06 +0000946CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000947 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000948}
949
Ken Dycka6046ab2010-01-26 17:25:18 +0000950/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000951/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000952CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000953 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000954}
Jay Foad39c79802011-01-12 09:06:06 +0000955CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000956 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000957}
958
Chris Lattnera3402cd2009-01-27 18:08:34 +0000959/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
960/// type for the current target in bits. This can be different than the ABI
961/// alignment in cases where it is beneficial for performance to overalign
962/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +0000963unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +0000964 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000965
966 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000967 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000968 T = CT->getElementType().getTypePtr();
969 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
970 T->isSpecificBuiltinType(BuiltinType::LongLong))
971 return std::max(ABIAlign, (unsigned)getTypeSize(T));
972
Chris Lattnera3402cd2009-01-27 18:08:34 +0000973 return ABIAlign;
974}
975
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000976/// ShallowCollectObjCIvars -
977/// Collect all ivars, including those synthesized, in the current class.
978///
979void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +0000980 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000981 // FIXME. This need be removed but there are two many places which
982 // assume const-ness of ObjCInterfaceDecl
983 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
984 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
985 Iv= Iv->getNextIvar())
986 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000987}
988
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000989/// DeepCollectObjCIvars -
990/// This routine first collects all declared, but not synthesized, ivars in
991/// super class and then collects all ivars, including those synthesized for
992/// current class. This routine is used for implementation of current class
993/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000994///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000995void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
996 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +0000997 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000998 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
999 DeepCollectObjCIvars(SuperClass, false, Ivars);
1000 if (!leafClass) {
1001 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1002 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001003 Ivars.push_back(*I);
1004 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001005 else
1006 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001007}
1008
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001009/// CollectInheritedProtocols - Collect all protocols in current class and
1010/// those inherited by it.
1011void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001012 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001013 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001014 // We can use protocol_iterator here instead of
1015 // all_referenced_protocol_iterator since we are walking all categories.
1016 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1017 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001018 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001019 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001020 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001021 PE = Proto->protocol_end(); P != PE; ++P) {
1022 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001023 CollectInheritedProtocols(*P, Protocols);
1024 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001025 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001026
1027 // Categories of this Interface.
1028 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1029 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1030 CollectInheritedProtocols(CDeclChain, Protocols);
1031 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1032 while (SD) {
1033 CollectInheritedProtocols(SD, Protocols);
1034 SD = SD->getSuperClass();
1035 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001036 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001037 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001038 PE = OC->protocol_end(); P != PE; ++P) {
1039 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001040 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001041 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1042 PE = Proto->protocol_end(); P != PE; ++P)
1043 CollectInheritedProtocols(*P, Protocols);
1044 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001045 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001046 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1047 PE = OP->protocol_end(); P != PE; ++P) {
1048 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001049 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001050 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1051 PE = Proto->protocol_end(); P != PE; ++P)
1052 CollectInheritedProtocols(*P, Protocols);
1053 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001054 }
1055}
1056
Jay Foad39c79802011-01-12 09:06:06 +00001057unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001058 unsigned count = 0;
1059 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001060 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1061 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001062 count += CDecl->ivar_size();
1063
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001064 // Count ivar defined in this class's implementation. This
1065 // includes synthesized ivars.
1066 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001067 count += ImplDecl->ivar_size();
1068
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001069 return count;
1070}
1071
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001072/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1073ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1074 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1075 I = ObjCImpls.find(D);
1076 if (I != ObjCImpls.end())
1077 return cast<ObjCImplementationDecl>(I->second);
1078 return 0;
1079}
1080/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1081ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1082 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1083 I = ObjCImpls.find(D);
1084 if (I != ObjCImpls.end())
1085 return cast<ObjCCategoryImplDecl>(I->second);
1086 return 0;
1087}
1088
1089/// \brief Set the implementation of ObjCInterfaceDecl.
1090void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1091 ObjCImplementationDecl *ImplD) {
1092 assert(IFaceD && ImplD && "Passed null params");
1093 ObjCImpls[IFaceD] = ImplD;
1094}
1095/// \brief Set the implementation of ObjCCategoryDecl.
1096void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1097 ObjCCategoryImplDecl *ImplD) {
1098 assert(CatD && ImplD && "Passed null params");
1099 ObjCImpls[CatD] = ImplD;
1100}
1101
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001102/// \brief Get the copy initialization expression of VarDecl,or NULL if
1103/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001104Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001105 assert(VD && "Passed null params");
1106 assert(VD->hasAttr<BlocksAttr>() &&
1107 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001108 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001109 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001110 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1111}
1112
1113/// \brief Set the copy inialization expression of a block var decl.
1114void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1115 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001116 assert(VD->hasAttr<BlocksAttr>() &&
1117 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001118 BlockVarCopyInits[VD] = Init;
1119}
1120
John McCallbcd03502009-12-07 02:54:59 +00001121/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001122///
John McCallbcd03502009-12-07 02:54:59 +00001123/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001124/// the TypeLoc wrappers.
1125///
1126/// \param T the type that will be the basis for type source info. This type
1127/// should refer to how the declarator was written in source code, not to
1128/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001129TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001130 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001131 if (!DataSize)
1132 DataSize = TypeLoc::getFullDataSizeForType(T);
1133 else
1134 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001135 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001136
John McCallbcd03502009-12-07 02:54:59 +00001137 TypeSourceInfo *TInfo =
1138 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1139 new (TInfo) TypeSourceInfo(T);
1140 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001141}
1142
John McCallbcd03502009-12-07 02:54:59 +00001143TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001144 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001145 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001146 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001147 return DI;
1148}
1149
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001150const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001151ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001152 return getObjCLayout(D, 0);
1153}
1154
1155const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001156ASTContext::getASTObjCImplementationLayout(
1157 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001158 return getObjCLayout(D->getClassInterface(), D);
1159}
1160
Chris Lattner983a8bb2007-07-13 22:13:22 +00001161//===----------------------------------------------------------------------===//
1162// Type creation/memoization methods
1163//===----------------------------------------------------------------------===//
1164
Jay Foad39c79802011-01-12 09:06:06 +00001165QualType
John McCall33ddac02011-01-19 10:06:00 +00001166ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1167 unsigned fastQuals = quals.getFastQualifiers();
1168 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001169
1170 // Check if we've already instantiated this type.
1171 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001172 ExtQuals::Profile(ID, baseType, quals);
1173 void *insertPos = 0;
1174 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1175 assert(eq->getQualifiers() == quals);
1176 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001177 }
1178
John McCall33ddac02011-01-19 10:06:00 +00001179 // If the base type is not canonical, make the appropriate canonical type.
1180 QualType canon;
1181 if (!baseType->isCanonicalUnqualified()) {
1182 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1183 canonSplit.second.addConsistentQualifiers(quals);
1184 canon = getExtQualType(canonSplit.first, canonSplit.second);
1185
1186 // Re-find the insert position.
1187 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1188 }
1189
1190 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1191 ExtQualNodes.InsertNode(eq, insertPos);
1192 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001193}
1194
Jay Foad39c79802011-01-12 09:06:06 +00001195QualType
1196ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001197 QualType CanT = getCanonicalType(T);
1198 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001199 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001200
John McCall8ccfcb52009-09-24 19:53:00 +00001201 // If we are composing extended qualifiers together, merge together
1202 // into one ExtQuals node.
1203 QualifierCollector Quals;
1204 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001205
John McCall8ccfcb52009-09-24 19:53:00 +00001206 // If this type already has an address space specified, it cannot get
1207 // another one.
1208 assert(!Quals.hasAddressSpace() &&
1209 "Type cannot be in multiple addr spaces!");
1210 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001211
John McCall8ccfcb52009-09-24 19:53:00 +00001212 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001213}
1214
Chris Lattnerd60183d2009-02-18 22:53:11 +00001215QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001216 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001217 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001218 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001219 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001220
John McCall53fa7142010-12-24 02:08:15 +00001221 if (const PointerType *ptr = T->getAs<PointerType>()) {
1222 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001223 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001224 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1225 return getPointerType(ResultType);
1226 }
1227 }
Mike Stump11289f42009-09-09 15:08:12 +00001228
John McCall8ccfcb52009-09-24 19:53:00 +00001229 // If we are composing extended qualifiers together, merge together
1230 // into one ExtQuals node.
1231 QualifierCollector Quals;
1232 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001233
John McCall8ccfcb52009-09-24 19:53:00 +00001234 // If this type already has an ObjCGC specified, it cannot get
1235 // another one.
1236 assert(!Quals.hasObjCGCAttr() &&
1237 "Type cannot have multiple ObjCGCs!");
1238 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001239
John McCall8ccfcb52009-09-24 19:53:00 +00001240 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001241}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001242
John McCall4f5019e2010-12-19 02:44:49 +00001243const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1244 FunctionType::ExtInfo Info) {
1245 if (T->getExtInfo() == Info)
1246 return T;
1247
1248 QualType Result;
1249 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1250 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1251 } else {
1252 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1253 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1254 EPI.ExtInfo = Info;
1255 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1256 FPT->getNumArgs(), EPI);
1257 }
1258
1259 return cast<FunctionType>(Result.getTypePtr());
1260}
1261
Chris Lattnerc6395932007-06-22 20:56:16 +00001262/// getComplexType - Return the uniqued reference to the type for a complex
1263/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001264QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001265 // Unique pointers, to guarantee there is only one pointer of a particular
1266 // structure.
1267 llvm::FoldingSetNodeID ID;
1268 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001269
Chris Lattnerc6395932007-06-22 20:56:16 +00001270 void *InsertPos = 0;
1271 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1272 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001273
Chris Lattnerc6395932007-06-22 20:56:16 +00001274 // If the pointee type isn't canonical, this won't be a canonical type either,
1275 // so fill in the canonical type field.
1276 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001277 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001278 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001279
Chris Lattnerc6395932007-06-22 20:56:16 +00001280 // Get the new insert position for the node we care about.
1281 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001282 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001283 }
John McCall90d1c2d2009-09-24 23:30:46 +00001284 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001285 Types.push_back(New);
1286 ComplexTypes.InsertNode(New, InsertPos);
1287 return QualType(New, 0);
1288}
1289
Chris Lattner970e54e2006-11-12 00:37:36 +00001290/// getPointerType - Return the uniqued reference to the type for a pointer to
1291/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001292QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001293 // Unique pointers, to guarantee there is only one pointer of a particular
1294 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001295 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001296 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001297
Chris Lattner67521df2007-01-27 01:29:36 +00001298 void *InsertPos = 0;
1299 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001300 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001301
Chris Lattner7ccecb92006-11-12 08:50:50 +00001302 // If the pointee type isn't canonical, this won't be a canonical type either,
1303 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001304 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001305 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001306 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001307
Chris Lattner67521df2007-01-27 01:29:36 +00001308 // Get the new insert position for the node we care about.
1309 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001310 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001311 }
John McCall90d1c2d2009-09-24 23:30:46 +00001312 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001313 Types.push_back(New);
1314 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001315 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001316}
1317
Mike Stump11289f42009-09-09 15:08:12 +00001318/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001319/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001320QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001321 assert(T->isFunctionType() && "block of function types only");
1322 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001323 // structure.
1324 llvm::FoldingSetNodeID ID;
1325 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001326
Steve Naroffec33ed92008-08-27 16:04:49 +00001327 void *InsertPos = 0;
1328 if (BlockPointerType *PT =
1329 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1330 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001331
1332 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001333 // type either so fill in the canonical type field.
1334 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001335 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001336 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001337
Steve Naroffec33ed92008-08-27 16:04:49 +00001338 // Get the new insert position for the node we care about.
1339 BlockPointerType *NewIP =
1340 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001341 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001342 }
John McCall90d1c2d2009-09-24 23:30:46 +00001343 BlockPointerType *New
1344 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001345 Types.push_back(New);
1346 BlockPointerTypes.InsertNode(New, InsertPos);
1347 return QualType(New, 0);
1348}
1349
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001350/// getLValueReferenceType - Return the uniqued reference to the type for an
1351/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001352QualType
1353ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001354 // Unique pointers, to guarantee there is only one pointer of a particular
1355 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001356 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001357 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001358
1359 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001360 if (LValueReferenceType *RT =
1361 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001362 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001363
John McCallfc93cf92009-10-22 22:37:11 +00001364 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1365
Bill Wendling3708c182007-05-27 10:15:43 +00001366 // If the referencee type isn't canonical, this won't be a canonical type
1367 // either, so fill in the canonical type field.
1368 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001369 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1370 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1371 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001372
Bill Wendling3708c182007-05-27 10:15:43 +00001373 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001374 LValueReferenceType *NewIP =
1375 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001376 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001377 }
1378
John McCall90d1c2d2009-09-24 23:30:46 +00001379 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001380 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1381 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001382 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001383 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001384
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001385 return QualType(New, 0);
1386}
1387
1388/// getRValueReferenceType - Return the uniqued reference to the type for an
1389/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001390QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001391 // Unique pointers, to guarantee there is only one pointer of a particular
1392 // structure.
1393 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001394 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001395
1396 void *InsertPos = 0;
1397 if (RValueReferenceType *RT =
1398 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1399 return QualType(RT, 0);
1400
John McCallfc93cf92009-10-22 22:37:11 +00001401 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1402
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001403 // If the referencee type isn't canonical, this won't be a canonical type
1404 // either, so fill in the canonical type field.
1405 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001406 if (InnerRef || !T.isCanonical()) {
1407 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1408 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001409
1410 // Get the new insert position for the node we care about.
1411 RValueReferenceType *NewIP =
1412 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001413 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001414 }
1415
John McCall90d1c2d2009-09-24 23:30:46 +00001416 RValueReferenceType *New
1417 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001418 Types.push_back(New);
1419 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001420 return QualType(New, 0);
1421}
1422
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001423/// getMemberPointerType - Return the uniqued reference to the type for a
1424/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001425QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001426 // Unique pointers, to guarantee there is only one pointer of a particular
1427 // structure.
1428 llvm::FoldingSetNodeID ID;
1429 MemberPointerType::Profile(ID, T, Cls);
1430
1431 void *InsertPos = 0;
1432 if (MemberPointerType *PT =
1433 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1434 return QualType(PT, 0);
1435
1436 // If the pointee or class type isn't canonical, this won't be a canonical
1437 // type either, so fill in the canonical type field.
1438 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001439 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001440 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1441
1442 // Get the new insert position for the node we care about.
1443 MemberPointerType *NewIP =
1444 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001445 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001446 }
John McCall90d1c2d2009-09-24 23:30:46 +00001447 MemberPointerType *New
1448 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001449 Types.push_back(New);
1450 MemberPointerTypes.InsertNode(New, InsertPos);
1451 return QualType(New, 0);
1452}
1453
Mike Stump11289f42009-09-09 15:08:12 +00001454/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001455/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001456QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001457 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001458 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001459 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001460 assert((EltTy->isDependentType() ||
1461 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001462 "Constant array of VLAs is illegal!");
1463
Chris Lattnere2df3f92009-05-13 04:12:56 +00001464 // Convert the array size into a canonical width matching the pointer size for
1465 // the target.
1466 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001467 ArySize =
1468 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001469
Chris Lattner23b7eb62007-06-15 23:05:46 +00001470 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001471 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001472
Chris Lattner36f8e652007-01-27 08:31:04 +00001473 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001474 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001475 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001476 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001477
John McCall33ddac02011-01-19 10:06:00 +00001478 // If the element type isn't canonical or has qualifiers, this won't
1479 // be a canonical type either, so fill in the canonical type field.
1480 QualType Canon;
1481 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1482 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1483 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001484 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001485 Canon = getQualifiedType(Canon, canonSplit.second);
1486
Chris Lattner36f8e652007-01-27 08:31:04 +00001487 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001488 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001489 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001490 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001491 }
Mike Stump11289f42009-09-09 15:08:12 +00001492
John McCall90d1c2d2009-09-24 23:30:46 +00001493 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001494 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001495 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001496 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001497 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001498}
1499
John McCall06549462011-01-18 08:40:38 +00001500/// getVariableArrayDecayedType - Turns the given type, which may be
1501/// variably-modified, into the corresponding type with all the known
1502/// sizes replaced with [*].
1503QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1504 // Vastly most common case.
1505 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001506
John McCall06549462011-01-18 08:40:38 +00001507 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001508
John McCall06549462011-01-18 08:40:38 +00001509 SplitQualType split = type.getSplitDesugaredType();
1510 const Type *ty = split.first;
1511 switch (ty->getTypeClass()) {
1512#define TYPE(Class, Base)
1513#define ABSTRACT_TYPE(Class, Base)
1514#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1515#include "clang/AST/TypeNodes.def"
1516 llvm_unreachable("didn't desugar past all non-canonical types?");
1517
1518 // These types should never be variably-modified.
1519 case Type::Builtin:
1520 case Type::Complex:
1521 case Type::Vector:
1522 case Type::ExtVector:
1523 case Type::DependentSizedExtVector:
1524 case Type::ObjCObject:
1525 case Type::ObjCInterface:
1526 case Type::ObjCObjectPointer:
1527 case Type::Record:
1528 case Type::Enum:
1529 case Type::UnresolvedUsing:
1530 case Type::TypeOfExpr:
1531 case Type::TypeOf:
1532 case Type::Decltype:
1533 case Type::DependentName:
1534 case Type::InjectedClassName:
1535 case Type::TemplateSpecialization:
1536 case Type::DependentTemplateSpecialization:
1537 case Type::TemplateTypeParm:
1538 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001539 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001540 case Type::PackExpansion:
1541 llvm_unreachable("type should never be variably-modified");
1542
1543 // These types can be variably-modified but should never need to
1544 // further decay.
1545 case Type::FunctionNoProto:
1546 case Type::FunctionProto:
1547 case Type::BlockPointer:
1548 case Type::MemberPointer:
1549 return type;
1550
1551 // These types can be variably-modified. All these modifications
1552 // preserve structure except as noted by comments.
1553 // TODO: if we ever care about optimizing VLAs, there are no-op
1554 // optimizations available here.
1555 case Type::Pointer:
1556 result = getPointerType(getVariableArrayDecayedType(
1557 cast<PointerType>(ty)->getPointeeType()));
1558 break;
1559
1560 case Type::LValueReference: {
1561 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1562 result = getLValueReferenceType(
1563 getVariableArrayDecayedType(lv->getPointeeType()),
1564 lv->isSpelledAsLValue());
1565 break;
1566 }
1567
1568 case Type::RValueReference: {
1569 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1570 result = getRValueReferenceType(
1571 getVariableArrayDecayedType(lv->getPointeeType()));
1572 break;
1573 }
1574
1575 case Type::ConstantArray: {
1576 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1577 result = getConstantArrayType(
1578 getVariableArrayDecayedType(cat->getElementType()),
1579 cat->getSize(),
1580 cat->getSizeModifier(),
1581 cat->getIndexTypeCVRQualifiers());
1582 break;
1583 }
1584
1585 case Type::DependentSizedArray: {
1586 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1587 result = getDependentSizedArrayType(
1588 getVariableArrayDecayedType(dat->getElementType()),
1589 dat->getSizeExpr(),
1590 dat->getSizeModifier(),
1591 dat->getIndexTypeCVRQualifiers(),
1592 dat->getBracketsRange());
1593 break;
1594 }
1595
1596 // Turn incomplete types into [*] types.
1597 case Type::IncompleteArray: {
1598 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1599 result = getVariableArrayType(
1600 getVariableArrayDecayedType(iat->getElementType()),
1601 /*size*/ 0,
1602 ArrayType::Normal,
1603 iat->getIndexTypeCVRQualifiers(),
1604 SourceRange());
1605 break;
1606 }
1607
1608 // Turn VLA types into [*] types.
1609 case Type::VariableArray: {
1610 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1611 result = getVariableArrayType(
1612 getVariableArrayDecayedType(vat->getElementType()),
1613 /*size*/ 0,
1614 ArrayType::Star,
1615 vat->getIndexTypeCVRQualifiers(),
1616 vat->getBracketsRange());
1617 break;
1618 }
1619 }
1620
1621 // Apply the top-level qualifiers from the original.
1622 return getQualifiedType(result, split.second);
1623}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001624
Steve Naroffcadebd02007-08-30 18:14:25 +00001625/// getVariableArrayType - Returns a non-unique reference to the type for a
1626/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001627QualType ASTContext::getVariableArrayType(QualType EltTy,
1628 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001629 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001630 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001631 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001632 // Since we don't unique expressions, it isn't possible to unique VLA's
1633 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001634 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001635
John McCall33ddac02011-01-19 10:06:00 +00001636 // Be sure to pull qualifiers off the element type.
1637 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1638 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1639 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001640 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001641 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001642 }
1643
John McCall90d1c2d2009-09-24 23:30:46 +00001644 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001645 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001646
1647 VariableArrayTypes.push_back(New);
1648 Types.push_back(New);
1649 return QualType(New, 0);
1650}
1651
Douglas Gregor4619e432008-12-05 23:32:09 +00001652/// getDependentSizedArrayType - Returns a non-unique reference to
1653/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001654/// type.
John McCall33ddac02011-01-19 10:06:00 +00001655QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1656 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001657 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001658 unsigned elementTypeQuals,
1659 SourceRange brackets) const {
1660 assert((!numElements || numElements->isTypeDependent() ||
1661 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001662 "Size must be type- or value-dependent!");
1663
John McCall33ddac02011-01-19 10:06:00 +00001664 // Dependently-sized array types that do not have a specified number
1665 // of elements will have their sizes deduced from a dependent
1666 // initializer. We do no canonicalization here at all, which is okay
1667 // because they can't be used in most locations.
1668 if (!numElements) {
1669 DependentSizedArrayType *newType
1670 = new (*this, TypeAlignment)
1671 DependentSizedArrayType(*this, elementType, QualType(),
1672 numElements, ASM, elementTypeQuals,
1673 brackets);
1674 Types.push_back(newType);
1675 return QualType(newType, 0);
1676 }
1677
1678 // Otherwise, we actually build a new type every time, but we
1679 // also build a canonical type.
1680
1681 SplitQualType canonElementType = getCanonicalType(elementType).split();
1682
1683 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001684 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001685 DependentSizedArrayType::Profile(ID, *this,
1686 QualType(canonElementType.first, 0),
1687 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001688
John McCall33ddac02011-01-19 10:06:00 +00001689 // Look for an existing type with these properties.
1690 DependentSizedArrayType *canonTy =
1691 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001692
John McCall33ddac02011-01-19 10:06:00 +00001693 // If we don't have one, build one.
1694 if (!canonTy) {
1695 canonTy = new (*this, TypeAlignment)
1696 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1697 QualType(), numElements, ASM, elementTypeQuals,
1698 brackets);
1699 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1700 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001701 }
1702
John McCall33ddac02011-01-19 10:06:00 +00001703 // Apply qualifiers from the element type to the array.
1704 QualType canon = getQualifiedType(QualType(canonTy,0),
1705 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001706
John McCall33ddac02011-01-19 10:06:00 +00001707 // If we didn't need extra canonicalization for the element type,
1708 // then just use that as our result.
1709 if (QualType(canonElementType.first, 0) == elementType)
1710 return canon;
1711
1712 // Otherwise, we need to build a type which follows the spelling
1713 // of the element type.
1714 DependentSizedArrayType *sugaredType
1715 = new (*this, TypeAlignment)
1716 DependentSizedArrayType(*this, elementType, canon, numElements,
1717 ASM, elementTypeQuals, brackets);
1718 Types.push_back(sugaredType);
1719 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001720}
1721
John McCall33ddac02011-01-19 10:06:00 +00001722QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001723 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001724 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001725 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001726 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001727
John McCall33ddac02011-01-19 10:06:00 +00001728 void *insertPos = 0;
1729 if (IncompleteArrayType *iat =
1730 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1731 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001732
1733 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001734 // either, so fill in the canonical type field. We also have to pull
1735 // qualifiers off the element type.
1736 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001737
John McCall33ddac02011-01-19 10:06:00 +00001738 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1739 SplitQualType canonSplit = getCanonicalType(elementType).split();
1740 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1741 ASM, elementTypeQuals);
1742 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001743
1744 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001745 IncompleteArrayType *existing =
1746 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1747 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001748 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001749
John McCall33ddac02011-01-19 10:06:00 +00001750 IncompleteArrayType *newType = new (*this, TypeAlignment)
1751 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001752
John McCall33ddac02011-01-19 10:06:00 +00001753 IncompleteArrayTypes.InsertNode(newType, insertPos);
1754 Types.push_back(newType);
1755 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001756}
1757
Steve Naroff91fcddb2007-07-18 18:00:27 +00001758/// getVectorType - Return the unique reference to a vector type of
1759/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001760QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001761 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001762 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001763
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001764 // Check if we've already instantiated a vector of this type.
1765 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001766 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001767
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001768 void *InsertPos = 0;
1769 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1770 return QualType(VTP, 0);
1771
1772 // If the element type isn't canonical, this won't be a canonical type either,
1773 // so fill in the canonical type field.
1774 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001775 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001776 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001777
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001778 // Get the new insert position for the node we care about.
1779 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001780 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001781 }
John McCall90d1c2d2009-09-24 23:30:46 +00001782 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001783 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001784 VectorTypes.InsertNode(New, InsertPos);
1785 Types.push_back(New);
1786 return QualType(New, 0);
1787}
1788
Nate Begemance4d7fc2008-04-18 23:10:10 +00001789/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001790/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001791QualType
1792ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall33ddac02011-01-19 10:06:00 +00001793 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001794
Steve Naroff91fcddb2007-07-18 18:00:27 +00001795 // Check if we've already instantiated a vector of this type.
1796 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001797 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001798 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001799 void *InsertPos = 0;
1800 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1801 return QualType(VTP, 0);
1802
1803 // If the element type isn't canonical, this won't be a canonical type either,
1804 // so fill in the canonical type field.
1805 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001806 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001807 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001808
Steve Naroff91fcddb2007-07-18 18:00:27 +00001809 // Get the new insert position for the node we care about.
1810 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001811 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001812 }
John McCall90d1c2d2009-09-24 23:30:46 +00001813 ExtVectorType *New = new (*this, TypeAlignment)
1814 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001815 VectorTypes.InsertNode(New, InsertPos);
1816 Types.push_back(New);
1817 return QualType(New, 0);
1818}
1819
Jay Foad39c79802011-01-12 09:06:06 +00001820QualType
1821ASTContext::getDependentSizedExtVectorType(QualType vecType,
1822 Expr *SizeExpr,
1823 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001824 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001825 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001826 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001827
Douglas Gregor352169a2009-07-31 03:54:25 +00001828 void *InsertPos = 0;
1829 DependentSizedExtVectorType *Canon
1830 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1831 DependentSizedExtVectorType *New;
1832 if (Canon) {
1833 // We already have a canonical version of this array type; use it as
1834 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001835 New = new (*this, TypeAlignment)
1836 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1837 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001838 } else {
1839 QualType CanonVecTy = getCanonicalType(vecType);
1840 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001841 New = new (*this, TypeAlignment)
1842 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1843 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001844
1845 DependentSizedExtVectorType *CanonCheck
1846 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1847 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1848 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001849 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1850 } else {
1851 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1852 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001853 New = new (*this, TypeAlignment)
1854 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001855 }
1856 }
Mike Stump11289f42009-09-09 15:08:12 +00001857
Douglas Gregor758a8692009-06-17 21:51:59 +00001858 Types.push_back(New);
1859 return QualType(New, 0);
1860}
1861
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001862/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001863///
Jay Foad39c79802011-01-12 09:06:06 +00001864QualType
1865ASTContext::getFunctionNoProtoType(QualType ResultTy,
1866 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00001867 const CallingConv DefaultCC = Info.getCC();
1868 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1869 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001870 // Unique functions, to guarantee there is only one function of a particular
1871 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001872 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001873 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001874
Chris Lattner47955de2007-01-27 08:37:20 +00001875 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001876 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001877 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001878 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001879
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001880 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001881 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001882 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001883 Canonical =
1884 getFunctionNoProtoType(getCanonicalType(ResultTy),
1885 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001886
Chris Lattner47955de2007-01-27 08:37:20 +00001887 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001888 FunctionNoProtoType *NewIP =
1889 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001890 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001891 }
Mike Stump11289f42009-09-09 15:08:12 +00001892
Roman Divacky65b88cd2011-03-01 17:40:53 +00001893 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00001894 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00001895 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00001896 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001897 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001898 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001899}
1900
1901/// getFunctionType - Return a normal function type with a typed argument
1902/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001903QualType
1904ASTContext::getFunctionType(QualType ResultTy,
1905 const QualType *ArgArray, unsigned NumArgs,
1906 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001907 // Unique functions, to guarantee there is only one function of a particular
1908 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001909 llvm::FoldingSetNodeID ID;
John McCalldb40c7f2010-12-14 08:05:40 +00001910 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001911
1912 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001913 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001914 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001915 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001916
1917 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00001918 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001919 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001920 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001921 isCanonical = false;
1922
Roman Divacky65b88cd2011-03-01 17:40:53 +00001923 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
1924 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1925 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00001926
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001927 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001928 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001929 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001930 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001931 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001932 CanonicalArgs.reserve(NumArgs);
1933 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001934 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001935
John McCalldb40c7f2010-12-14 08:05:40 +00001936 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00001937 CanonicalEPI.ExceptionSpecType = EST_None;
1938 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00001939 CanonicalEPI.ExtInfo
1940 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1941
Chris Lattner76a00cf2008-04-06 22:59:24 +00001942 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001943 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00001944 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001945
Chris Lattnerfd4de792007-01-27 01:15:32 +00001946 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001947 FunctionProtoType *NewIP =
1948 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001949 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001950 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001951
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001952 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001953 // for two variable size arrays (for parameter and exception types) at the
1954 // end of them.
John McCalldb40c7f2010-12-14 08:05:40 +00001955 size_t Size = sizeof(FunctionProtoType) +
1956 NumArgs * sizeof(QualType) +
1957 EPI.NumExceptions * sizeof(QualType);
1958 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00001959 FunctionProtoType::ExtProtoInfo newEPI = EPI;
1960 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
1961 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001962 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001963 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001964 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001965}
Chris Lattneref51c202006-11-10 07:17:23 +00001966
John McCalle78aac42010-03-10 03:28:59 +00001967#ifndef NDEBUG
1968static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1969 if (!isa<CXXRecordDecl>(D)) return false;
1970 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1971 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1972 return true;
1973 if (RD->getDescribedClassTemplate() &&
1974 !isa<ClassTemplateSpecializationDecl>(RD))
1975 return true;
1976 return false;
1977}
1978#endif
1979
1980/// getInjectedClassNameType - Return the unique reference to the
1981/// injected class name type for the specified templated declaration.
1982QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00001983 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00001984 assert(NeedsInjectedClassNameType(Decl));
1985 if (Decl->TypeForDecl) {
1986 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001987 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001988 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1989 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1990 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1991 } else {
John McCall424cec92011-01-19 06:33:43 +00001992 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00001993 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00001994 Decl->TypeForDecl = newType;
1995 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00001996 }
1997 return QualType(Decl->TypeForDecl, 0);
1998}
1999
Douglas Gregor83a586e2008-04-13 21:07:44 +00002000/// getTypeDeclType - Return the unique reference to the type for the
2001/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002002QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002003 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002004 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002005
John McCall81e38502010-02-16 03:57:14 +00002006 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002007 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002008
John McCall96f0b5f2010-03-10 06:48:02 +00002009 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2010 "Template type parameter types are always available.");
2011
John McCall81e38502010-02-16 03:57:14 +00002012 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002013 assert(!Record->getPreviousDeclaration() &&
2014 "struct/union has previous declaration");
2015 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002016 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002017 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002018 assert(!Enum->getPreviousDeclaration() &&
2019 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002020 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002021 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002022 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002023 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2024 Decl->TypeForDecl = newType;
2025 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002026 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002027 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002028
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002029 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002030}
2031
Chris Lattner32d920b2007-01-26 02:01:53 +00002032/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00002033/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002034QualType
Jay Foad39c79802011-01-12 09:06:06 +00002035ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002036 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002037
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002038 if (Canonical.isNull())
2039 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002040 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002041 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002042 Decl->TypeForDecl = newType;
2043 Types.push_back(newType);
2044 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002045}
2046
Jay Foad39c79802011-01-12 09:06:06 +00002047QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002048 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2049
2050 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2051 if (PrevDecl->TypeForDecl)
2052 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2053
John McCall424cec92011-01-19 06:33:43 +00002054 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2055 Decl->TypeForDecl = newType;
2056 Types.push_back(newType);
2057 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002058}
2059
Jay Foad39c79802011-01-12 09:06:06 +00002060QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002061 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2062
2063 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2064 if (PrevDecl->TypeForDecl)
2065 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2066
John McCall424cec92011-01-19 06:33:43 +00002067 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2068 Decl->TypeForDecl = newType;
2069 Types.push_back(newType);
2070 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002071}
2072
John McCall81904512011-01-06 01:58:22 +00002073QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2074 QualType modifiedType,
2075 QualType equivalentType) {
2076 llvm::FoldingSetNodeID id;
2077 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2078
2079 void *insertPos = 0;
2080 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2081 if (type) return QualType(type, 0);
2082
2083 QualType canon = getCanonicalType(equivalentType);
2084 type = new (*this, TypeAlignment)
2085 AttributedType(canon, attrKind, modifiedType, equivalentType);
2086
2087 Types.push_back(type);
2088 AttributedTypes.InsertNode(type, insertPos);
2089
2090 return QualType(type, 0);
2091}
2092
2093
John McCallcebee162009-10-18 09:09:24 +00002094/// \brief Retrieve a substitution-result type.
2095QualType
2096ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002097 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002098 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002099 && "replacement types must always be canonical");
2100
2101 llvm::FoldingSetNodeID ID;
2102 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2103 void *InsertPos = 0;
2104 SubstTemplateTypeParmType *SubstParm
2105 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2106
2107 if (!SubstParm) {
2108 SubstParm = new (*this, TypeAlignment)
2109 SubstTemplateTypeParmType(Parm, Replacement);
2110 Types.push_back(SubstParm);
2111 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2112 }
2113
2114 return QualType(SubstParm, 0);
2115}
2116
Douglas Gregorada4b792011-01-14 02:55:32 +00002117/// \brief Retrieve a
2118QualType ASTContext::getSubstTemplateTypeParmPackType(
2119 const TemplateTypeParmType *Parm,
2120 const TemplateArgument &ArgPack) {
2121#ifndef NDEBUG
2122 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2123 PEnd = ArgPack.pack_end();
2124 P != PEnd; ++P) {
2125 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2126 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2127 }
2128#endif
2129
2130 llvm::FoldingSetNodeID ID;
2131 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2132 void *InsertPos = 0;
2133 if (SubstTemplateTypeParmPackType *SubstParm
2134 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2135 return QualType(SubstParm, 0);
2136
2137 QualType Canon;
2138 if (!Parm->isCanonicalUnqualified()) {
2139 Canon = getCanonicalType(QualType(Parm, 0));
2140 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2141 ArgPack);
2142 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2143 }
2144
2145 SubstTemplateTypeParmPackType *SubstParm
2146 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2147 ArgPack);
2148 Types.push_back(SubstParm);
2149 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2150 return QualType(SubstParm, 0);
2151}
2152
Douglas Gregoreff93e02009-02-05 23:33:38 +00002153/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002154/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002155/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002156QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002157 bool ParameterPack,
Jay Foad39c79802011-01-12 09:06:06 +00002158 IdentifierInfo *Name) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002159 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002160 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002161 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002162 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002163 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2164
2165 if (TypeParm)
2166 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002167
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002168 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002169 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002170 TypeParm = new (*this, TypeAlignment)
2171 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002172
2173 TemplateTypeParmType *TypeCheck
2174 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2175 assert(!TypeCheck && "Template type parameter canonical type broken");
2176 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002177 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002178 TypeParm = new (*this, TypeAlignment)
2179 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002180
2181 Types.push_back(TypeParm);
2182 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2183
2184 return QualType(TypeParm, 0);
2185}
2186
John McCalle78aac42010-03-10 03:28:59 +00002187TypeSourceInfo *
2188ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2189 SourceLocation NameLoc,
2190 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002191 QualType CanonType) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002192 assert(!Name.getAsDependentTemplateName() &&
2193 "No dependent template names here!");
John McCalle78aac42010-03-10 03:28:59 +00002194 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2195
2196 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2197 TemplateSpecializationTypeLoc TL
2198 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2199 TL.setTemplateNameLoc(NameLoc);
2200 TL.setLAngleLoc(Args.getLAngleLoc());
2201 TL.setRAngleLoc(Args.getRAngleLoc());
2202 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2203 TL.setArgLocInfo(i, Args[i].getLocInfo());
2204 return DI;
2205}
2206
Mike Stump11289f42009-09-09 15:08:12 +00002207QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002208ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002209 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002210 QualType Canon) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002211 assert(!Template.getAsDependentTemplateName() &&
2212 "No dependent template names here!");
2213
John McCall6b51f282009-11-23 01:53:49 +00002214 unsigned NumArgs = Args.size();
2215
John McCall0ad16662009-10-29 08:12:44 +00002216 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2217 ArgVec.reserve(NumArgs);
2218 for (unsigned i = 0; i != NumArgs; ++i)
2219 ArgVec.push_back(Args[i].getArgument());
2220
John McCall2408e322010-04-27 00:57:59 +00002221 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00002222 Canon);
John McCall0ad16662009-10-29 08:12:44 +00002223}
2224
2225QualType
2226ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002227 const TemplateArgument *Args,
2228 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002229 QualType Canon) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002230 assert(!Template.getAsDependentTemplateName() &&
2231 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002232 // Look through qualified template names.
2233 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2234 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002235
Douglas Gregor15301382009-07-30 17:40:51 +00002236 if (!Canon.isNull())
2237 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002238 else
2239 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00002240
Douglas Gregora8e02e72009-07-28 23:00:59 +00002241 // Allocate the (non-canonical) template specialization type, but don't
2242 // try to unique it: these types typically have location information that
2243 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002244 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002245 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002246 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002247 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002248 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002249 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002250 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002251
Douglas Gregor8bf42052009-02-09 18:46:07 +00002252 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002253 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002254}
2255
Mike Stump11289f42009-09-09 15:08:12 +00002256QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002257ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2258 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002259 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002260 assert(!Template.getAsDependentTemplateName() &&
2261 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002262 // Look through qualified template names.
2263 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2264 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002265
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002266 // Build the canonical template specialization type.
2267 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2268 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2269 CanonArgs.reserve(NumArgs);
2270 for (unsigned I = 0; I != NumArgs; ++I)
2271 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2272
2273 // Determine whether this canonical template specialization type already
2274 // exists.
2275 llvm::FoldingSetNodeID ID;
2276 TemplateSpecializationType::Profile(ID, CanonTemplate,
2277 CanonArgs.data(), NumArgs, *this);
2278
2279 void *InsertPos = 0;
2280 TemplateSpecializationType *Spec
2281 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2282
2283 if (!Spec) {
2284 // Allocate a new canonical template specialization type.
2285 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2286 sizeof(TemplateArgument) * NumArgs),
2287 TypeAlignment);
2288 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2289 CanonArgs.data(), NumArgs,
2290 QualType());
2291 Types.push_back(Spec);
2292 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2293 }
2294
2295 assert(Spec->isDependentType() &&
2296 "Non-dependent template-id type must have a canonical type");
2297 return QualType(Spec, 0);
2298}
2299
2300QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002301ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2302 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002303 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002304 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002305 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002306
2307 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002308 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002309 if (T)
2310 return QualType(T, 0);
2311
Douglas Gregorc42075a2010-02-04 18:10:26 +00002312 QualType Canon = NamedType;
2313 if (!Canon.isCanonical()) {
2314 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002315 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2316 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002317 (void)CheckT;
2318 }
2319
Abramo Bagnara6150c882010-05-11 21:36:43 +00002320 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002321 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002322 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002323 return QualType(T, 0);
2324}
2325
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002326QualType
Jay Foad39c79802011-01-12 09:06:06 +00002327ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002328 llvm::FoldingSetNodeID ID;
2329 ParenType::Profile(ID, InnerType);
2330
2331 void *InsertPos = 0;
2332 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2333 if (T)
2334 return QualType(T, 0);
2335
2336 QualType Canon = InnerType;
2337 if (!Canon.isCanonical()) {
2338 Canon = getCanonicalType(InnerType);
2339 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2340 assert(!CheckT && "Paren canonical type broken");
2341 (void)CheckT;
2342 }
2343
2344 T = new (*this) ParenType(InnerType, Canon);
2345 Types.push_back(T);
2346 ParenTypes.InsertNode(T, InsertPos);
2347 return QualType(T, 0);
2348}
2349
Douglas Gregor02085352010-03-31 20:19:30 +00002350QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2351 NestedNameSpecifier *NNS,
2352 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002353 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002354 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2355
2356 if (Canon.isNull()) {
2357 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002358 ElaboratedTypeKeyword CanonKeyword = Keyword;
2359 if (Keyword == ETK_None)
2360 CanonKeyword = ETK_Typename;
2361
2362 if (CanonNNS != NNS || CanonKeyword != Keyword)
2363 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002364 }
2365
2366 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002367 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002368
2369 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002370 DependentNameType *T
2371 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002372 if (T)
2373 return QualType(T, 0);
2374
Douglas Gregor02085352010-03-31 20:19:30 +00002375 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002376 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002377 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002378 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002379}
2380
Mike Stump11289f42009-09-09 15:08:12 +00002381QualType
John McCallc392f372010-06-11 00:33:02 +00002382ASTContext::getDependentTemplateSpecializationType(
2383 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002384 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002385 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002386 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002387 // TODO: avoid this copy
2388 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2389 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2390 ArgCopy.push_back(Args[I].getArgument());
2391 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2392 ArgCopy.size(),
2393 ArgCopy.data());
2394}
2395
2396QualType
2397ASTContext::getDependentTemplateSpecializationType(
2398 ElaboratedTypeKeyword Keyword,
2399 NestedNameSpecifier *NNS,
2400 const IdentifierInfo *Name,
2401 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002402 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002403 assert((!NNS || NNS->isDependent()) &&
2404 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002405
Douglas Gregorc42075a2010-02-04 18:10:26 +00002406 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002407 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2408 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002409
2410 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002411 DependentTemplateSpecializationType *T
2412 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002413 if (T)
2414 return QualType(T, 0);
2415
John McCallc392f372010-06-11 00:33:02 +00002416 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002417
John McCallc392f372010-06-11 00:33:02 +00002418 ElaboratedTypeKeyword CanonKeyword = Keyword;
2419 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2420
2421 bool AnyNonCanonArgs = false;
2422 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2423 for (unsigned I = 0; I != NumArgs; ++I) {
2424 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2425 if (!CanonArgs[I].structurallyEquals(Args[I]))
2426 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002427 }
2428
John McCallc392f372010-06-11 00:33:02 +00002429 QualType Canon;
2430 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2431 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2432 Name, NumArgs,
2433 CanonArgs.data());
2434
2435 // Find the insert position again.
2436 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2437 }
2438
2439 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2440 sizeof(TemplateArgument) * NumArgs),
2441 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002442 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002443 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002444 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002445 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002446 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002447}
2448
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002449QualType ASTContext::getPackExpansionType(QualType Pattern,
2450 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002451 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002452 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002453
2454 assert(Pattern->containsUnexpandedParameterPack() &&
2455 "Pack expansions must expand one or more parameter packs");
2456 void *InsertPos = 0;
2457 PackExpansionType *T
2458 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2459 if (T)
2460 return QualType(T, 0);
2461
2462 QualType Canon;
2463 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002464 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002465
2466 // Find the insert position again.
2467 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2468 }
2469
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002470 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002471 Types.push_back(T);
2472 PackExpansionTypes.InsertNode(T, InsertPos);
2473 return QualType(T, 0);
2474}
2475
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002476/// CmpProtocolNames - Comparison predicate for sorting protocols
2477/// alphabetically.
2478static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2479 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002480 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002481}
2482
John McCall8b07ec22010-05-15 11:32:37 +00002483static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002484 unsigned NumProtocols) {
2485 if (NumProtocols == 0) return true;
2486
2487 for (unsigned i = 1; i != NumProtocols; ++i)
2488 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2489 return false;
2490 return true;
2491}
2492
2493static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002494 unsigned &NumProtocols) {
2495 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002496
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002497 // Sort protocols, keyed by name.
2498 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2499
2500 // Remove duplicates.
2501 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2502 NumProtocols = ProtocolsEnd-Protocols;
2503}
2504
John McCall8b07ec22010-05-15 11:32:37 +00002505QualType ASTContext::getObjCObjectType(QualType BaseType,
2506 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002507 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002508 // If the base type is an interface and there aren't any protocols
2509 // to add, then the interface type will do just fine.
2510 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2511 return BaseType;
2512
2513 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002514 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002515 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002516 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002517 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2518 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002519
John McCall8b07ec22010-05-15 11:32:37 +00002520 // Build the canonical type, which has the canonical base type and
2521 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002522 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002523 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2524 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2525 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002526 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2527 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002528 unsigned UniqueCount = NumProtocols;
2529
John McCallfc93cf92009-10-22 22:37:11 +00002530 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002531 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2532 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002533 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002534 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2535 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002536 }
2537
2538 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002539 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2540 }
2541
2542 unsigned Size = sizeof(ObjCObjectTypeImpl);
2543 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2544 void *Mem = Allocate(Size, TypeAlignment);
2545 ObjCObjectTypeImpl *T =
2546 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2547
2548 Types.push_back(T);
2549 ObjCObjectTypes.InsertNode(T, InsertPos);
2550 return QualType(T, 0);
2551}
2552
2553/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2554/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002555QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002556 llvm::FoldingSetNodeID ID;
2557 ObjCObjectPointerType::Profile(ID, ObjectT);
2558
2559 void *InsertPos = 0;
2560 if (ObjCObjectPointerType *QT =
2561 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2562 return QualType(QT, 0);
2563
2564 // Find the canonical object type.
2565 QualType Canonical;
2566 if (!ObjectT.isCanonical()) {
2567 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2568
2569 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002570 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2571 }
2572
Douglas Gregorf85bee62010-02-08 22:59:26 +00002573 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002574 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2575 ObjCObjectPointerType *QType =
2576 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002577
Steve Narofffb4330f2009-06-17 22:40:22 +00002578 Types.push_back(QType);
2579 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002580 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002581}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002582
Douglas Gregor1c283312010-08-11 12:19:30 +00002583/// getObjCInterfaceType - Return the unique reference to the type for the
2584/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002585QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002586 if (Decl->TypeForDecl)
2587 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002588
Douglas Gregor1c283312010-08-11 12:19:30 +00002589 // FIXME: redeclarations?
2590 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2591 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2592 Decl->TypeForDecl = T;
2593 Types.push_back(T);
2594 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002595}
2596
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002597/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2598/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002599/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002600/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002601/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002602QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002603 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002604 if (tofExpr->isTypeDependent()) {
2605 llvm::FoldingSetNodeID ID;
2606 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002607
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002608 void *InsertPos = 0;
2609 DependentTypeOfExprType *Canon
2610 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2611 if (Canon) {
2612 // We already have a "canonical" version of an identical, dependent
2613 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002614 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002615 QualType((TypeOfExprType*)Canon, 0));
2616 }
2617 else {
2618 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002619 Canon
2620 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002621 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2622 toe = Canon;
2623 }
2624 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002625 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002626 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002627 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002628 Types.push_back(toe);
2629 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002630}
2631
Steve Naroffa773cd52007-08-01 18:02:17 +00002632/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2633/// TypeOfType AST's. The only motivation to unique these nodes would be
2634/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002635/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002636/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002637QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002638 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002639 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002640 Types.push_back(tot);
2641 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002642}
2643
Anders Carlssonad6bd352009-06-24 21:24:56 +00002644/// getDecltypeForExpr - Given an expr, will return the decltype for that
2645/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002646static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002647 if (e->isTypeDependent())
2648 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002649
Anders Carlssonad6bd352009-06-24 21:24:56 +00002650 // If e is an id expression or a class member access, decltype(e) is defined
2651 // as the type of the entity named by e.
2652 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2653 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2654 return VD->getType();
2655 }
2656 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2657 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2658 return FD->getType();
2659 }
2660 // If e is a function call or an invocation of an overloaded operator,
2661 // (parentheses around e are ignored), decltype(e) is defined as the
2662 // return type of that function.
2663 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2664 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002665
Anders Carlssonad6bd352009-06-24 21:24:56 +00002666 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002667
2668 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002669 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002670 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002671 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002672
Anders Carlssonad6bd352009-06-24 21:24:56 +00002673 return T;
2674}
2675
Anders Carlsson81df7b82009-06-24 19:06:50 +00002676/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2677/// DecltypeType AST's. The only motivation to unique these nodes would be
2678/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002679/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002680/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002681QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002682 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002683 if (e->isTypeDependent()) {
2684 llvm::FoldingSetNodeID ID;
2685 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002686
Douglas Gregora21f6c32009-07-30 23:36:40 +00002687 void *InsertPos = 0;
2688 DependentDecltypeType *Canon
2689 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2690 if (Canon) {
2691 // We already have a "canonical" version of an equivalent, dependent
2692 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002693 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002694 QualType((DecltypeType*)Canon, 0));
2695 }
2696 else {
2697 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002698 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002699 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2700 dt = Canon;
2701 }
2702 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002703 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002704 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002705 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002706 Types.push_back(dt);
2707 return QualType(dt, 0);
2708}
2709
Richard Smithb2bc2e62011-02-21 20:05:19 +00002710/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002711QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002712 void *InsertPos = 0;
2713 if (!DeducedType.isNull()) {
2714 // Look in the folding set for an existing type.
2715 llvm::FoldingSetNodeID ID;
2716 AutoType::Profile(ID, DeducedType);
2717 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2718 return QualType(AT, 0);
2719 }
2720
2721 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2722 Types.push_back(AT);
2723 if (InsertPos)
2724 AutoTypes.InsertNode(AT, InsertPos);
2725 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002726}
2727
Chris Lattnerfb072462007-01-23 05:45:31 +00002728/// getTagDeclType - Return the unique reference to the type for the
2729/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002730QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002731 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002732 // FIXME: What is the design on getTagDeclType when it requires casting
2733 // away const? mutable?
2734 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002735}
2736
Mike Stump11289f42009-09-09 15:08:12 +00002737/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2738/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2739/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002740CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002741 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002742}
Chris Lattnerfb072462007-01-23 05:45:31 +00002743
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002744/// getSignedWCharType - Return the type of "signed wchar_t".
2745/// Used when in C++, as a GCC extension.
2746QualType ASTContext::getSignedWCharType() const {
2747 // FIXME: derive from "Target" ?
2748 return WCharTy;
2749}
2750
2751/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2752/// Used when in C++, as a GCC extension.
2753QualType ASTContext::getUnsignedWCharType() const {
2754 // FIXME: derive from "Target" ?
2755 return UnsignedIntTy;
2756}
2757
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002758/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2759/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2760QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002761 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002762}
2763
Chris Lattnera21ad802008-04-02 05:18:44 +00002764//===----------------------------------------------------------------------===//
2765// Type Operators
2766//===----------------------------------------------------------------------===//
2767
Jay Foad39c79802011-01-12 09:06:06 +00002768CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002769 // Push qualifiers into arrays, and then discard any remaining
2770 // qualifiers.
2771 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002772 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002773 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002774 QualType Result;
2775 if (isa<ArrayType>(Ty)) {
2776 Result = getArrayDecayedType(QualType(Ty,0));
2777 } else if (isa<FunctionType>(Ty)) {
2778 Result = getPointerType(QualType(Ty, 0));
2779 } else {
2780 Result = QualType(Ty, 0);
2781 }
2782
2783 return CanQualType::CreateUnsafe(Result);
2784}
2785
Chris Lattner7adf0762008-08-04 07:31:14 +00002786
John McCall6c9dd522011-01-18 07:41:22 +00002787QualType ASTContext::getUnqualifiedArrayType(QualType type,
2788 Qualifiers &quals) {
2789 SplitQualType splitType = type.getSplitUnqualifiedType();
2790
2791 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2792 // the unqualified desugared type and then drops it on the floor.
2793 // We then have to strip that sugar back off with
2794 // getUnqualifiedDesugaredType(), which is silly.
2795 const ArrayType *AT =
2796 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2797
2798 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002799 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002800 quals = splitType.second;
2801 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002802 }
2803
John McCall6c9dd522011-01-18 07:41:22 +00002804 // Otherwise, recurse on the array's element type.
2805 QualType elementType = AT->getElementType();
2806 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2807
2808 // If that didn't change the element type, AT has no qualifiers, so we
2809 // can just use the results in splitType.
2810 if (elementType == unqualElementType) {
2811 assert(quals.empty()); // from the recursive call
2812 quals = splitType.second;
2813 return QualType(splitType.first, 0);
2814 }
2815
2816 // Otherwise, add in the qualifiers from the outermost type, then
2817 // build the type back up.
2818 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002819
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002820 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002821 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002822 CAT->getSizeModifier(), 0);
2823 }
2824
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002825 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002826 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002827 }
2828
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002829 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002830 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002831 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002832 VAT->getSizeModifier(),
2833 VAT->getIndexTypeCVRQualifiers(),
2834 VAT->getBracketsRange());
2835 }
2836
2837 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002838 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002839 DSAT->getSizeModifier(), 0,
2840 SourceRange());
2841}
2842
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002843/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2844/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2845/// they point to and return true. If T1 and T2 aren't pointer types
2846/// or pointer-to-member types, or if they are not similar at this
2847/// level, returns false and leaves T1 and T2 unchanged. Top-level
2848/// qualifiers on T1 and T2 are ignored. This function will typically
2849/// be called in a loop that successively "unwraps" pointer and
2850/// pointer-to-member types to compare them at each level.
2851bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2852 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2853 *T2PtrType = T2->getAs<PointerType>();
2854 if (T1PtrType && T2PtrType) {
2855 T1 = T1PtrType->getPointeeType();
2856 T2 = T2PtrType->getPointeeType();
2857 return true;
2858 }
2859
2860 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2861 *T2MPType = T2->getAs<MemberPointerType>();
2862 if (T1MPType && T2MPType &&
2863 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2864 QualType(T2MPType->getClass(), 0))) {
2865 T1 = T1MPType->getPointeeType();
2866 T2 = T2MPType->getPointeeType();
2867 return true;
2868 }
2869
2870 if (getLangOptions().ObjC1) {
2871 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2872 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2873 if (T1OPType && T2OPType) {
2874 T1 = T1OPType->getPointeeType();
2875 T2 = T2OPType->getPointeeType();
2876 return true;
2877 }
2878 }
2879
2880 // FIXME: Block pointers, too?
2881
2882 return false;
2883}
2884
Jay Foad39c79802011-01-12 09:06:06 +00002885DeclarationNameInfo
2886ASTContext::getNameForTemplate(TemplateName Name,
2887 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002888 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002889 // DNInfo work in progress: CHECKME: what about DNLoc?
2890 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2891
John McCall847e2a12009-11-24 18:42:40 +00002892 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002893 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002894 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002895 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2896 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002897 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002898 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2899 // DNInfo work in progress: FIXME: source locations?
2900 DeclarationNameLoc DNLoc;
2901 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2902 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2903 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002904 }
2905 }
2906
John McCalld28ae272009-12-02 08:04:21 +00002907 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2908 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002909 // DNInfo work in progress: CHECKME: what about DNLoc?
2910 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002911}
2912
Jay Foad39c79802011-01-12 09:06:06 +00002913TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002914 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2915 if (TemplateTemplateParmDecl *TTP
2916 = dyn_cast<TemplateTemplateParmDecl>(Template))
2917 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2918
2919 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002920 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002921 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002922
Douglas Gregor5590be02011-01-15 06:45:20 +00002923 if (SubstTemplateTemplateParmPackStorage *SubstPack
2924 = Name.getAsSubstTemplateTemplateParmPack()) {
2925 TemplateTemplateParmDecl *CanonParam
2926 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2927 TemplateArgument CanonArgPack
2928 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2929 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2930 }
2931
John McCalld28ae272009-12-02 08:04:21 +00002932 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002933
Douglas Gregor6bc50582009-05-07 06:41:52 +00002934 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2935 assert(DTN && "Non-dependent template names must refer to template decls.");
2936 return DTN->CanonicalTemplateName;
2937}
2938
Douglas Gregoradee3e32009-11-11 23:06:43 +00002939bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2940 X = getCanonicalTemplateName(X);
2941 Y = getCanonicalTemplateName(Y);
2942 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2943}
2944
Mike Stump11289f42009-09-09 15:08:12 +00002945TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00002946ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00002947 switch (Arg.getKind()) {
2948 case TemplateArgument::Null:
2949 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002950
Douglas Gregora8e02e72009-07-28 23:00:59 +00002951 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002952 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002953
Douglas Gregora8e02e72009-07-28 23:00:59 +00002954 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002955 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002956
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002957 case TemplateArgument::Template:
2958 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002959
2960 case TemplateArgument::TemplateExpansion:
2961 return TemplateArgument(getCanonicalTemplateName(
2962 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00002963 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002964
Douglas Gregora8e02e72009-07-28 23:00:59 +00002965 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002966 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002967 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002968
Douglas Gregora8e02e72009-07-28 23:00:59 +00002969 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002970 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002971
Douglas Gregora8e02e72009-07-28 23:00:59 +00002972 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00002973 if (Arg.pack_size() == 0)
2974 return Arg;
2975
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002976 TemplateArgument *CanonArgs
2977 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00002978 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002979 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002980 AEnd = Arg.pack_end();
2981 A != AEnd; (void)++A, ++Idx)
2982 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002983
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002984 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00002985 }
2986 }
2987
2988 // Silence GCC warning
2989 assert(false && "Unhandled template argument kind");
2990 return TemplateArgument();
2991}
2992
Douglas Gregor333489b2009-03-27 23:10:48 +00002993NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00002994ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00002995 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002996 return 0;
2997
2998 switch (NNS->getKind()) {
2999 case NestedNameSpecifier::Identifier:
3000 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003001 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003002 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3003 NNS->getAsIdentifier());
3004
3005 case NestedNameSpecifier::Namespace:
3006 // A namespace is canonical; build a nested-name-specifier with
3007 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003008 return NestedNameSpecifier::Create(*this, 0,
3009 NNS->getAsNamespace()->getOriginalNamespace());
3010
3011 case NestedNameSpecifier::NamespaceAlias:
3012 // A namespace is canonical; build a nested-name-specifier with
3013 // this namespace and no prefix.
3014 return NestedNameSpecifier::Create(*this, 0,
3015 NNS->getAsNamespaceAlias()->getNamespace()
3016 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003017
3018 case NestedNameSpecifier::TypeSpec:
3019 case NestedNameSpecifier::TypeSpecWithTemplate: {
3020 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003021
3022 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3023 // break it apart into its prefix and identifier, then reconsititute those
3024 // as the canonical nested-name-specifier. This is required to canonicalize
3025 // a dependent nested-name-specifier involving typedefs of dependent-name
3026 // types, e.g.,
3027 // typedef typename T::type T1;
3028 // typedef typename T1::type T2;
3029 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3030 NestedNameSpecifier *Prefix
3031 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3032 return NestedNameSpecifier::Create(*this, Prefix,
3033 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3034 }
3035
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003036 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003037 if (const DependentTemplateSpecializationType *DTST
3038 = T->getAs<DependentTemplateSpecializationType>()) {
3039 NestedNameSpecifier *Prefix
3040 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003041
3042 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3043 Prefix, DTST->getIdentifier(),
3044 DTST->getNumArgs(),
3045 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003046 T = getCanonicalType(T);
3047 }
3048
John McCall33ddac02011-01-19 10:06:00 +00003049 return NestedNameSpecifier::Create(*this, 0, false,
3050 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003051 }
3052
3053 case NestedNameSpecifier::Global:
3054 // The global specifier is canonical and unique.
3055 return NNS;
3056 }
3057
3058 // Required to silence a GCC warning
3059 return 0;
3060}
3061
Chris Lattner7adf0762008-08-04 07:31:14 +00003062
Jay Foad39c79802011-01-12 09:06:06 +00003063const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003064 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003065 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003066 // Handle the common positive case fast.
3067 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3068 return AT;
3069 }
Mike Stump11289f42009-09-09 15:08:12 +00003070
John McCall8ccfcb52009-09-24 19:53:00 +00003071 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003072 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003073 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003074
John McCall8ccfcb52009-09-24 19:53:00 +00003075 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003076 // implements C99 6.7.3p8: "If the specification of an array type includes
3077 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003078
Chris Lattner7adf0762008-08-04 07:31:14 +00003079 // If we get here, we either have type qualifiers on the type, or we have
3080 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003081 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003082
John McCall33ddac02011-01-19 10:06:00 +00003083 SplitQualType split = T.getSplitDesugaredType();
3084 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003085
Chris Lattner7adf0762008-08-04 07:31:14 +00003086 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003087 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3088 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003089 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003090
Chris Lattner7adf0762008-08-04 07:31:14 +00003091 // Otherwise, we have an array and we have qualifiers on it. Push the
3092 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003093 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003094
Chris Lattner7adf0762008-08-04 07:31:14 +00003095 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3096 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3097 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003098 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003099 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3100 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3101 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003102 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003103
Mike Stump11289f42009-09-09 15:08:12 +00003104 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003105 = dyn_cast<DependentSizedArrayType>(ATy))
3106 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003107 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003108 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003109 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003110 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003111 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003112
Chris Lattner7adf0762008-08-04 07:31:14 +00003113 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003114 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003115 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003116 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003117 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003118 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003119}
3120
Chris Lattnera21ad802008-04-02 05:18:44 +00003121/// getArrayDecayedType - Return the properly qualified result of decaying the
3122/// specified array type to a pointer. This operation is non-trivial when
3123/// handling typedefs etc. The canonical type of "T" must be an array type,
3124/// this returns a pointer to a properly qualified element of the array.
3125///
3126/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003127QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003128 // Get the element type with 'getAsArrayType' so that we don't lose any
3129 // typedefs in the element type of the array. This also handles propagation
3130 // of type qualifiers from the array type into the element type if present
3131 // (C99 6.7.3p8).
3132 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3133 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003134
Chris Lattner7adf0762008-08-04 07:31:14 +00003135 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003136
3137 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003138 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003139}
3140
John McCall33ddac02011-01-19 10:06:00 +00003141QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3142 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003143}
3144
John McCall33ddac02011-01-19 10:06:00 +00003145QualType ASTContext::getBaseElementType(QualType type) const {
3146 Qualifiers qs;
3147 while (true) {
3148 SplitQualType split = type.getSplitDesugaredType();
3149 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3150 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003151
John McCall33ddac02011-01-19 10:06:00 +00003152 type = array->getElementType();
3153 qs.addConsistentQualifiers(split.second);
3154 }
Mike Stump11289f42009-09-09 15:08:12 +00003155
John McCall33ddac02011-01-19 10:06:00 +00003156 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003157}
3158
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003159/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003160uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003161ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3162 uint64_t ElementCount = 1;
3163 do {
3164 ElementCount *= CA->getSize().getZExtValue();
3165 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3166 } while (CA);
3167 return ElementCount;
3168}
3169
Steve Naroff0af91202007-04-27 21:51:21 +00003170/// getFloatingRank - Return a relative rank for floating point types.
3171/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003172static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003173 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003174 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003175
John McCall9dd450b2009-09-21 23:43:11 +00003176 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3177 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003178 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003179 case BuiltinType::Float: return FloatRank;
3180 case BuiltinType::Double: return DoubleRank;
3181 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003182 }
3183}
3184
Mike Stump11289f42009-09-09 15:08:12 +00003185/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3186/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003187/// 'typeDomain' is a real floating point or complex type.
3188/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003189QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3190 QualType Domain) const {
3191 FloatingRank EltRank = getFloatingRank(Size);
3192 if (Domain->isComplexType()) {
3193 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003194 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003195 case FloatRank: return FloatComplexTy;
3196 case DoubleRank: return DoubleComplexTy;
3197 case LongDoubleRank: return LongDoubleComplexTy;
3198 }
Steve Naroff0af91202007-04-27 21:51:21 +00003199 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003200
3201 assert(Domain->isRealFloatingType() && "Unknown domain!");
3202 switch (EltRank) {
3203 default: assert(0 && "getFloatingRank(): illegal value for rank");
3204 case FloatRank: return FloatTy;
3205 case DoubleRank: return DoubleTy;
3206 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003207 }
Steve Naroffe4718892007-04-27 18:30:00 +00003208}
3209
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003210/// getFloatingTypeOrder - Compare the rank of the two specified floating
3211/// point types, ignoring the domain of the type (i.e. 'double' ==
3212/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003213/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003214int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003215 FloatingRank LHSR = getFloatingRank(LHS);
3216 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003217
Chris Lattnerb90739d2008-04-06 23:38:49 +00003218 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003219 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003220 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003221 return 1;
3222 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003223}
3224
Chris Lattner76a00cf2008-04-06 22:59:24 +00003225/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3226/// routine will assert if passed a built-in type that isn't an integer or enum,
3227/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003228unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003229 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003230 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003231 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003232
Chris Lattnerad3467e2010-12-25 23:25:43 +00003233 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3234 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003235 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3236
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003237 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3238 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3239
3240 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3241 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3242
Chris Lattner76a00cf2008-04-06 22:59:24 +00003243 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003244 default: assert(0 && "getIntegerRank(): not a built-in integer");
3245 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003246 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003247 case BuiltinType::Char_S:
3248 case BuiltinType::Char_U:
3249 case BuiltinType::SChar:
3250 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003251 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003252 case BuiltinType::Short:
3253 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003254 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003255 case BuiltinType::Int:
3256 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003257 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003258 case BuiltinType::Long:
3259 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003260 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003261 case BuiltinType::LongLong:
3262 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003263 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003264 case BuiltinType::Int128:
3265 case BuiltinType::UInt128:
3266 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003267 }
3268}
3269
Eli Friedman629ffb92009-08-20 04:21:42 +00003270/// \brief Whether this is a promotable bitfield reference according
3271/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3272///
3273/// \returns the type this bit-field will promote to, or NULL if no
3274/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003275QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003276 if (E->isTypeDependent() || E->isValueDependent())
3277 return QualType();
3278
Eli Friedman629ffb92009-08-20 04:21:42 +00003279 FieldDecl *Field = E->getBitField();
3280 if (!Field)
3281 return QualType();
3282
3283 QualType FT = Field->getType();
3284
3285 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3286 uint64_t BitWidth = BitWidthAP.getZExtValue();
3287 uint64_t IntSize = getTypeSize(IntTy);
3288 // GCC extension compatibility: if the bit-field size is less than or equal
3289 // to the size of int, it gets promoted no matter what its type is.
3290 // For instance, unsigned long bf : 4 gets promoted to signed int.
3291 if (BitWidth < IntSize)
3292 return IntTy;
3293
3294 if (BitWidth == IntSize)
3295 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3296
3297 // Types bigger than int are not subject to promotions, and therefore act
3298 // like the base type.
3299 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3300 // is ridiculous.
3301 return QualType();
3302}
3303
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003304/// getPromotedIntegerType - Returns the type that Promotable will
3305/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3306/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003307QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003308 assert(!Promotable.isNull());
3309 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003310 if (const EnumType *ET = Promotable->getAs<EnumType>())
3311 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003312 if (Promotable->isSignedIntegerType())
3313 return IntTy;
3314 uint64_t PromotableSize = getTypeSize(Promotable);
3315 uint64_t IntSize = getTypeSize(IntTy);
3316 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3317 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3318}
3319
Mike Stump11289f42009-09-09 15:08:12 +00003320/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003321/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003322/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003323int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003324 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3325 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003326 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003327
Chris Lattner76a00cf2008-04-06 22:59:24 +00003328 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3329 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003330
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003331 unsigned LHSRank = getIntegerRank(LHSC);
3332 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003333
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003334 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3335 if (LHSRank == RHSRank) return 0;
3336 return LHSRank > RHSRank ? 1 : -1;
3337 }
Mike Stump11289f42009-09-09 15:08:12 +00003338
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003339 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3340 if (LHSUnsigned) {
3341 // If the unsigned [LHS] type is larger, return it.
3342 if (LHSRank >= RHSRank)
3343 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003344
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003345 // If the signed type can represent all values of the unsigned type, it
3346 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003347 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003348 return -1;
3349 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003350
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003351 // If the unsigned [RHS] type is larger, return it.
3352 if (RHSRank >= LHSRank)
3353 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003354
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003355 // If the signed type can represent all values of the unsigned type, it
3356 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003357 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003358 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003359}
Anders Carlsson98f07902007-08-17 05:31:46 +00003360
Anders Carlsson6d417272009-11-14 21:45:58 +00003361static RecordDecl *
Jay Foad39c79802011-01-12 09:06:06 +00003362CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
Anders Carlsson6d417272009-11-14 21:45:58 +00003363 SourceLocation L, IdentifierInfo *Id) {
3364 if (Ctx.getLangOptions().CPlusPlus)
3365 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3366 else
3367 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3368}
3369
Mike Stump11289f42009-09-09 15:08:12 +00003370// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003371QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003372 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003373 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003374 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003375 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003376 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003377
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003378 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003379
Anders Carlsson98f07902007-08-17 05:31:46 +00003380 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003381 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003382 // int flags;
3383 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003384 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003385 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003386 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003387 FieldTypes[3] = LongTy;
3388
Anders Carlsson98f07902007-08-17 05:31:46 +00003389 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003390 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003391 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003392 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003393 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003394 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003395 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003396 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003397 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003398 }
3399
Douglas Gregord5058122010-02-11 01:19:42 +00003400 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003401 }
Mike Stump11289f42009-09-09 15:08:12 +00003402
Anders Carlsson98f07902007-08-17 05:31:46 +00003403 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003404}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003405
Douglas Gregor512b0772009-04-23 22:29:11 +00003406void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003407 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003408 assert(Rec && "Invalid CFConstantStringType");
3409 CFConstantStringTypeDecl = Rec->getDecl();
3410}
3411
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003412// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003413QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003414 if (!NSConstantStringTypeDecl) {
3415 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003416 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003417 &Idents.get("__builtin_NSString"));
3418 NSConstantStringTypeDecl->startDefinition();
3419
3420 QualType FieldTypes[3];
3421
3422 // const int *isa;
3423 FieldTypes[0] = getPointerType(IntTy.withConst());
3424 // const char *str;
3425 FieldTypes[1] = getPointerType(CharTy.withConst());
3426 // unsigned int length;
3427 FieldTypes[2] = UnsignedIntTy;
3428
3429 // Create fields
3430 for (unsigned i = 0; i < 3; ++i) {
3431 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3432 SourceLocation(), 0,
3433 FieldTypes[i], /*TInfo=*/0,
3434 /*BitWidth=*/0,
3435 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003436 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003437 NSConstantStringTypeDecl->addDecl(Field);
3438 }
3439
3440 NSConstantStringTypeDecl->completeDefinition();
3441 }
3442
3443 return getTagDeclType(NSConstantStringTypeDecl);
3444}
3445
3446void ASTContext::setNSConstantStringType(QualType T) {
3447 const RecordType *Rec = T->getAs<RecordType>();
3448 assert(Rec && "Invalid NSConstantStringType");
3449 NSConstantStringTypeDecl = Rec->getDecl();
3450}
3451
Jay Foad39c79802011-01-12 09:06:06 +00003452QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003453 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003454 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003455 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003456 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003457 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003458
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003459 QualType FieldTypes[] = {
3460 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003461 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003462 getPointerType(UnsignedLongTy),
3463 getConstantArrayType(UnsignedLongTy,
3464 llvm::APInt(32, 5), ArrayType::Normal, 0)
3465 };
Mike Stump11289f42009-09-09 15:08:12 +00003466
Douglas Gregor91f84212008-12-11 16:49:14 +00003467 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003468 FieldDecl *Field = FieldDecl::Create(*this,
3469 ObjCFastEnumerationStateTypeDecl,
3470 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003471 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003472 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003473 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003474 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003475 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003476 }
Mike Stump11289f42009-09-09 15:08:12 +00003477
Douglas Gregord5058122010-02-11 01:19:42 +00003478 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003479 }
Mike Stump11289f42009-09-09 15:08:12 +00003480
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003481 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3482}
3483
Jay Foad39c79802011-01-12 09:06:06 +00003484QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003485 if (BlockDescriptorType)
3486 return getTagDeclType(BlockDescriptorType);
3487
3488 RecordDecl *T;
3489 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003490 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003491 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003492 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003493
3494 QualType FieldTypes[] = {
3495 UnsignedLongTy,
3496 UnsignedLongTy,
3497 };
3498
3499 const char *FieldNames[] = {
3500 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003501 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003502 };
3503
3504 for (size_t i = 0; i < 2; ++i) {
3505 FieldDecl *Field = FieldDecl::Create(*this,
3506 T,
3507 SourceLocation(),
3508 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003509 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003510 /*BitWidth=*/0,
3511 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003512 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003513 T->addDecl(Field);
3514 }
3515
Douglas Gregord5058122010-02-11 01:19:42 +00003516 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003517
3518 BlockDescriptorType = T;
3519
3520 return getTagDeclType(BlockDescriptorType);
3521}
3522
3523void ASTContext::setBlockDescriptorType(QualType T) {
3524 const RecordType *Rec = T->getAs<RecordType>();
3525 assert(Rec && "Invalid BlockDescriptorType");
3526 BlockDescriptorType = Rec->getDecl();
3527}
3528
Jay Foad39c79802011-01-12 09:06:06 +00003529QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003530 if (BlockDescriptorExtendedType)
3531 return getTagDeclType(BlockDescriptorExtendedType);
3532
3533 RecordDecl *T;
3534 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003535 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003536 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003537 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003538
3539 QualType FieldTypes[] = {
3540 UnsignedLongTy,
3541 UnsignedLongTy,
3542 getPointerType(VoidPtrTy),
3543 getPointerType(VoidPtrTy)
3544 };
3545
3546 const char *FieldNames[] = {
3547 "reserved",
3548 "Size",
3549 "CopyFuncPtr",
3550 "DestroyFuncPtr"
3551 };
3552
3553 for (size_t i = 0; i < 4; ++i) {
3554 FieldDecl *Field = FieldDecl::Create(*this,
3555 T,
3556 SourceLocation(),
3557 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003558 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003559 /*BitWidth=*/0,
3560 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003561 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003562 T->addDecl(Field);
3563 }
3564
Douglas Gregord5058122010-02-11 01:19:42 +00003565 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003566
3567 BlockDescriptorExtendedType = T;
3568
3569 return getTagDeclType(BlockDescriptorExtendedType);
3570}
3571
3572void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3573 const RecordType *Rec = T->getAs<RecordType>();
3574 assert(Rec && "Invalid BlockDescriptorType");
3575 BlockDescriptorExtendedType = Rec->getDecl();
3576}
3577
Jay Foad39c79802011-01-12 09:06:06 +00003578bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003579 if (Ty->isBlockPointerType())
3580 return true;
3581 if (isObjCNSObjectType(Ty))
3582 return true;
3583 if (Ty->isObjCObjectPointerType())
3584 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003585 if (getLangOptions().CPlusPlus) {
3586 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3587 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3588 return RD->hasConstCopyConstructor(*this);
3589
3590 }
3591 }
Mike Stump94967902009-10-21 18:16:27 +00003592 return false;
3593}
3594
Jay Foad39c79802011-01-12 09:06:06 +00003595QualType
3596ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003597 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003598 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003599 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003600 // unsigned int __flags;
3601 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003602 // void *__copy_helper; // as needed
3603 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003604 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003605 // } *
3606
Mike Stump94967902009-10-21 18:16:27 +00003607 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3608
3609 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003610 llvm::SmallString<36> Name;
3611 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3612 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003613 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003614 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003615 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003616 T->startDefinition();
3617 QualType Int32Ty = IntTy;
3618 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3619 QualType FieldTypes[] = {
3620 getPointerType(VoidPtrTy),
3621 getPointerType(getTagDeclType(T)),
3622 Int32Ty,
3623 Int32Ty,
3624 getPointerType(VoidPtrTy),
3625 getPointerType(VoidPtrTy),
3626 Ty
3627 };
3628
Daniel Dunbar56df9772010-08-17 22:39:59 +00003629 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003630 "__isa",
3631 "__forwarding",
3632 "__flags",
3633 "__size",
3634 "__copy_helper",
3635 "__destroy_helper",
3636 DeclName,
3637 };
3638
3639 for (size_t i = 0; i < 7; ++i) {
3640 if (!HasCopyAndDispose && i >=4 && i <= 5)
3641 continue;
3642 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3643 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003644 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003645 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003646 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003647 T->addDecl(Field);
3648 }
3649
Douglas Gregord5058122010-02-11 01:19:42 +00003650 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003651
3652 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003653}
3654
Douglas Gregor512b0772009-04-23 22:29:11 +00003655void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003656 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003657 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3658 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3659}
3660
Anders Carlsson18acd442007-10-29 06:33:42 +00003661// This returns true if a type has been typedefed to BOOL:
3662// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003663static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003664 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003665 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3666 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003667
Anders Carlssond8499822007-10-29 05:01:08 +00003668 return false;
3669}
3670
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003671/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003672/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003673CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003674 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003675
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003676 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003677 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003678 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003679 // Treat arrays as pointers, since that's how they're passed in.
3680 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003681 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003682 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003683}
3684
3685static inline
3686std::string charUnitsToString(const CharUnits &CU) {
3687 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003688}
3689
John McCall351762c2011-02-07 10:33:21 +00003690/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003691/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003692std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3693 std::string S;
3694
David Chisnall950a9512009-11-17 19:33:30 +00003695 const BlockDecl *Decl = Expr->getBlockDecl();
3696 QualType BlockTy =
3697 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3698 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003699 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003700 // Compute size of all parameters.
3701 // Start with computing size of a pointer in number of bytes.
3702 // FIXME: There might(should) be a better way of doing this computation!
3703 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003704 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3705 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003706 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003707 E = Decl->param_end(); PI != E; ++PI) {
3708 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003709 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003710 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003711 ParmOffset += sz;
3712 }
3713 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003714 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003715 // Block pointer and offset.
3716 S += "@?0";
3717 ParmOffset = PtrSize;
3718
3719 // Argument types.
3720 ParmOffset = PtrSize;
3721 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3722 Decl->param_end(); PI != E; ++PI) {
3723 ParmVarDecl *PVDecl = *PI;
3724 QualType PType = PVDecl->getOriginalType();
3725 if (const ArrayType *AT =
3726 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3727 // Use array's original type only if it has known number of
3728 // elements.
3729 if (!isa<ConstantArrayType>(AT))
3730 PType = PVDecl->getType();
3731 } else if (PType->isFunctionType())
3732 PType = PVDecl->getType();
3733 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003734 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003735 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003736 }
John McCall351762c2011-02-07 10:33:21 +00003737
3738 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003739}
3740
David Chisnall50e4eba2010-12-30 14:05:53 +00003741void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3742 std::string& S) {
3743 // Encode result type.
3744 getObjCEncodingForType(Decl->getResultType(), S);
3745 CharUnits ParmOffset;
3746 // Compute size of all parameters.
3747 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3748 E = Decl->param_end(); PI != E; ++PI) {
3749 QualType PType = (*PI)->getType();
3750 CharUnits sz = getObjCEncodingTypeSize(PType);
3751 assert (sz.isPositive() &&
3752 "getObjCEncodingForMethodDecl - Incomplete param type");
3753 ParmOffset += sz;
3754 }
3755 S += charUnitsToString(ParmOffset);
3756 ParmOffset = CharUnits::Zero();
3757
3758 // Argument types.
3759 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3760 E = Decl->param_end(); PI != E; ++PI) {
3761 ParmVarDecl *PVDecl = *PI;
3762 QualType PType = PVDecl->getOriginalType();
3763 if (const ArrayType *AT =
3764 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3765 // Use array's original type only if it has known number of
3766 // elements.
3767 if (!isa<ConstantArrayType>(AT))
3768 PType = PVDecl->getType();
3769 } else if (PType->isFunctionType())
3770 PType = PVDecl->getType();
3771 getObjCEncodingForType(PType, S);
3772 S += charUnitsToString(ParmOffset);
3773 ParmOffset += getObjCEncodingTypeSize(PType);
3774 }
3775}
3776
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003777/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003778/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003779void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003780 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003781 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003782 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003783 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003784 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003785 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003786 // Compute size of all parameters.
3787 // Start with computing size of a pointer in number of bytes.
3788 // FIXME: There might(should) be a better way of doing this computation!
3789 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003790 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003791 // The first two arguments (self and _cmd) are pointers; account for
3792 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003793 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003794 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003795 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003796 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003797 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003798 assert (sz.isPositive() &&
3799 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003800 ParmOffset += sz;
3801 }
Ken Dyck40775002010-01-11 17:06:35 +00003802 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003803 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003804 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003805
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003806 // Argument types.
3807 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003808 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003809 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003810 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003811 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003812 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003813 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3814 // Use array's original type only if it has known number of
3815 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003816 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003817 PType = PVDecl->getType();
3818 } else if (PType->isFunctionType())
3819 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003820 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003821 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003822 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003823 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003824 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003825 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003826 }
3827}
3828
Daniel Dunbar4932b362008-08-28 04:38:10 +00003829/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003830/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003831/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3832/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003833/// Property attributes are stored as a comma-delimited C string. The simple
3834/// attributes readonly and bycopy are encoded as single characters. The
3835/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3836/// encoded as single characters, followed by an identifier. Property types
3837/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003838/// these attributes are defined by the following enumeration:
3839/// @code
3840/// enum PropertyAttributes {
3841/// kPropertyReadOnly = 'R', // property is read-only.
3842/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3843/// kPropertyByref = '&', // property is a reference to the value last assigned
3844/// kPropertyDynamic = 'D', // property is dynamic
3845/// kPropertyGetter = 'G', // followed by getter selector name
3846/// kPropertySetter = 'S', // followed by setter selector name
3847/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3848/// kPropertyType = 't' // followed by old-style type encoding.
3849/// kPropertyWeak = 'W' // 'weak' property
3850/// kPropertyStrong = 'P' // property GC'able
3851/// kPropertyNonAtomic = 'N' // property non-atomic
3852/// };
3853/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003854void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003855 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003856 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003857 // Collect information from the property implementation decl(s).
3858 bool Dynamic = false;
3859 ObjCPropertyImplDecl *SynthesizePID = 0;
3860
3861 // FIXME: Duplicated code due to poor abstraction.
3862 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003863 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003864 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3865 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003866 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003867 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003868 ObjCPropertyImplDecl *PID = *i;
3869 if (PID->getPropertyDecl() == PD) {
3870 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3871 Dynamic = true;
3872 } else {
3873 SynthesizePID = PID;
3874 }
3875 }
3876 }
3877 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003878 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003879 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003880 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003881 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003882 ObjCPropertyImplDecl *PID = *i;
3883 if (PID->getPropertyDecl() == PD) {
3884 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3885 Dynamic = true;
3886 } else {
3887 SynthesizePID = PID;
3888 }
3889 }
Mike Stump11289f42009-09-09 15:08:12 +00003890 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003891 }
3892 }
3893
3894 // FIXME: This is not very efficient.
3895 S = "T";
3896
3897 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003898 // GCC has some special rules regarding encoding of properties which
3899 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003900 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003901 true /* outermost type */,
3902 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003903
3904 if (PD->isReadOnly()) {
3905 S += ",R";
3906 } else {
3907 switch (PD->getSetterKind()) {
3908 case ObjCPropertyDecl::Assign: break;
3909 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003910 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003911 }
3912 }
3913
3914 // It really isn't clear at all what this means, since properties
3915 // are "dynamic by default".
3916 if (Dynamic)
3917 S += ",D";
3918
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003919 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3920 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003921
Daniel Dunbar4932b362008-08-28 04:38:10 +00003922 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3923 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003924 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003925 }
3926
3927 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3928 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003929 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003930 }
3931
3932 if (SynthesizePID) {
3933 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3934 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003935 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003936 }
3937
3938 // FIXME: OBJCGC: weak & strong
3939}
3940
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003941/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003942/// Another legacy compatibility encoding: 32-bit longs are encoded as
3943/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003944/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3945///
3946void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003947 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003948 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00003949 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003950 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003951 else
Jay Foad39c79802011-01-12 09:06:06 +00003952 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003953 PointeeTy = IntTy;
3954 }
3955 }
3956}
3957
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003958void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00003959 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003960 // We follow the behavior of gcc, expanding structures which are
3961 // directly pointed to, and expanding embedded structures. Note that
3962 // these rules are sufficient to prevent recursive encoding of the
3963 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003964 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003965 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003966}
3967
David Chisnallb190a2c2010-06-04 01:10:52 +00003968static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3969 switch (T->getAs<BuiltinType>()->getKind()) {
3970 default: assert(0 && "Unhandled builtin type kind");
3971 case BuiltinType::Void: return 'v';
3972 case BuiltinType::Bool: return 'B';
3973 case BuiltinType::Char_U:
3974 case BuiltinType::UChar: return 'C';
3975 case BuiltinType::UShort: return 'S';
3976 case BuiltinType::UInt: return 'I';
3977 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00003978 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003979 case BuiltinType::UInt128: return 'T';
3980 case BuiltinType::ULongLong: return 'Q';
3981 case BuiltinType::Char_S:
3982 case BuiltinType::SChar: return 'c';
3983 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00003984 case BuiltinType::WChar_S:
3985 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00003986 case BuiltinType::Int: return 'i';
3987 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00003988 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003989 case BuiltinType::LongLong: return 'q';
3990 case BuiltinType::Int128: return 't';
3991 case BuiltinType::Float: return 'f';
3992 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00003993 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00003994 }
3995}
3996
Jay Foad39c79802011-01-12 09:06:06 +00003997static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003998 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003999 const Expr *E = FD->getBitWidth();
4000 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004001 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004002 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4003 // The GNU runtime requires more information; bitfields are encoded as b,
4004 // then the offset (in bits) of the first element, then the type of the
4005 // bitfield, then the size in bits. For example, in this structure:
4006 //
4007 // struct
4008 // {
4009 // int integer;
4010 // int flags:2;
4011 // };
4012 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4013 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4014 // information is not especially sensible, but we're stuck with it for
4015 // compatibility with GCC, although providing it breaks anything that
4016 // actually uses runtime introspection and wants to work on both runtimes...
4017 if (!Ctx->getLangOptions().NeXTRuntime) {
4018 const RecordDecl *RD = FD->getParent();
4019 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4020 // FIXME: This same linear search is also used in ExprConstant - it might
4021 // be better if the FieldDecl stored its offset. We'd be increasing the
4022 // size of the object slightly, but saving some time every time it is used.
4023 unsigned i = 0;
4024 for (RecordDecl::field_iterator Field = RD->field_begin(),
4025 FieldEnd = RD->field_end();
4026 Field != FieldEnd; (void)++Field, ++i) {
4027 if (*Field == FD)
4028 break;
4029 }
4030 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004031 if (T->isEnumeralType())
4032 S += 'i';
4033 else
Jay Foad39c79802011-01-12 09:06:06 +00004034 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004035 }
4036 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004037 S += llvm::utostr(N);
4038}
4039
Daniel Dunbar07d07852009-10-18 21:17:35 +00004040// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004041void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4042 bool ExpandPointedToStructures,
4043 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004044 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004045 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00004046 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004047 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004048 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004049 return EncodeBitField(this, S, T, FD);
4050 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004051 return;
4052 }
Mike Stump11289f42009-09-09 15:08:12 +00004053
John McCall9dd450b2009-09-21 23:43:11 +00004054 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004055 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004056 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004057 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004058 return;
4059 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004060
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004061 // encoding for pointer or r3eference types.
4062 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004063 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004064 if (PT->isObjCSelType()) {
4065 S += ':';
4066 return;
4067 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004068 PointeeTy = PT->getPointeeType();
4069 }
4070 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4071 PointeeTy = RT->getPointeeType();
4072 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004073 bool isReadOnly = false;
4074 // For historical/compatibility reasons, the read-only qualifier of the
4075 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4076 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004077 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004078 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004079 if (OutermostType && T.isConstQualified()) {
4080 isReadOnly = true;
4081 S += 'r';
4082 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004083 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004084 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004085 while (P->getAs<PointerType>())
4086 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004087 if (P.isConstQualified()) {
4088 isReadOnly = true;
4089 S += 'r';
4090 }
4091 }
4092 if (isReadOnly) {
4093 // Another legacy compatibility encoding. Some ObjC qualifier and type
4094 // combinations need to be rearranged.
4095 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004096 if (llvm::StringRef(S).endswith("nr"))
4097 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004098 }
Mike Stump11289f42009-09-09 15:08:12 +00004099
Anders Carlssond8499822007-10-29 05:01:08 +00004100 if (PointeeTy->isCharType()) {
4101 // char pointer types should be encoded as '*' unless it is a
4102 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004103 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004104 S += '*';
4105 return;
4106 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004107 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004108 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4109 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4110 S += '#';
4111 return;
4112 }
4113 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4114 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4115 S += '@';
4116 return;
4117 }
4118 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004119 }
Anders Carlssond8499822007-10-29 05:01:08 +00004120 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004121 getLegacyIntegralTypeEncoding(PointeeTy);
4122
Mike Stump11289f42009-09-09 15:08:12 +00004123 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004124 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004125 return;
4126 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004127
Chris Lattnere7cabb92009-07-13 00:10:46 +00004128 if (const ArrayType *AT =
4129 // Ignore type qualifiers etc.
4130 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004131 if (isa<IncompleteArrayType>(AT)) {
4132 // Incomplete arrays are encoded as a pointer to the array element.
4133 S += '^';
4134
Mike Stump11289f42009-09-09 15:08:12 +00004135 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004136 false, ExpandStructures, FD);
4137 } else {
4138 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004139
Anders Carlssond05f44b2009-02-22 01:38:57 +00004140 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4141 S += llvm::utostr(CAT->getSize().getZExtValue());
4142 else {
4143 //Variable length arrays are encoded as a regular array with 0 elements.
4144 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4145 S += '0';
4146 }
Mike Stump11289f42009-09-09 15:08:12 +00004147
4148 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004149 false, ExpandStructures, FD);
4150 S += ']';
4151 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004152 return;
4153 }
Mike Stump11289f42009-09-09 15:08:12 +00004154
John McCall9dd450b2009-09-21 23:43:11 +00004155 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004156 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004157 return;
4158 }
Mike Stump11289f42009-09-09 15:08:12 +00004159
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004160 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004161 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004162 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004163 // Anonymous structures print as '?'
4164 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4165 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004166 if (ClassTemplateSpecializationDecl *Spec
4167 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4168 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4169 std::string TemplateArgsStr
4170 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004171 TemplateArgs.data(),
4172 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004173 (*this).PrintingPolicy);
4174
4175 S += TemplateArgsStr;
4176 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004177 } else {
4178 S += '?';
4179 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004180 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004181 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004182 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4183 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004184 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004185 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004186 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004187 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004188 S += '"';
4189 }
Mike Stump11289f42009-09-09 15:08:12 +00004190
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004191 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004192 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004193 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004194 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004195 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004196 QualType qt = Field->getType();
4197 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004198 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004199 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004200 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004201 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004202 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004203 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004204 return;
4205 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004206
Chris Lattnere7cabb92009-07-13 00:10:46 +00004207 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004208 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004209 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004210 else
4211 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004212 return;
4213 }
Mike Stump11289f42009-09-09 15:08:12 +00004214
Chris Lattnere7cabb92009-07-13 00:10:46 +00004215 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004216 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004217 return;
4218 }
Mike Stump11289f42009-09-09 15:08:12 +00004219
John McCall8b07ec22010-05-15 11:32:37 +00004220 // Ignore protocol qualifiers when mangling at this level.
4221 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4222 T = OT->getBaseType();
4223
John McCall8ccfcb52009-09-24 19:53:00 +00004224 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004225 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004226 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004227 S += '{';
4228 const IdentifierInfo *II = OI->getIdentifier();
4229 S += II->getName();
4230 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004231 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4232 DeepCollectObjCIvars(OI, true, Ivars);
4233 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4234 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4235 if (Field->isBitField())
4236 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004237 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004238 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004239 }
4240 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004241 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004242 }
Mike Stump11289f42009-09-09 15:08:12 +00004243
John McCall9dd450b2009-09-21 23:43:11 +00004244 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004245 if (OPT->isObjCIdType()) {
4246 S += '@';
4247 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004248 }
Mike Stump11289f42009-09-09 15:08:12 +00004249
Steve Narofff0c86112009-10-28 22:03:49 +00004250 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4251 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4252 // Since this is a binary compatibility issue, need to consult with runtime
4253 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004254 S += '#';
4255 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004256 }
Mike Stump11289f42009-09-09 15:08:12 +00004257
Chris Lattnere7cabb92009-07-13 00:10:46 +00004258 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004259 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004260 ExpandPointedToStructures,
4261 ExpandStructures, FD);
4262 if (FD || EncodingProperty) {
4263 // Note that we do extended encoding of protocol qualifer list
4264 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004265 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004266 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4267 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004268 S += '<';
4269 S += (*I)->getNameAsString();
4270 S += '>';
4271 }
4272 S += '"';
4273 }
4274 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004275 }
Mike Stump11289f42009-09-09 15:08:12 +00004276
Chris Lattnere7cabb92009-07-13 00:10:46 +00004277 QualType PointeeTy = OPT->getPointeeType();
4278 if (!EncodingProperty &&
4279 isa<TypedefType>(PointeeTy.getTypePtr())) {
4280 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004281 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004282 // {...};
4283 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004284 getObjCEncodingForTypeImpl(PointeeTy, S,
4285 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004286 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004287 return;
4288 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004289
4290 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004291 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004292 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004293 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004294 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4295 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004296 S += '<';
4297 S += (*I)->getNameAsString();
4298 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004299 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004300 S += '"';
4301 }
4302 return;
4303 }
Mike Stump11289f42009-09-09 15:08:12 +00004304
John McCalla9e6e8d2010-05-17 23:56:34 +00004305 // gcc just blithely ignores member pointers.
4306 // TODO: maybe there should be a mangling for these
4307 if (T->getAs<MemberPointerType>())
4308 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004309
4310 if (T->isVectorType()) {
4311 // This matches gcc's encoding, even though technically it is
4312 // insufficient.
4313 // FIXME. We should do a better job than gcc.
4314 return;
4315 }
4316
Chris Lattnere7cabb92009-07-13 00:10:46 +00004317 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004318}
4319
Mike Stump11289f42009-09-09 15:08:12 +00004320void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004321 std::string& S) const {
4322 if (QT & Decl::OBJC_TQ_In)
4323 S += 'n';
4324 if (QT & Decl::OBJC_TQ_Inout)
4325 S += 'N';
4326 if (QT & Decl::OBJC_TQ_Out)
4327 S += 'o';
4328 if (QT & Decl::OBJC_TQ_Bycopy)
4329 S += 'O';
4330 if (QT & Decl::OBJC_TQ_Byref)
4331 S += 'R';
4332 if (QT & Decl::OBJC_TQ_Oneway)
4333 S += 'V';
4334}
4335
Chris Lattnere7cabb92009-07-13 00:10:46 +00004336void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004337 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004338
Anders Carlsson87c149b2007-10-11 01:00:40 +00004339 BuiltinVaListType = T;
4340}
4341
Chris Lattnere7cabb92009-07-13 00:10:46 +00004342void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004343 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004344}
4345
Chris Lattnere7cabb92009-07-13 00:10:46 +00004346void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004347 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004348}
4349
Chris Lattnere7cabb92009-07-13 00:10:46 +00004350void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004351 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004352}
4353
Chris Lattnere7cabb92009-07-13 00:10:46 +00004354void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004355 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004356}
4357
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004358void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004359 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004360 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004361
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004362 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004363}
4364
John McCalld28ae272009-12-02 08:04:21 +00004365/// \brief Retrieve the template name that corresponds to a non-empty
4366/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004367TemplateName
4368ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4369 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004370 unsigned size = End - Begin;
4371 assert(size > 1 && "set is not overloaded!");
4372
4373 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4374 size * sizeof(FunctionTemplateDecl*));
4375 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4376
4377 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004378 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004379 NamedDecl *D = *I;
4380 assert(isa<FunctionTemplateDecl>(D) ||
4381 (isa<UsingShadowDecl>(D) &&
4382 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4383 *Storage++ = D;
4384 }
4385
4386 return TemplateName(OT);
4387}
4388
Douglas Gregordc572a32009-03-30 22:58:21 +00004389/// \brief Retrieve the template name that represents a qualified
4390/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004391TemplateName
4392ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4393 bool TemplateKeyword,
4394 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004395 assert(NNS && "Missing nested-name-specifier in qualified template name");
4396
Douglas Gregorc42075a2010-02-04 18:10:26 +00004397 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004398 llvm::FoldingSetNodeID ID;
4399 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4400
4401 void *InsertPos = 0;
4402 QualifiedTemplateName *QTN =
4403 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4404 if (!QTN) {
4405 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4406 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4407 }
4408
4409 return TemplateName(QTN);
4410}
4411
4412/// \brief Retrieve the template name that represents a dependent
4413/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004414TemplateName
4415ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4416 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004417 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004418 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004419
4420 llvm::FoldingSetNodeID ID;
4421 DependentTemplateName::Profile(ID, NNS, Name);
4422
4423 void *InsertPos = 0;
4424 DependentTemplateName *QTN =
4425 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4426
4427 if (QTN)
4428 return TemplateName(QTN);
4429
4430 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4431 if (CanonNNS == NNS) {
4432 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4433 } else {
4434 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4435 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004436 DependentTemplateName *CheckQTN =
4437 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4438 assert(!CheckQTN && "Dependent type name canonicalization broken");
4439 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004440 }
4441
4442 DependentTemplateNames.InsertNode(QTN, InsertPos);
4443 return TemplateName(QTN);
4444}
4445
Douglas Gregor71395fa2009-11-04 00:56:37 +00004446/// \brief Retrieve the template name that represents a dependent
4447/// template name such as \c MetaFun::template operator+.
4448TemplateName
4449ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004450 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004451 assert((!NNS || NNS->isDependent()) &&
4452 "Nested name specifier must be dependent");
4453
4454 llvm::FoldingSetNodeID ID;
4455 DependentTemplateName::Profile(ID, NNS, Operator);
4456
4457 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004458 DependentTemplateName *QTN
4459 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004460
4461 if (QTN)
4462 return TemplateName(QTN);
4463
4464 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4465 if (CanonNNS == NNS) {
4466 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4467 } else {
4468 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4469 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004470
4471 DependentTemplateName *CheckQTN
4472 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4473 assert(!CheckQTN && "Dependent template name canonicalization broken");
4474 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004475 }
4476
4477 DependentTemplateNames.InsertNode(QTN, InsertPos);
4478 return TemplateName(QTN);
4479}
4480
Douglas Gregor5590be02011-01-15 06:45:20 +00004481TemplateName
4482ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4483 const TemplateArgument &ArgPack) const {
4484 ASTContext &Self = const_cast<ASTContext &>(*this);
4485 llvm::FoldingSetNodeID ID;
4486 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4487
4488 void *InsertPos = 0;
4489 SubstTemplateTemplateParmPackStorage *Subst
4490 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4491
4492 if (!Subst) {
4493 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4494 ArgPack.pack_size(),
4495 ArgPack.pack_begin());
4496 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4497 }
4498
4499 return TemplateName(Subst);
4500}
4501
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004502/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004503/// TargetInfo, produce the corresponding type. The unsigned @p Type
4504/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004505CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004506 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004507 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004508 case TargetInfo::SignedShort: return ShortTy;
4509 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4510 case TargetInfo::SignedInt: return IntTy;
4511 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4512 case TargetInfo::SignedLong: return LongTy;
4513 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4514 case TargetInfo::SignedLongLong: return LongLongTy;
4515 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4516 }
4517
4518 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004519 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004520}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004521
4522//===----------------------------------------------------------------------===//
4523// Type Predicates.
4524//===----------------------------------------------------------------------===//
4525
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004526/// isObjCNSObjectType - Return true if this is an NSObject object using
4527/// NSObject attribute on a c-style pointer type.
4528/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004529/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004530///
4531bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCall424cec92011-01-19 06:33:43 +00004532 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004533 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004534 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004535 return true;
4536 }
Mike Stump11289f42009-09-09 15:08:12 +00004537 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004538}
4539
Fariborz Jahanian96207692009-02-18 21:49:28 +00004540/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4541/// garbage collection attribute.
4542///
John McCall553d45a2011-01-12 00:34:59 +00004543Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4544 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4545 return Qualifiers::GCNone;
4546
4547 assert(getLangOptions().ObjC1);
4548 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4549
4550 // Default behaviour under objective-C's gc is for ObjC pointers
4551 // (or pointers to them) be treated as though they were declared
4552 // as __strong.
4553 if (GCAttrs == Qualifiers::GCNone) {
4554 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4555 return Qualifiers::Strong;
4556 else if (Ty->isPointerType())
4557 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4558 } else {
4559 // It's not valid to set GC attributes on anything that isn't a
4560 // pointer.
4561#ifndef NDEBUG
4562 QualType CT = Ty->getCanonicalTypeInternal();
4563 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4564 CT = AT->getElementType();
4565 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4566#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004567 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004568 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004569}
4570
Chris Lattner49af6a42008-04-07 06:51:04 +00004571//===----------------------------------------------------------------------===//
4572// Type Compatibility Testing
4573//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004574
Mike Stump11289f42009-09-09 15:08:12 +00004575/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004576/// compatible.
4577static bool areCompatVectorTypes(const VectorType *LHS,
4578 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004579 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004580 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004581 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004582}
4583
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004584bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4585 QualType SecondVec) {
4586 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4587 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4588
4589 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4590 return true;
4591
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004592 // Treat Neon vector types and most AltiVec vector types as if they are the
4593 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004594 const VectorType *First = FirstVec->getAs<VectorType>();
4595 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004596 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004597 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004598 First->getVectorKind() != VectorType::AltiVecPixel &&
4599 First->getVectorKind() != VectorType::AltiVecBool &&
4600 Second->getVectorKind() != VectorType::AltiVecPixel &&
4601 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004602 return true;
4603
4604 return false;
4605}
4606
Steve Naroff8e6aee52009-07-23 01:01:38 +00004607//===----------------------------------------------------------------------===//
4608// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4609//===----------------------------------------------------------------------===//
4610
4611/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4612/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004613bool
4614ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4615 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004616 if (lProto == rProto)
4617 return true;
4618 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4619 E = rProto->protocol_end(); PI != E; ++PI)
4620 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4621 return true;
4622 return false;
4623}
4624
Steve Naroff8e6aee52009-07-23 01:01:38 +00004625/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4626/// return true if lhs's protocols conform to rhs's protocol; false
4627/// otherwise.
4628bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4629 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4630 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4631 return false;
4632}
4633
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004634/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4635/// Class<p1, ...>.
4636bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4637 QualType rhs) {
4638 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4639 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4640 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4641
4642 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4643 E = lhsQID->qual_end(); I != E; ++I) {
4644 bool match = false;
4645 ObjCProtocolDecl *lhsProto = *I;
4646 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4647 E = rhsOPT->qual_end(); J != E; ++J) {
4648 ObjCProtocolDecl *rhsProto = *J;
4649 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4650 match = true;
4651 break;
4652 }
4653 }
4654 if (!match)
4655 return false;
4656 }
4657 return true;
4658}
4659
Steve Naroff8e6aee52009-07-23 01:01:38 +00004660/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4661/// ObjCQualifiedIDType.
4662bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4663 bool compare) {
4664 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004665 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004666 lhs->isObjCIdType() || lhs->isObjCClassType())
4667 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004668 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004669 rhs->isObjCIdType() || rhs->isObjCClassType())
4670 return true;
4671
4672 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004673 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004674
Steve Naroff8e6aee52009-07-23 01:01:38 +00004675 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004676
Steve Naroff8e6aee52009-07-23 01:01:38 +00004677 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004678 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004679 // make sure we check the class hierarchy.
4680 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4681 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4682 E = lhsQID->qual_end(); I != E; ++I) {
4683 // when comparing an id<P> on lhs with a static type on rhs,
4684 // see if static class implements all of id's protocols, directly or
4685 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004686 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004687 return false;
4688 }
4689 }
4690 // If there are no qualifiers and no interface, we have an 'id'.
4691 return true;
4692 }
Mike Stump11289f42009-09-09 15:08:12 +00004693 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004694 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4695 E = lhsQID->qual_end(); I != E; ++I) {
4696 ObjCProtocolDecl *lhsProto = *I;
4697 bool match = false;
4698
4699 // when comparing an id<P> on lhs with a static type on rhs,
4700 // see if static class implements all of id's protocols, directly or
4701 // through its super class and categories.
4702 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4703 E = rhsOPT->qual_end(); J != E; ++J) {
4704 ObjCProtocolDecl *rhsProto = *J;
4705 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4706 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4707 match = true;
4708 break;
4709 }
4710 }
Mike Stump11289f42009-09-09 15:08:12 +00004711 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004712 // make sure we check the class hierarchy.
4713 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4714 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4715 E = lhsQID->qual_end(); I != E; ++I) {
4716 // when comparing an id<P> on lhs with a static type on rhs,
4717 // see if static class implements all of id's protocols, directly or
4718 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004719 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004720 match = true;
4721 break;
4722 }
4723 }
4724 }
4725 if (!match)
4726 return false;
4727 }
Mike Stump11289f42009-09-09 15:08:12 +00004728
Steve Naroff8e6aee52009-07-23 01:01:38 +00004729 return true;
4730 }
Mike Stump11289f42009-09-09 15:08:12 +00004731
Steve Naroff8e6aee52009-07-23 01:01:38 +00004732 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4733 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4734
Mike Stump11289f42009-09-09 15:08:12 +00004735 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004736 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004737 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004738 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4739 E = lhsOPT->qual_end(); I != E; ++I) {
4740 ObjCProtocolDecl *lhsProto = *I;
4741 bool match = false;
4742
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004743 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004744 // see if static class implements all of id's protocols, directly or
4745 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004746 // First, lhs protocols in the qualifier list must be found, direct
4747 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004748 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4749 E = rhsQID->qual_end(); J != E; ++J) {
4750 ObjCProtocolDecl *rhsProto = *J;
4751 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4752 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4753 match = true;
4754 break;
4755 }
4756 }
4757 if (!match)
4758 return false;
4759 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004760
4761 // Static class's protocols, or its super class or category protocols
4762 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4763 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4764 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4765 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4766 // This is rather dubious but matches gcc's behavior. If lhs has
4767 // no type qualifier and its class has no static protocol(s)
4768 // assume that it is mismatch.
4769 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4770 return false;
4771 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4772 LHSInheritedProtocols.begin(),
4773 E = LHSInheritedProtocols.end(); I != E; ++I) {
4774 bool match = false;
4775 ObjCProtocolDecl *lhsProto = (*I);
4776 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4777 E = rhsQID->qual_end(); J != E; ++J) {
4778 ObjCProtocolDecl *rhsProto = *J;
4779 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4780 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4781 match = true;
4782 break;
4783 }
4784 }
4785 if (!match)
4786 return false;
4787 }
4788 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004789 return true;
4790 }
4791 return false;
4792}
4793
Eli Friedman47f77112008-08-22 00:56:42 +00004794/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004795/// compatible for assignment from RHS to LHS. This handles validation of any
4796/// protocol qualifiers on the LHS or RHS.
4797///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004798bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4799 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004800 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4801 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4802
Steve Naroff1329fa02009-07-15 18:40:39 +00004803 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004804 if (LHS->isObjCUnqualifiedIdOrClass() ||
4805 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004806 return true;
4807
John McCall8b07ec22010-05-15 11:32:37 +00004808 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004809 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4810 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004811 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004812
4813 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4814 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4815 QualType(RHSOPT,0));
4816
John McCall8b07ec22010-05-15 11:32:37 +00004817 // If we have 2 user-defined types, fall into that path.
4818 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004819 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004820
Steve Naroff8e6aee52009-07-23 01:01:38 +00004821 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004822}
4823
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004824/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4825/// for providing type-safty for objective-c pointers used to pass/return
4826/// arguments in block literals. When passed as arguments, passing 'A*' where
4827/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4828/// not OK. For the return type, the opposite is not OK.
4829bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4830 const ObjCObjectPointerType *LHSOPT,
4831 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004832 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004833 return true;
4834
4835 if (LHSOPT->isObjCBuiltinType()) {
4836 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4837 }
4838
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004839 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004840 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4841 QualType(RHSOPT,0),
4842 false);
4843
4844 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4845 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4846 if (LHS && RHS) { // We have 2 user-defined types.
4847 if (LHS != RHS) {
4848 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4849 return false;
4850 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4851 return true;
4852 }
4853 else
4854 return true;
4855 }
4856 return false;
4857}
4858
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004859/// getIntersectionOfProtocols - This routine finds the intersection of set
4860/// of protocols inherited from two distinct objective-c pointer objects.
4861/// It is used to build composite qualifier list of the composite type of
4862/// the conditional expression involving two objective-c pointer objects.
4863static
4864void getIntersectionOfProtocols(ASTContext &Context,
4865 const ObjCObjectPointerType *LHSOPT,
4866 const ObjCObjectPointerType *RHSOPT,
4867 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4868
John McCall8b07ec22010-05-15 11:32:37 +00004869 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4870 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4871 assert(LHS->getInterface() && "LHS must have an interface base");
4872 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004873
4874 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4875 unsigned LHSNumProtocols = LHS->getNumProtocols();
4876 if (LHSNumProtocols > 0)
4877 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4878 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004879 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004880 Context.CollectInheritedProtocols(LHS->getInterface(),
4881 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004882 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4883 LHSInheritedProtocols.end());
4884 }
4885
4886 unsigned RHSNumProtocols = RHS->getNumProtocols();
4887 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004888 ObjCProtocolDecl **RHSProtocols =
4889 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004890 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4891 if (InheritedProtocolSet.count(RHSProtocols[i]))
4892 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4893 }
4894 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004895 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004896 Context.CollectInheritedProtocols(RHS->getInterface(),
4897 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004898 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4899 RHSInheritedProtocols.begin(),
4900 E = RHSInheritedProtocols.end(); I != E; ++I)
4901 if (InheritedProtocolSet.count((*I)))
4902 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004903 }
4904}
4905
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004906/// areCommonBaseCompatible - Returns common base class of the two classes if
4907/// one found. Note that this is O'2 algorithm. But it will be called as the
4908/// last type comparison in a ?-exp of ObjC pointer types before a
4909/// warning is issued. So, its invokation is extremely rare.
4910QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004911 const ObjCObjectPointerType *Lptr,
4912 const ObjCObjectPointerType *Rptr) {
4913 const ObjCObjectType *LHS = Lptr->getObjectType();
4914 const ObjCObjectType *RHS = Rptr->getObjectType();
4915 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4916 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4917 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004918 return QualType();
4919
John McCall8b07ec22010-05-15 11:32:37 +00004920 while ((LDecl = LDecl->getSuperClass())) {
4921 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004922 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004923 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4924 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4925
4926 QualType Result = QualType(LHS, 0);
4927 if (!Protocols.empty())
4928 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4929 Result = getObjCObjectPointerType(Result);
4930 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004931 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004932 }
4933
4934 return QualType();
4935}
4936
John McCall8b07ec22010-05-15 11:32:37 +00004937bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4938 const ObjCObjectType *RHS) {
4939 assert(LHS->getInterface() && "LHS is not an interface type");
4940 assert(RHS->getInterface() && "RHS is not an interface type");
4941
Chris Lattner49af6a42008-04-07 06:51:04 +00004942 // Verify that the base decls are compatible: the RHS must be a subclass of
4943 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004944 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004945 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004946
Chris Lattner49af6a42008-04-07 06:51:04 +00004947 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4948 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004949 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004950 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004951
Chris Lattner49af6a42008-04-07 06:51:04 +00004952 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4953 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004954 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004955 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004956
John McCall8b07ec22010-05-15 11:32:37 +00004957 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4958 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004959 LHSPI != LHSPE; LHSPI++) {
4960 bool RHSImplementsProtocol = false;
4961
4962 // If the RHS doesn't implement the protocol on the left, the types
4963 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004964 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4965 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004966 RHSPI != RHSPE; RHSPI++) {
4967 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004968 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004969 break;
4970 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004971 }
4972 // FIXME: For better diagnostics, consider passing back the protocol name.
4973 if (!RHSImplementsProtocol)
4974 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004975 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004976 // The RHS implements all protocols listed on the LHS.
4977 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004978}
4979
Steve Naroffb7605152009-02-12 17:52:19 +00004980bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4981 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004982 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4983 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004984
Steve Naroff7cae42b2009-07-10 23:34:53 +00004985 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004986 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004987
4988 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4989 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004990}
4991
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004992bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4993 return canAssignObjCInterfaces(
4994 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4995 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4996}
4997
Mike Stump11289f42009-09-09 15:08:12 +00004998/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004999/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005000/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005001/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005002bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5003 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005004 if (getLangOptions().CPlusPlus)
5005 return hasSameType(LHS, RHS);
5006
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005007 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005008}
5009
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005010bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5011 return !mergeTypes(LHS, RHS, true).isNull();
5012}
5013
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005014/// mergeTransparentUnionType - if T is a transparent union type and a member
5015/// of T is compatible with SubType, return the merged type, else return
5016/// QualType()
5017QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5018 bool OfBlockPointer,
5019 bool Unqualified) {
5020 if (const RecordType *UT = T->getAsUnionType()) {
5021 RecordDecl *UD = UT->getDecl();
5022 if (UD->hasAttr<TransparentUnionAttr>()) {
5023 for (RecordDecl::field_iterator it = UD->field_begin(),
5024 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005025 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005026 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5027 if (!MT.isNull())
5028 return MT;
5029 }
5030 }
5031 }
5032
5033 return QualType();
5034}
5035
5036/// mergeFunctionArgumentTypes - merge two types which appear as function
5037/// argument types
5038QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5039 bool OfBlockPointer,
5040 bool Unqualified) {
5041 // GNU extension: two types are compatible if they appear as a function
5042 // argument, one of the types is a transparent union type and the other
5043 // type is compatible with a union member
5044 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5045 Unqualified);
5046 if (!lmerge.isNull())
5047 return lmerge;
5048
5049 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5050 Unqualified);
5051 if (!rmerge.isNull())
5052 return rmerge;
5053
5054 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5055}
5056
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005057QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005058 bool OfBlockPointer,
5059 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005060 const FunctionType *lbase = lhs->getAs<FunctionType>();
5061 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005062 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5063 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005064 bool allLTypes = true;
5065 bool allRTypes = true;
5066
5067 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005068 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005069 if (OfBlockPointer) {
5070 QualType RHS = rbase->getResultType();
5071 QualType LHS = lbase->getResultType();
5072 bool UnqualifiedResult = Unqualified;
5073 if (!UnqualifiedResult)
5074 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
5075 retType = mergeTypes(RHS, LHS, true, UnqualifiedResult);
5076 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005077 else
John McCall8c6b56f2010-12-15 01:06:38 +00005078 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5079 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005080 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005081
5082 if (Unqualified)
5083 retType = retType.getUnqualifiedType();
5084
5085 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5086 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5087 if (Unqualified) {
5088 LRetType = LRetType.getUnqualifiedType();
5089 RRetType = RRetType.getUnqualifiedType();
5090 }
5091
5092 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005093 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005094 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005095 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005096
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005097 // FIXME: double check this
5098 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5099 // rbase->getRegParmAttr() != 0 &&
5100 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005101 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5102 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005103
Douglas Gregor8c940862010-01-18 17:14:39 +00005104 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005105 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005106 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005107
John McCall8c6b56f2010-12-15 01:06:38 +00005108 // Regparm is part of the calling convention.
5109 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5110 return QualType();
5111
5112 // It's noreturn if either type is.
5113 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5114 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5115 if (NoReturn != lbaseInfo.getNoReturn())
5116 allLTypes = false;
5117 if (NoReturn != rbaseInfo.getNoReturn())
5118 allRTypes = false;
5119
5120 FunctionType::ExtInfo einfo(NoReturn,
5121 lbaseInfo.getRegParm(),
5122 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00005123
Eli Friedman47f77112008-08-22 00:56:42 +00005124 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005125 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5126 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005127 unsigned lproto_nargs = lproto->getNumArgs();
5128 unsigned rproto_nargs = rproto->getNumArgs();
5129
5130 // Compatible functions must have the same number of arguments
5131 if (lproto_nargs != rproto_nargs)
5132 return QualType();
5133
5134 // Variadic and non-variadic functions aren't compatible
5135 if (lproto->isVariadic() != rproto->isVariadic())
5136 return QualType();
5137
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005138 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5139 return QualType();
5140
Eli Friedman47f77112008-08-22 00:56:42 +00005141 // Check argument compatibility
5142 llvm::SmallVector<QualType, 10> types;
5143 for (unsigned i = 0; i < lproto_nargs; i++) {
5144 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5145 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005146 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5147 OfBlockPointer,
5148 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005149 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005150
5151 if (Unqualified)
5152 argtype = argtype.getUnqualifiedType();
5153
Eli Friedman47f77112008-08-22 00:56:42 +00005154 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005155 if (Unqualified) {
5156 largtype = largtype.getUnqualifiedType();
5157 rargtype = rargtype.getUnqualifiedType();
5158 }
5159
Chris Lattner465fa322008-10-05 17:34:18 +00005160 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5161 allLTypes = false;
5162 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5163 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005164 }
5165 if (allLTypes) return lhs;
5166 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005167
5168 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5169 EPI.ExtInfo = einfo;
5170 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005171 }
5172
5173 if (lproto) allRTypes = false;
5174 if (rproto) allLTypes = false;
5175
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005176 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005177 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005178 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005179 if (proto->isVariadic()) return QualType();
5180 // Check that the types are compatible with the types that
5181 // would result from default argument promotions (C99 6.7.5.3p15).
5182 // The only types actually affected are promotable integer
5183 // types and floats, which would be passed as a different
5184 // type depending on whether the prototype is visible.
5185 unsigned proto_nargs = proto->getNumArgs();
5186 for (unsigned i = 0; i < proto_nargs; ++i) {
5187 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005188
5189 // Look at the promotion type of enum types, since that is the type used
5190 // to pass enum values.
5191 if (const EnumType *Enum = argTy->getAs<EnumType>())
5192 argTy = Enum->getDecl()->getPromotionType();
5193
Eli Friedman47f77112008-08-22 00:56:42 +00005194 if (argTy->isPromotableIntegerType() ||
5195 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5196 return QualType();
5197 }
5198
5199 if (allLTypes) return lhs;
5200 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005201
5202 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5203 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005204 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005205 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005206 }
5207
5208 if (allLTypes) return lhs;
5209 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005210 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005211}
5212
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005213QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005214 bool OfBlockPointer,
5215 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005216 // C++ [expr]: If an expression initially has the type "reference to T", the
5217 // type is adjusted to "T" prior to any further analysis, the expression
5218 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005219 // expression is an lvalue unless the reference is an rvalue reference and
5220 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005221 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5222 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005223
5224 if (Unqualified) {
5225 LHS = LHS.getUnqualifiedType();
5226 RHS = RHS.getUnqualifiedType();
5227 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005228
Eli Friedman47f77112008-08-22 00:56:42 +00005229 QualType LHSCan = getCanonicalType(LHS),
5230 RHSCan = getCanonicalType(RHS);
5231
5232 // If two types are identical, they are compatible.
5233 if (LHSCan == RHSCan)
5234 return LHS;
5235
John McCall8ccfcb52009-09-24 19:53:00 +00005236 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005237 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5238 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005239 if (LQuals != RQuals) {
5240 // If any of these qualifiers are different, we have a type
5241 // mismatch.
5242 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5243 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5244 return QualType();
5245
5246 // Exactly one GC qualifier difference is allowed: __strong is
5247 // okay if the other type has no GC qualifier but is an Objective
5248 // C object pointer (i.e. implicitly strong by default). We fix
5249 // this by pretending that the unqualified type was actually
5250 // qualified __strong.
5251 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5252 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5253 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5254
5255 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5256 return QualType();
5257
5258 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5259 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5260 }
5261 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5262 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5263 }
Eli Friedman47f77112008-08-22 00:56:42 +00005264 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005265 }
5266
5267 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005268
Eli Friedmandcca6332009-06-01 01:22:52 +00005269 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5270 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005271
Chris Lattnerfd652912008-01-14 05:45:46 +00005272 // We want to consider the two function types to be the same for these
5273 // comparisons, just force one to the other.
5274 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5275 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005276
5277 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005278 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5279 LHSClass = Type::ConstantArray;
5280 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5281 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005282
John McCall8b07ec22010-05-15 11:32:37 +00005283 // ObjCInterfaces are just specialized ObjCObjects.
5284 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5285 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5286
Nate Begemance4d7fc2008-04-18 23:10:10 +00005287 // Canonicalize ExtVector -> Vector.
5288 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5289 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005290
Chris Lattner95554662008-04-07 05:43:21 +00005291 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005292 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005293 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005294 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005295 // Compatibility is based on the underlying type, not the promotion
5296 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005297 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005298 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5299 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005300 }
John McCall9dd450b2009-09-21 23:43:11 +00005301 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005302 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5303 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005304 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005305
Eli Friedman47f77112008-08-22 00:56:42 +00005306 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005307 }
Eli Friedman47f77112008-08-22 00:56:42 +00005308
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005309 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005310 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005311#define TYPE(Class, Base)
5312#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005313#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005314#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5315#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5316#include "clang/AST/TypeNodes.def"
5317 assert(false && "Non-canonical and dependent types shouldn't get here");
5318 return QualType();
5319
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005320 case Type::LValueReference:
5321 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005322 case Type::MemberPointer:
5323 assert(false && "C++ should never be in mergeTypes");
5324 return QualType();
5325
John McCall8b07ec22010-05-15 11:32:37 +00005326 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005327 case Type::IncompleteArray:
5328 case Type::VariableArray:
5329 case Type::FunctionProto:
5330 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005331 assert(false && "Types are eliminated above");
5332 return QualType();
5333
Chris Lattnerfd652912008-01-14 05:45:46 +00005334 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005335 {
5336 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005337 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5338 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005339 if (Unqualified) {
5340 LHSPointee = LHSPointee.getUnqualifiedType();
5341 RHSPointee = RHSPointee.getUnqualifiedType();
5342 }
5343 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5344 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005345 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005346 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005347 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005348 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005349 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005350 return getPointerType(ResultType);
5351 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005352 case Type::BlockPointer:
5353 {
5354 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005355 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5356 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005357 if (Unqualified) {
5358 LHSPointee = LHSPointee.getUnqualifiedType();
5359 RHSPointee = RHSPointee.getUnqualifiedType();
5360 }
5361 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5362 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005363 if (ResultType.isNull()) return QualType();
5364 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5365 return LHS;
5366 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5367 return RHS;
5368 return getBlockPointerType(ResultType);
5369 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005370 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005371 {
5372 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5373 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5374 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5375 return QualType();
5376
5377 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5378 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005379 if (Unqualified) {
5380 LHSElem = LHSElem.getUnqualifiedType();
5381 RHSElem = RHSElem.getUnqualifiedType();
5382 }
5383
5384 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005385 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005386 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5387 return LHS;
5388 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5389 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005390 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5391 ArrayType::ArraySizeModifier(), 0);
5392 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5393 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005394 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5395 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005396 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5397 return LHS;
5398 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5399 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005400 if (LVAT) {
5401 // FIXME: This isn't correct! But tricky to implement because
5402 // the array's size has to be the size of LHS, but the type
5403 // has to be different.
5404 return LHS;
5405 }
5406 if (RVAT) {
5407 // FIXME: This isn't correct! But tricky to implement because
5408 // the array's size has to be the size of RHS, but the type
5409 // has to be different.
5410 return RHS;
5411 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005412 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5413 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005414 return getIncompleteArrayType(ResultType,
5415 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005416 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005417 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005418 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005419 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005420 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005421 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005422 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005423 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005424 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005425 case Type::Complex:
5426 // Distinct complex types are incompatible.
5427 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005428 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005429 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005430 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5431 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005432 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005433 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005434 case Type::ObjCObject: {
5435 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005436 // FIXME: This should be type compatibility, e.g. whether
5437 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005438 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5439 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5440 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005441 return LHS;
5442
Eli Friedman47f77112008-08-22 00:56:42 +00005443 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005444 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005445 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005446 if (OfBlockPointer) {
5447 if (canAssignObjCInterfacesInBlockPointer(
5448 LHS->getAs<ObjCObjectPointerType>(),
5449 RHS->getAs<ObjCObjectPointerType>()))
5450 return LHS;
5451 return QualType();
5452 }
John McCall9dd450b2009-09-21 23:43:11 +00005453 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5454 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005455 return LHS;
5456
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005457 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005458 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005459 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005460
5461 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005462}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005463
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005464/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5465/// 'RHS' attributes and returns the merged version; including for function
5466/// return types.
5467QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5468 QualType LHSCan = getCanonicalType(LHS),
5469 RHSCan = getCanonicalType(RHS);
5470 // If two types are identical, they are compatible.
5471 if (LHSCan == RHSCan)
5472 return LHS;
5473 if (RHSCan->isFunctionType()) {
5474 if (!LHSCan->isFunctionType())
5475 return QualType();
5476 QualType OldReturnType =
5477 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5478 QualType NewReturnType =
5479 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5480 QualType ResReturnType =
5481 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5482 if (ResReturnType.isNull())
5483 return QualType();
5484 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5485 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5486 // In either case, use OldReturnType to build the new function type.
5487 const FunctionType *F = LHS->getAs<FunctionType>();
5488 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005489 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5490 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005491 QualType ResultType
5492 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005493 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005494 return ResultType;
5495 }
5496 }
5497 return QualType();
5498 }
5499
5500 // If the qualifiers are different, the types can still be merged.
5501 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5502 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5503 if (LQuals != RQuals) {
5504 // If any of these qualifiers are different, we have a type mismatch.
5505 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5506 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5507 return QualType();
5508
5509 // Exactly one GC qualifier difference is allowed: __strong is
5510 // okay if the other type has no GC qualifier but is an Objective
5511 // C object pointer (i.e. implicitly strong by default). We fix
5512 // this by pretending that the unqualified type was actually
5513 // qualified __strong.
5514 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5515 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5516 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5517
5518 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5519 return QualType();
5520
5521 if (GC_L == Qualifiers::Strong)
5522 return LHS;
5523 if (GC_R == Qualifiers::Strong)
5524 return RHS;
5525 return QualType();
5526 }
5527
5528 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5529 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5530 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5531 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5532 if (ResQT == LHSBaseQT)
5533 return LHS;
5534 if (ResQT == RHSBaseQT)
5535 return RHS;
5536 }
5537 return QualType();
5538}
5539
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005540//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005541// Integer Predicates
5542//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005543
Jay Foad39c79802011-01-12 09:06:06 +00005544unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005545 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005546 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005547 if (T->isBooleanType())
5548 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005549 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005550 return (unsigned)getTypeSize(T);
5551}
5552
5553QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005554 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005555
5556 // Turn <4 x signed int> -> <4 x unsigned int>
5557 if (const VectorType *VTy = T->getAs<VectorType>())
5558 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005559 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005560
5561 // For enums, we return the unsigned version of the base type.
5562 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005563 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005564
5565 const BuiltinType *BTy = T->getAs<BuiltinType>();
5566 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005567 switch (BTy->getKind()) {
5568 case BuiltinType::Char_S:
5569 case BuiltinType::SChar:
5570 return UnsignedCharTy;
5571 case BuiltinType::Short:
5572 return UnsignedShortTy;
5573 case BuiltinType::Int:
5574 return UnsignedIntTy;
5575 case BuiltinType::Long:
5576 return UnsignedLongTy;
5577 case BuiltinType::LongLong:
5578 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005579 case BuiltinType::Int128:
5580 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005581 default:
5582 assert(0 && "Unexpected signed integer type");
5583 return QualType();
5584 }
5585}
5586
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005587ASTMutationListener::~ASTMutationListener() { }
5588
Chris Lattnerecd79c62009-06-14 00:45:47 +00005589
5590//===----------------------------------------------------------------------===//
5591// Builtin Type Computation
5592//===----------------------------------------------------------------------===//
5593
5594/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005595/// pointer over the consumed characters. This returns the resultant type. If
5596/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5597/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5598/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005599///
5600/// RequiresICE is filled in on return to indicate whether the value is required
5601/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005602static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005603 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005604 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005605 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005606 // Modifiers.
5607 int HowLong = 0;
5608 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005609 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005610
Chris Lattnerdc226c22010-10-01 22:42:38 +00005611 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005612 bool Done = false;
5613 while (!Done) {
5614 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005615 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005616 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005617 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005618 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005619 case 'S':
5620 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5621 assert(!Signed && "Can't use 'S' modifier multiple times!");
5622 Signed = true;
5623 break;
5624 case 'U':
5625 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5626 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5627 Unsigned = true;
5628 break;
5629 case 'L':
5630 assert(HowLong <= 2 && "Can't have LLLL modifier");
5631 ++HowLong;
5632 break;
5633 }
5634 }
5635
5636 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005637
Chris Lattnerecd79c62009-06-14 00:45:47 +00005638 // Read the base type.
5639 switch (*Str++) {
5640 default: assert(0 && "Unknown builtin type letter!");
5641 case 'v':
5642 assert(HowLong == 0 && !Signed && !Unsigned &&
5643 "Bad modifiers used with 'v'!");
5644 Type = Context.VoidTy;
5645 break;
5646 case 'f':
5647 assert(HowLong == 0 && !Signed && !Unsigned &&
5648 "Bad modifiers used with 'f'!");
5649 Type = Context.FloatTy;
5650 break;
5651 case 'd':
5652 assert(HowLong < 2 && !Signed && !Unsigned &&
5653 "Bad modifiers used with 'd'!");
5654 if (HowLong)
5655 Type = Context.LongDoubleTy;
5656 else
5657 Type = Context.DoubleTy;
5658 break;
5659 case 's':
5660 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5661 if (Unsigned)
5662 Type = Context.UnsignedShortTy;
5663 else
5664 Type = Context.ShortTy;
5665 break;
5666 case 'i':
5667 if (HowLong == 3)
5668 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5669 else if (HowLong == 2)
5670 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5671 else if (HowLong == 1)
5672 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5673 else
5674 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5675 break;
5676 case 'c':
5677 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5678 if (Signed)
5679 Type = Context.SignedCharTy;
5680 else if (Unsigned)
5681 Type = Context.UnsignedCharTy;
5682 else
5683 Type = Context.CharTy;
5684 break;
5685 case 'b': // boolean
5686 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5687 Type = Context.BoolTy;
5688 break;
5689 case 'z': // size_t.
5690 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5691 Type = Context.getSizeType();
5692 break;
5693 case 'F':
5694 Type = Context.getCFConstantStringType();
5695 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005696 case 'G':
5697 Type = Context.getObjCIdType();
5698 break;
5699 case 'H':
5700 Type = Context.getObjCSelType();
5701 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005702 case 'a':
5703 Type = Context.getBuiltinVaListType();
5704 assert(!Type.isNull() && "builtin va list type not initialized!");
5705 break;
5706 case 'A':
5707 // This is a "reference" to a va_list; however, what exactly
5708 // this means depends on how va_list is defined. There are two
5709 // different kinds of va_list: ones passed by value, and ones
5710 // passed by reference. An example of a by-value va_list is
5711 // x86, where va_list is a char*. An example of by-ref va_list
5712 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5713 // we want this argument to be a char*&; for x86-64, we want
5714 // it to be a __va_list_tag*.
5715 Type = Context.getBuiltinVaListType();
5716 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005717 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005718 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005719 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005720 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005721 break;
5722 case 'V': {
5723 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005724 unsigned NumElements = strtoul(Str, &End, 10);
5725 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005726 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005727
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005728 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5729 RequiresICE, false);
5730 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005731
5732 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005733 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005734 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005735 break;
5736 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005737 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005738 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5739 false);
5740 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005741 Type = Context.getComplexType(ElementType);
5742 break;
5743 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005744 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005745 Type = Context.getFILEType();
5746 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005747 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005748 return QualType();
5749 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005750 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005751 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005752 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005753 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005754 else
5755 Type = Context.getjmp_bufType();
5756
Mike Stump2adb4da2009-07-28 23:47:15 +00005757 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005758 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005759 return QualType();
5760 }
5761 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005762 }
Mike Stump11289f42009-09-09 15:08:12 +00005763
Chris Lattnerdc226c22010-10-01 22:42:38 +00005764 // If there are modifiers and if we're allowed to parse them, go for it.
5765 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005766 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005767 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005768 default: Done = true; --Str; break;
5769 case '*':
5770 case '&': {
5771 // Both pointers and references can have their pointee types
5772 // qualified with an address space.
5773 char *End;
5774 unsigned AddrSpace = strtoul(Str, &End, 10);
5775 if (End != Str && AddrSpace != 0) {
5776 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5777 Str = End;
5778 }
5779 if (c == '*')
5780 Type = Context.getPointerType(Type);
5781 else
5782 Type = Context.getLValueReferenceType(Type);
5783 break;
5784 }
5785 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5786 case 'C':
5787 Type = Type.withConst();
5788 break;
5789 case 'D':
5790 Type = Context.getVolatileType(Type);
5791 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005792 }
5793 }
Chris Lattner84733392010-10-01 07:13:18 +00005794
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005795 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005796 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005797
Chris Lattnerecd79c62009-06-14 00:45:47 +00005798 return Type;
5799}
5800
5801/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005802QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005803 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005804 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005805 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005806
Chris Lattnerecd79c62009-06-14 00:45:47 +00005807 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005808
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005809 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005810 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005811 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5812 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005813 if (Error != GE_None)
5814 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005815
5816 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5817
Chris Lattnerecd79c62009-06-14 00:45:47 +00005818 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005819 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005820 if (Error != GE_None)
5821 return QualType();
5822
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005823 // If this argument is required to be an IntegerConstantExpression and the
5824 // caller cares, fill in the bitmask we return.
5825 if (RequiresICE && IntegerConstantArgs)
5826 *IntegerConstantArgs |= 1 << ArgTypes.size();
5827
Chris Lattnerecd79c62009-06-14 00:45:47 +00005828 // Do array -> pointer decay. The builtin should use the decayed type.
5829 if (Ty->isArrayType())
5830 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005831
Chris Lattnerecd79c62009-06-14 00:45:47 +00005832 ArgTypes.push_back(Ty);
5833 }
5834
5835 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5836 "'.' should only occur at end of builtin type list!");
5837
John McCall991eb4b2010-12-21 00:44:39 +00005838 FunctionType::ExtInfo EI;
5839 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5840
5841 bool Variadic = (TypeStr[0] == '.');
5842
5843 // We really shouldn't be making a no-proto type here, especially in C++.
5844 if (ArgTypes.empty() && Variadic)
5845 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005846
John McCalldb40c7f2010-12-14 08:05:40 +00005847 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005848 EPI.ExtInfo = EI;
5849 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00005850
5851 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005852}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005853
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005854GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5855 GVALinkage External = GVA_StrongExternal;
5856
5857 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005858 switch (L) {
5859 case NoLinkage:
5860 case InternalLinkage:
5861 case UniqueExternalLinkage:
5862 return GVA_Internal;
5863
5864 case ExternalLinkage:
5865 switch (FD->getTemplateSpecializationKind()) {
5866 case TSK_Undeclared:
5867 case TSK_ExplicitSpecialization:
5868 External = GVA_StrongExternal;
5869 break;
5870
5871 case TSK_ExplicitInstantiationDefinition:
5872 return GVA_ExplicitTemplateInstantiation;
5873
5874 case TSK_ExplicitInstantiationDeclaration:
5875 case TSK_ImplicitInstantiation:
5876 External = GVA_TemplateInstantiation;
5877 break;
5878 }
5879 }
5880
5881 if (!FD->isInlined())
5882 return External;
5883
5884 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5885 // GNU or C99 inline semantics. Determine whether this symbol should be
5886 // externally visible.
5887 if (FD->isInlineDefinitionExternallyVisible())
5888 return External;
5889
5890 // C99 inline semantics, where the symbol is not externally visible.
5891 return GVA_C99Inline;
5892 }
5893
5894 // C++0x [temp.explicit]p9:
5895 // [ Note: The intent is that an inline function that is the subject of
5896 // an explicit instantiation declaration will still be implicitly
5897 // instantiated when used so that the body can be considered for
5898 // inlining, but that no out-of-line copy of the inline function would be
5899 // generated in the translation unit. -- end note ]
5900 if (FD->getTemplateSpecializationKind()
5901 == TSK_ExplicitInstantiationDeclaration)
5902 return GVA_C99Inline;
5903
5904 return GVA_CXXInline;
5905}
5906
5907GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5908 // If this is a static data member, compute the kind of template
5909 // specialization. Otherwise, this variable is not part of a
5910 // template.
5911 TemplateSpecializationKind TSK = TSK_Undeclared;
5912 if (VD->isStaticDataMember())
5913 TSK = VD->getTemplateSpecializationKind();
5914
5915 Linkage L = VD->getLinkage();
5916 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5917 VD->getType()->getLinkage() == UniqueExternalLinkage)
5918 L = UniqueExternalLinkage;
5919
5920 switch (L) {
5921 case NoLinkage:
5922 case InternalLinkage:
5923 case UniqueExternalLinkage:
5924 return GVA_Internal;
5925
5926 case ExternalLinkage:
5927 switch (TSK) {
5928 case TSK_Undeclared:
5929 case TSK_ExplicitSpecialization:
5930 return GVA_StrongExternal;
5931
5932 case TSK_ExplicitInstantiationDeclaration:
5933 llvm_unreachable("Variable should not be instantiated");
5934 // Fall through to treat this like any other instantiation.
5935
5936 case TSK_ExplicitInstantiationDefinition:
5937 return GVA_ExplicitTemplateInstantiation;
5938
5939 case TSK_ImplicitInstantiation:
5940 return GVA_TemplateInstantiation;
5941 }
5942 }
5943
5944 return GVA_StrongExternal;
5945}
5946
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005947bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005948 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5949 if (!VD->isFileVarDecl())
5950 return false;
5951 } else if (!isa<FunctionDecl>(D))
5952 return false;
5953
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005954 // Weak references don't produce any output by themselves.
5955 if (D->hasAttr<WeakRefAttr>())
5956 return false;
5957
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005958 // Aliases and used decls are required.
5959 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5960 return true;
5961
5962 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5963 // Forward declarations aren't required.
5964 if (!FD->isThisDeclarationADefinition())
5965 return false;
5966
5967 // Constructors and destructors are required.
5968 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5969 return true;
5970
5971 // The key function for a class is required.
5972 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5973 const CXXRecordDecl *RD = MD->getParent();
5974 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5975 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5976 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5977 return true;
5978 }
5979 }
5980
5981 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5982
5983 // static, static inline, always_inline, and extern inline functions can
5984 // always be deferred. Normal inline functions can be deferred in C99/C++.
5985 // Implicit template instantiations can also be deferred in C++.
5986 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5987 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5988 return false;
5989 return true;
5990 }
5991
5992 const VarDecl *VD = cast<VarDecl>(D);
5993 assert(VD->isFileVarDecl() && "Expected file scoped var");
5994
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005995 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5996 return false;
5997
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005998 // Structs that have non-trivial constructors or destructors are required.
5999
6000 // FIXME: Handle references.
6001 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6002 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006003 if (RD->hasDefinition() &&
6004 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006005 return true;
6006 }
6007 }
6008
6009 GVALinkage L = GetGVALinkageForVariable(VD);
6010 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6011 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6012 return false;
6013 }
6014
6015 return true;
6016}
Charles Davis53c59df2010-08-16 03:33:14 +00006017
Charles Davis99202b32010-11-09 18:04:24 +00006018CallingConv ASTContext::getDefaultMethodCallConv() {
6019 // Pass through to the C++ ABI object
6020 return ABI->getDefaultMethodCallConv();
6021}
6022
Jay Foad39c79802011-01-12 09:06:06 +00006023bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006024 // Pass through to the C++ ABI object
6025 return ABI->isNearlyEmpty(RD);
6026}
6027
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006028MangleContext *ASTContext::createMangleContext() {
6029 switch (Target.getCXXABI()) {
6030 case CXXABI_ARM:
6031 case CXXABI_Itanium:
6032 return createItaniumMangleContext(*this, getDiagnostics());
6033 case CXXABI_Microsoft:
6034 return createMicrosoftMangleContext(*this, getDiagnostics());
6035 }
6036 assert(0 && "Unsupported ABI");
6037 return 0;
6038}
6039
Charles Davis53c59df2010-08-16 03:33:14 +00006040CXXABI::~CXXABI() {}