blob: 674356245faf091f16e9a7b1ab173ed03a675485 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Charles Davis53c59df2010-08-16 03:33:14 +000033#include "CXXABI.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000034
Chris Lattnerddc135e2006-11-10 06:34:16 +000035using namespace clang;
36
Douglas Gregor9672f922010-07-03 00:47:00 +000037unsigned ASTContext::NumImplicitDefaultConstructors;
38unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000039unsigned ASTContext::NumImplicitCopyConstructors;
40unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000041unsigned ASTContext::NumImplicitCopyAssignmentOperators;
42unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000043unsigned ASTContext::NumImplicitDestructors;
44unsigned ASTContext::NumImplicitDestructorsDeclared;
45
Steve Naroff0af91202007-04-27 21:51:21 +000046enum FloatingRank {
47 FloatRank, DoubleRank, LongDoubleRank
48};
49
Douglas Gregor7dbfb462010-06-16 21:09:37 +000050void
51ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
52 TemplateTemplateParmDecl *Parm) {
53 ID.AddInteger(Parm->getDepth());
54 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000055 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000056
57 TemplateParameterList *Params = Parm->getTemplateParameters();
58 ID.AddInteger(Params->size());
59 for (TemplateParameterList::const_iterator P = Params->begin(),
60 PEnd = Params->end();
61 P != PEnd; ++P) {
62 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
63 ID.AddInteger(0);
64 ID.AddBoolean(TTP->isParameterPack());
65 continue;
66 }
67
68 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
69 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000070 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000071 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +000072 if (NTTP->isExpandedParameterPack()) {
73 ID.AddBoolean(true);
74 ID.AddInteger(NTTP->getNumExpansionTypes());
75 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
76 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
77 } else
78 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +000079 continue;
80 }
81
82 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
83 ID.AddInteger(2);
84 Profile(ID, TTP);
85 }
86}
87
88TemplateTemplateParmDecl *
89ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000090 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000091 // Check if we already have a canonical template template parameter.
92 llvm::FoldingSetNodeID ID;
93 CanonicalTemplateTemplateParm::Profile(ID, TTP);
94 void *InsertPos = 0;
95 CanonicalTemplateTemplateParm *Canonical
96 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
97 if (Canonical)
98 return Canonical->getParam();
99
100 // Build a canonical template parameter list.
101 TemplateParameterList *Params = TTP->getTemplateParameters();
102 llvm::SmallVector<NamedDecl *, 4> CanonParams;
103 CanonParams.reserve(Params->size());
104 for (TemplateParameterList::const_iterator P = Params->begin(),
105 PEnd = Params->end();
106 P != PEnd; ++P) {
107 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
108 CanonParams.push_back(
109 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000110 SourceLocation(),
111 SourceLocation(),
112 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000113 TTP->getIndex(), 0, false,
114 TTP->isParameterPack()));
115 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000116 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
117 QualType T = getCanonicalType(NTTP->getType());
118 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
119 NonTypeTemplateParmDecl *Param;
120 if (NTTP->isExpandedParameterPack()) {
121 llvm::SmallVector<QualType, 2> ExpandedTypes;
122 llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
123 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
124 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
125 ExpandedTInfos.push_back(
126 getTrivialTypeSourceInfo(ExpandedTypes.back()));
127 }
128
129 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000130 SourceLocation(),
131 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000132 NTTP->getDepth(),
133 NTTP->getPosition(), 0,
134 T,
135 TInfo,
136 ExpandedTypes.data(),
137 ExpandedTypes.size(),
138 ExpandedTInfos.data());
139 } else {
140 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000141 SourceLocation(),
142 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000143 NTTP->getDepth(),
144 NTTP->getPosition(), 0,
145 T,
146 NTTP->isParameterPack(),
147 TInfo);
148 }
149 CanonParams.push_back(Param);
150
151 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000152 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
153 cast<TemplateTemplateParmDecl>(*P)));
154 }
155
156 TemplateTemplateParmDecl *CanonTTP
157 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
158 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000159 TTP->getPosition(),
160 TTP->isParameterPack(),
161 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000162 TemplateParameterList::Create(*this, SourceLocation(),
163 SourceLocation(),
164 CanonParams.data(),
165 CanonParams.size(),
166 SourceLocation()));
167
168 // Get the new insert position for the node we care about.
169 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
170 assert(Canonical == 0 && "Shouldn't be in the map!");
171 (void)Canonical;
172
173 // Create the canonical template template parameter entry.
174 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
175 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
176 return CanonTTP;
177}
178
Charles Davis53c59df2010-08-16 03:33:14 +0000179CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000180 if (!LangOpts.CPlusPlus) return 0;
181
Charles Davis6bcb07a2010-08-19 02:18:14 +0000182 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000183 case CXXABI_ARM:
184 return CreateARMCXXABI(*this);
185 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000186 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000187 case CXXABI_Microsoft:
188 return CreateMicrosoftCXXABI(*this);
189 }
John McCall86353412010-08-21 22:46:04 +0000190 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000191}
192
Chris Lattner465fa322008-10-05 17:34:18 +0000193ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000194 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000195 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000196 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000197 unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000198 TemplateSpecializationTypes(this_()),
199 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000200 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
201 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000202 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000203 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +0000204 cudaConfigureCallDecl(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000205 NullTypeSourceInfo(QualType()),
Charles Davis53c59df2010-08-16 03:33:14 +0000206 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000207 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000208 BuiltinInfo(builtins),
209 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000210 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000211 LastSDM(0, 0),
John McCall147d0212011-02-22 22:38:33 +0000212 UniqueBlockByRefTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000213 ObjCIdRedefinitionType = QualType();
214 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000215 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000216 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000217 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000218 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000219}
220
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000221ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000222 // Release the DenseMaps associated with DeclContext objects.
223 // FIXME: Is this the ideal solution?
224 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000225
Douglas Gregor5b11d492010-07-25 17:53:33 +0000226 // Call all of the deallocation functions.
227 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
228 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000229
Douglas Gregor832940b2010-03-02 23:58:15 +0000230 // Release all of the memory associated with overridden C++ methods.
231 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
232 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
233 OM != OMEnd; ++OM)
234 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000235
Ted Kremenek076baeb2010-06-08 23:00:58 +0000236 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000237 // because they can contain DenseMaps.
238 for (llvm::DenseMap<const ObjCContainerDecl*,
239 const ASTRecordLayout*>::iterator
240 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
241 // Increment in loop to prevent using deallocated memory.
242 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
243 R->Destroy(*this);
244
Ted Kremenek076baeb2010-06-08 23:00:58 +0000245 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
246 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
247 // Increment in loop to prevent using deallocated memory.
248 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
249 R->Destroy(*this);
250 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000251
252 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
253 AEnd = DeclAttrs.end();
254 A != AEnd; ++A)
255 A->second->~AttrVec();
256}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000257
Douglas Gregor1a809332010-05-23 18:26:36 +0000258void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
259 Deallocations.push_back(std::make_pair(Callback, Data));
260}
261
Mike Stump11289f42009-09-09 15:08:12 +0000262void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000263ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
264 ExternalSource.reset(Source.take());
265}
266
Chris Lattner4eb445d2007-01-26 01:27:23 +0000267void ASTContext::PrintStats() const {
268 fprintf(stderr, "*** AST Context Stats:\n");
269 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000270
Douglas Gregora30d0462009-05-26 14:40:08 +0000271 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000272#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000273#define ABSTRACT_TYPE(Name, Parent)
274#include "clang/AST/TypeNodes.def"
275 0 // Extra
276 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000277
Chris Lattner4eb445d2007-01-26 01:27:23 +0000278 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
279 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000280 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000281 }
282
Douglas Gregora30d0462009-05-26 14:40:08 +0000283 unsigned Idx = 0;
284 unsigned TotalBytes = 0;
285#define TYPE(Name, Parent) \
286 if (counts[Idx]) \
287 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
288 TotalBytes += counts[Idx] * sizeof(Name##Type); \
289 ++Idx;
290#define ABSTRACT_TYPE(Name, Parent)
291#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000292
Douglas Gregora30d0462009-05-26 14:40:08 +0000293 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000294
Douglas Gregor7454c562010-07-02 20:37:36 +0000295 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000296 fprintf(stderr, " %u/%u implicit default constructors created\n",
297 NumImplicitDefaultConstructorsDeclared,
298 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000299 fprintf(stderr, " %u/%u implicit copy constructors created\n",
300 NumImplicitCopyConstructorsDeclared,
301 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000302 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
303 NumImplicitCopyAssignmentOperatorsDeclared,
304 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000305 fprintf(stderr, " %u/%u implicit destructors created\n",
306 NumImplicitDestructorsDeclared, NumImplicitDestructors);
307
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000308 if (ExternalSource.get()) {
309 fprintf(stderr, "\n");
310 ExternalSource->PrintStats();
311 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000312
Douglas Gregor5b11d492010-07-25 17:53:33 +0000313 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000314}
315
316
John McCall48f2d582009-10-23 23:03:21 +0000317void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000318 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000319 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000320 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000321}
322
Chris Lattner970e54e2006-11-12 00:37:36 +0000323void ASTContext::InitBuiltinTypes() {
324 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000325
Chris Lattner970e54e2006-11-12 00:37:36 +0000326 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000327 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000328
Chris Lattner970e54e2006-11-12 00:37:36 +0000329 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000330 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000331 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000332 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000333 InitBuiltinType(CharTy, BuiltinType::Char_S);
334 else
335 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000336 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000337 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
338 InitBuiltinType(ShortTy, BuiltinType::Short);
339 InitBuiltinType(IntTy, BuiltinType::Int);
340 InitBuiltinType(LongTy, BuiltinType::Long);
341 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000342
Chris Lattner970e54e2006-11-12 00:37:36 +0000343 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000344 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
345 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
346 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
347 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
348 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000349
Chris Lattner970e54e2006-11-12 00:37:36 +0000350 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000351 InitBuiltinType(FloatTy, BuiltinType::Float);
352 InitBuiltinType(DoubleTy, BuiltinType::Double);
353 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000354
Chris Lattnerf122cef2009-04-30 02:43:43 +0000355 // GNU extension, 128-bit integers.
356 InitBuiltinType(Int128Ty, BuiltinType::Int128);
357 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
358
Chris Lattnerad3467e2010-12-25 23:25:43 +0000359 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
360 if (!LangOpts.ShortWChar)
361 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
362 else // -fshort-wchar makes wchar_t be unsigned.
363 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
364 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000365 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000366
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000367 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
368 InitBuiltinType(Char16Ty, BuiltinType::Char16);
369 else // C99
370 Char16Ty = getFromTargetType(Target.getChar16Type());
371
372 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
373 InitBuiltinType(Char32Ty, BuiltinType::Char32);
374 else // C99
375 Char32Ty = getFromTargetType(Target.getChar32Type());
376
Douglas Gregor4619e432008-12-05 23:32:09 +0000377 // Placeholder type for type-dependent expressions whose type is
378 // completely unknown. No code should ever check a type against
379 // DependentTy and users should never see it; however, it is here to
380 // help diagnose failures to properly check for type-dependent
381 // expressions.
382 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000383
John McCall36e7fe32010-10-12 00:20:44 +0000384 // Placeholder type for functions.
385 InitBuiltinType(OverloadTy, BuiltinType::Overload);
386
Chris Lattner970e54e2006-11-12 00:37:36 +0000387 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000388 FloatComplexTy = getComplexType(FloatTy);
389 DoubleComplexTy = getComplexType(DoubleTy);
390 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000391
Steve Naroff66e9f332007-10-15 14:41:52 +0000392 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000393
Steve Naroff1329fa02009-07-15 18:40:39 +0000394 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
395 ObjCIdTypedefType = QualType();
396 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000397 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000398
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000399 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000400 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
401 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000402 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000403
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000404 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000405
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000406 // void * type
407 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000408
409 // nullptr type (C++0x 2.14.7)
410 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000411}
412
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000413Diagnostic &ASTContext::getDiagnostics() const {
414 return SourceMgr.getDiagnostics();
415}
416
Douglas Gregor561eceb2010-08-30 16:49:28 +0000417AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
418 AttrVec *&Result = DeclAttrs[D];
419 if (!Result) {
420 void *Mem = Allocate(sizeof(AttrVec));
421 Result = new (Mem) AttrVec;
422 }
423
424 return *Result;
425}
426
427/// \brief Erase the attributes corresponding to the given declaration.
428void ASTContext::eraseDeclAttrs(const Decl *D) {
429 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
430 if (Pos != DeclAttrs.end()) {
431 Pos->second->~AttrVec();
432 DeclAttrs.erase(Pos);
433 }
434}
435
436
Douglas Gregor86d142a2009-10-08 07:24:58 +0000437MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000438ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000439 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000440 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000441 = InstantiatedFromStaticDataMember.find(Var);
442 if (Pos == InstantiatedFromStaticDataMember.end())
443 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000444
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000445 return Pos->second;
446}
447
Mike Stump11289f42009-09-09 15:08:12 +0000448void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000449ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000450 TemplateSpecializationKind TSK,
451 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000452 assert(Inst->isStaticDataMember() && "Not a static data member");
453 assert(Tmpl->isStaticDataMember() && "Not a static data member");
454 assert(!InstantiatedFromStaticDataMember[Inst] &&
455 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000456 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000457 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000458}
459
John McCalle61f2ba2009-11-18 02:36:19 +0000460NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000461ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000462 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000463 = InstantiatedFromUsingDecl.find(UUD);
464 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000465 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000466
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000467 return Pos->second;
468}
469
470void
John McCallb96ec562009-12-04 22:46:56 +0000471ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
472 assert((isa<UsingDecl>(Pattern) ||
473 isa<UnresolvedUsingValueDecl>(Pattern) ||
474 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
475 "pattern decl is not a using decl");
476 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
477 InstantiatedFromUsingDecl[Inst] = Pattern;
478}
479
480UsingShadowDecl *
481ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
482 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
483 = InstantiatedFromUsingShadowDecl.find(Inst);
484 if (Pos == InstantiatedFromUsingShadowDecl.end())
485 return 0;
486
487 return Pos->second;
488}
489
490void
491ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
492 UsingShadowDecl *Pattern) {
493 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
494 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000495}
496
Anders Carlsson5da84842009-09-01 04:26:58 +0000497FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
498 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
499 = InstantiatedFromUnnamedFieldDecl.find(Field);
500 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
501 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000502
Anders Carlsson5da84842009-09-01 04:26:58 +0000503 return Pos->second;
504}
505
506void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
507 FieldDecl *Tmpl) {
508 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
509 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
510 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
511 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000512
Anders Carlsson5da84842009-09-01 04:26:58 +0000513 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
514}
515
Douglas Gregor832940b2010-03-02 23:58:15 +0000516ASTContext::overridden_cxx_method_iterator
517ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
518 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
519 = OverriddenMethods.find(Method);
520 if (Pos == OverriddenMethods.end())
521 return 0;
522
523 return Pos->second.begin();
524}
525
526ASTContext::overridden_cxx_method_iterator
527ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
528 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
529 = OverriddenMethods.find(Method);
530 if (Pos == OverriddenMethods.end())
531 return 0;
532
533 return Pos->second.end();
534}
535
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000536unsigned
537ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
538 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
539 = OverriddenMethods.find(Method);
540 if (Pos == OverriddenMethods.end())
541 return 0;
542
543 return Pos->second.size();
544}
545
Douglas Gregor832940b2010-03-02 23:58:15 +0000546void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
547 const CXXMethodDecl *Overridden) {
548 OverriddenMethods[Method].push_back(Overridden);
549}
550
Chris Lattner53cfe802007-07-18 17:52:12 +0000551//===----------------------------------------------------------------------===//
552// Type Sizing and Analysis
553//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000554
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000555/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
556/// scalar floating point type.
557const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000558 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000559 assert(BT && "Not a floating point type!");
560 switch (BT->getKind()) {
561 default: assert(0 && "Not a floating point type!");
562 case BuiltinType::Float: return Target.getFloatFormat();
563 case BuiltinType::Double: return Target.getDoubleFormat();
564 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
565 }
566}
567
Ken Dyck160146e2010-01-27 17:10:57 +0000568/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000569/// specified decl. Note that bitfields do not have a valid alignment, so
570/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000571/// If @p RefAsPointee, references are treated like their underlying type
572/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000573CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000574 unsigned Align = Target.getCharWidth();
575
John McCall94268702010-10-08 18:24:19 +0000576 bool UseAlignAttrOnly = false;
577 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
578 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000579
John McCall94268702010-10-08 18:24:19 +0000580 // __attribute__((aligned)) can increase or decrease alignment
581 // *except* on a struct or struct member, where it only increases
582 // alignment unless 'packed' is also specified.
583 //
584 // It is an error for [[align]] to decrease alignment, so we can
585 // ignore that possibility; Sema should diagnose it.
586 if (isa<FieldDecl>(D)) {
587 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
588 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
589 } else {
590 UseAlignAttrOnly = true;
591 }
592 }
593
John McCall4e819612011-01-20 07:57:12 +0000594 // If we're using the align attribute only, just ignore everything
595 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000596 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000597 // do nothing
598
John McCall94268702010-10-08 18:24:19 +0000599 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000600 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000601 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000602 if (RefAsPointee)
603 T = RT->getPointeeType();
604 else
605 T = getPointerType(RT->getPointeeType());
606 }
607 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000608 // Adjust alignments of declarations with array type by the
609 // large-array alignment on the target.
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000610 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000611 const ArrayType *arrayType;
612 if (MinWidth && (arrayType = getAsArrayType(T))) {
613 if (isa<VariableArrayType>(arrayType))
614 Align = std::max(Align, Target.getLargeArrayAlign());
615 else if (isa<ConstantArrayType>(arrayType) &&
616 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
617 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000618
John McCall33ddac02011-01-19 10:06:00 +0000619 // Walk through any array types while we're at it.
620 T = getBaseElementType(arrayType);
621 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000622 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
623 }
John McCall4e819612011-01-20 07:57:12 +0000624
625 // Fields can be subject to extra alignment constraints, like if
626 // the field is packed, the struct is packed, or the struct has a
627 // a max-field-alignment constraint (#pragma pack). So calculate
628 // the actual alignment of the field within the struct, and then
629 // (as we're expected to) constrain that by the alignment of the type.
630 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
631 // So calculate the alignment of the field.
632 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
633
634 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000635 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000636
637 // Use the GCD of that and the offset within the record.
638 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
639 if (offset > 0) {
640 // Alignment is always a power of 2, so the GCD will be a power of 2,
641 // which means we get to do this crazy thing instead of Euclid's.
642 uint64_t lowBitOfOffset = offset & (~offset + 1);
643 if (lowBitOfOffset < fieldAlign)
644 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
645 }
646
647 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000648 }
Chris Lattner68061312009-01-24 21:53:27 +0000649 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000650
Ken Dyckcc56c542011-01-15 18:38:59 +0000651 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000652}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000653
John McCall87fe5d52010-05-20 01:18:31 +0000654std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000655ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000656 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000657 return std::make_pair(toCharUnitsFromBits(Info.first),
658 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000659}
660
661std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000662ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000663 return getTypeInfoInChars(T.getTypePtr());
664}
665
Chris Lattner983a8bb2007-07-13 22:13:22 +0000666/// getTypeSize - Return the size of the specified type, in bits. This method
667/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000668///
669/// FIXME: Pointers into different addr spaces could have different sizes and
670/// alignment requirements: getPointerInfo should take an AddrSpace, this
671/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000672std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000673ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000674 uint64_t Width=0;
675 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000676 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000677#define TYPE(Class, Base)
678#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000679#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000680#define DEPENDENT_TYPE(Class, Base) case Type::Class:
681#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000682 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000683 break;
684
Chris Lattner355332d2007-07-13 22:27:08 +0000685 case Type::FunctionNoProto:
686 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000687 // GCC extension: alignof(function) = 32 bits
688 Width = 0;
689 Align = 32;
690 break;
691
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000692 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000693 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000694 Width = 0;
695 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
696 break;
697
Steve Naroff5c131802007-08-30 01:06:46 +0000698 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000699 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000700
Chris Lattner37e05872008-03-05 18:54:05 +0000701 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000702 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000703 Align = EltInfo.second;
704 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000705 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000706 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000707 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000708 const VectorType *VT = cast<VectorType>(T);
709 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
710 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000711 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000712 // If the alignment is not a power of 2, round up to the next power of 2.
713 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000714 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000715 Align = llvm::NextPowerOf2(Align);
716 Width = llvm::RoundUpToAlignment(Width, Align);
717 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000718 break;
719 }
Chris Lattner647fb222007-07-18 18:26:58 +0000720
Chris Lattner7570e9c2008-03-08 08:52:55 +0000721 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000722 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000723 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000724 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000725 // GCC extension: alignof(void) = 8 bits.
726 Width = 0;
727 Align = 8;
728 break;
729
Chris Lattner6a4f7452007-12-19 19:23:28 +0000730 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000731 Width = Target.getBoolWidth();
732 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000733 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000734 case BuiltinType::Char_S:
735 case BuiltinType::Char_U:
736 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000737 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000738 Width = Target.getCharWidth();
739 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000740 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000741 case BuiltinType::WChar_S:
742 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000743 Width = Target.getWCharWidth();
744 Align = Target.getWCharAlign();
745 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000746 case BuiltinType::Char16:
747 Width = Target.getChar16Width();
748 Align = Target.getChar16Align();
749 break;
750 case BuiltinType::Char32:
751 Width = Target.getChar32Width();
752 Align = Target.getChar32Align();
753 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000754 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000755 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000756 Width = Target.getShortWidth();
757 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000758 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000759 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000760 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000761 Width = Target.getIntWidth();
762 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000763 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000764 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000765 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000766 Width = Target.getLongWidth();
767 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000768 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000769 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000770 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000771 Width = Target.getLongLongWidth();
772 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000773 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000774 case BuiltinType::Int128:
775 case BuiltinType::UInt128:
776 Width = 128;
777 Align = 128; // int128_t is 128-bit aligned on all targets.
778 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000779 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000780 Width = Target.getFloatWidth();
781 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000782 break;
783 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000784 Width = Target.getDoubleWidth();
785 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000786 break;
787 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000788 Width = Target.getLongDoubleWidth();
789 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000790 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000791 case BuiltinType::NullPtr:
792 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
793 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000794 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000795 case BuiltinType::ObjCId:
796 case BuiltinType::ObjCClass:
797 case BuiltinType::ObjCSel:
798 Width = Target.getPointerWidth(0);
799 Align = Target.getPointerAlign(0);
800 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000801 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000802 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000803 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000804 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000805 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000806 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000807 case Type::BlockPointer: {
808 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
809 Width = Target.getPointerWidth(AS);
810 Align = Target.getPointerAlign(AS);
811 break;
812 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000813 case Type::LValueReference:
814 case Type::RValueReference: {
815 // alignof and sizeof should never enter this code path here, so we go
816 // the pointer route.
817 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
818 Width = Target.getPointerWidth(AS);
819 Align = Target.getPointerAlign(AS);
820 break;
821 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000822 case Type::Pointer: {
823 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000824 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000825 Align = Target.getPointerAlign(AS);
826 break;
827 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000828 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000829 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000830 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000831 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000832 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000833 Align = PtrDiffInfo.second;
834 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000835 }
Chris Lattner647fb222007-07-18 18:26:58 +0000836 case Type::Complex: {
837 // Complex types have the same alignment as their elements, but twice the
838 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000839 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000840 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000841 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000842 Align = EltInfo.second;
843 break;
844 }
John McCall8b07ec22010-05-15 11:32:37 +0000845 case Type::ObjCObject:
846 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000847 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000848 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000849 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000850 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000851 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000852 break;
853 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000854 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000855 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000856 const TagType *TT = cast<TagType>(T);
857
858 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000859 Width = 1;
860 Align = 1;
861 break;
862 }
Mike Stump11289f42009-09-09 15:08:12 +0000863
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000864 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000865 return getTypeInfo(ET->getDecl()->getIntegerType());
866
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000867 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000868 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000869 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000870 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +0000871 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000872 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000873
Chris Lattner63d2b362009-10-22 05:17:15 +0000874 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000875 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
876 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000877
Richard Smith30482bc2011-02-20 03:19:35 +0000878 case Type::Auto: {
879 const AutoType *A = cast<AutoType>(T);
880 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +0000881 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +0000882 }
883
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000884 case Type::Paren:
885 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
886
Douglas Gregoref462e62009-04-30 17:32:17 +0000887 case Type::Typedef: {
888 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000889 std::pair<uint64_t, unsigned> Info
890 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +0000891 // If the typedef has an aligned attribute on it, it overrides any computed
892 // alignment we have. This violates the GCC documentation (which says that
893 // attribute(aligned) can only round up) but matches its implementation.
894 if (unsigned AttrAlign = Typedef->getMaxAlignment())
895 Align = AttrAlign;
896 else
897 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +0000898 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000899 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000900 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000901
902 case Type::TypeOfExpr:
903 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
904 .getTypePtr());
905
906 case Type::TypeOf:
907 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
908
Anders Carlsson81df7b82009-06-24 19:06:50 +0000909 case Type::Decltype:
910 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
911 .getTypePtr());
912
Abramo Bagnara6150c882010-05-11 21:36:43 +0000913 case Type::Elaborated:
914 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000915
John McCall81904512011-01-06 01:58:22 +0000916 case Type::Attributed:
917 return getTypeInfo(
918 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
919
Douglas Gregoref462e62009-04-30 17:32:17 +0000920 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000921 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000922 "Cannot request the size of a dependent type");
923 // FIXME: this is likely to be wrong once we support template
924 // aliases, since a template alias could refer to a typedef that
925 // has an __aligned__ attribute on it.
926 return getTypeInfo(getCanonicalType(T));
927 }
Mike Stump11289f42009-09-09 15:08:12 +0000928
Chris Lattner53cfe802007-07-18 17:52:12 +0000929 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000930 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000931}
932
Ken Dyckcc56c542011-01-15 18:38:59 +0000933/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
934CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
935 return CharUnits::fromQuantity(BitSize / getCharWidth());
936}
937
Ken Dyckb0fcc592011-02-11 01:54:29 +0000938/// toBits - Convert a size in characters to a size in characters.
939int64_t ASTContext::toBits(CharUnits CharSize) const {
940 return CharSize.getQuantity() * getCharWidth();
941}
942
Ken Dyck8c89d592009-12-22 14:23:30 +0000943/// getTypeSizeInChars - Return the size of the specified type, in characters.
944/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000945CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000946 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000947}
Jay Foad39c79802011-01-12 09:06:06 +0000948CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000949 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000950}
951
Ken Dycka6046ab2010-01-26 17:25:18 +0000952/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000953/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000954CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000955 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000956}
Jay Foad39c79802011-01-12 09:06:06 +0000957CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000958 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000959}
960
Chris Lattnera3402cd2009-01-27 18:08:34 +0000961/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
962/// type for the current target in bits. This can be different than the ABI
963/// alignment in cases where it is beneficial for performance to overalign
964/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +0000965unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +0000966 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000967
968 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000969 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000970 T = CT->getElementType().getTypePtr();
971 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
972 T->isSpecificBuiltinType(BuiltinType::LongLong))
973 return std::max(ABIAlign, (unsigned)getTypeSize(T));
974
Chris Lattnera3402cd2009-01-27 18:08:34 +0000975 return ABIAlign;
976}
977
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000978/// ShallowCollectObjCIvars -
979/// Collect all ivars, including those synthesized, in the current class.
980///
981void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +0000982 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000983 // FIXME. This need be removed but there are two many places which
984 // assume const-ness of ObjCInterfaceDecl
985 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
986 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
987 Iv= Iv->getNextIvar())
988 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000989}
990
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000991/// DeepCollectObjCIvars -
992/// This routine first collects all declared, but not synthesized, ivars in
993/// super class and then collects all ivars, including those synthesized for
994/// current class. This routine is used for implementation of current class
995/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000996///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000997void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
998 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +0000999 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001000 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1001 DeepCollectObjCIvars(SuperClass, false, Ivars);
1002 if (!leafClass) {
1003 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1004 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001005 Ivars.push_back(*I);
1006 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001007 else
1008 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001009}
1010
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001011/// CollectInheritedProtocols - Collect all protocols in current class and
1012/// those inherited by it.
1013void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001014 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001015 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001016 // We can use protocol_iterator here instead of
1017 // all_referenced_protocol_iterator since we are walking all categories.
1018 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1019 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001020 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001021 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001022 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001023 PE = Proto->protocol_end(); P != PE; ++P) {
1024 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001025 CollectInheritedProtocols(*P, Protocols);
1026 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001027 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001028
1029 // Categories of this Interface.
1030 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1031 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1032 CollectInheritedProtocols(CDeclChain, Protocols);
1033 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1034 while (SD) {
1035 CollectInheritedProtocols(SD, Protocols);
1036 SD = SD->getSuperClass();
1037 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001038 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001039 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001040 PE = OC->protocol_end(); P != PE; ++P) {
1041 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001042 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001043 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1044 PE = Proto->protocol_end(); P != PE; ++P)
1045 CollectInheritedProtocols(*P, Protocols);
1046 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001047 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001048 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1049 PE = OP->protocol_end(); P != PE; ++P) {
1050 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001051 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001052 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1053 PE = Proto->protocol_end(); P != PE; ++P)
1054 CollectInheritedProtocols(*P, Protocols);
1055 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001056 }
1057}
1058
Jay Foad39c79802011-01-12 09:06:06 +00001059unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001060 unsigned count = 0;
1061 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001062 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1063 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001064 count += CDecl->ivar_size();
1065
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001066 // Count ivar defined in this class's implementation. This
1067 // includes synthesized ivars.
1068 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001069 count += ImplDecl->ivar_size();
1070
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001071 return count;
1072}
1073
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001074/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1075ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1076 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1077 I = ObjCImpls.find(D);
1078 if (I != ObjCImpls.end())
1079 return cast<ObjCImplementationDecl>(I->second);
1080 return 0;
1081}
1082/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1083ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1084 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1085 I = ObjCImpls.find(D);
1086 if (I != ObjCImpls.end())
1087 return cast<ObjCCategoryImplDecl>(I->second);
1088 return 0;
1089}
1090
1091/// \brief Set the implementation of ObjCInterfaceDecl.
1092void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1093 ObjCImplementationDecl *ImplD) {
1094 assert(IFaceD && ImplD && "Passed null params");
1095 ObjCImpls[IFaceD] = ImplD;
1096}
1097/// \brief Set the implementation of ObjCCategoryDecl.
1098void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1099 ObjCCategoryImplDecl *ImplD) {
1100 assert(CatD && ImplD && "Passed null params");
1101 ObjCImpls[CatD] = ImplD;
1102}
1103
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001104/// \brief Get the copy initialization expression of VarDecl,or NULL if
1105/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001106Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001107 assert(VD && "Passed null params");
1108 assert(VD->hasAttr<BlocksAttr>() &&
1109 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001110 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001111 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001112 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1113}
1114
1115/// \brief Set the copy inialization expression of a block var decl.
1116void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1117 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001118 assert(VD->hasAttr<BlocksAttr>() &&
1119 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001120 BlockVarCopyInits[VD] = Init;
1121}
1122
John McCallbcd03502009-12-07 02:54:59 +00001123/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001124///
John McCallbcd03502009-12-07 02:54:59 +00001125/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001126/// the TypeLoc wrappers.
1127///
1128/// \param T the type that will be the basis for type source info. This type
1129/// should refer to how the declarator was written in source code, not to
1130/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001131TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001132 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001133 if (!DataSize)
1134 DataSize = TypeLoc::getFullDataSizeForType(T);
1135 else
1136 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001137 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001138
John McCallbcd03502009-12-07 02:54:59 +00001139 TypeSourceInfo *TInfo =
1140 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1141 new (TInfo) TypeSourceInfo(T);
1142 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001143}
1144
John McCallbcd03502009-12-07 02:54:59 +00001145TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001146 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001147 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001148 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001149 return DI;
1150}
1151
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001152const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001153ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001154 return getObjCLayout(D, 0);
1155}
1156
1157const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001158ASTContext::getASTObjCImplementationLayout(
1159 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001160 return getObjCLayout(D->getClassInterface(), D);
1161}
1162
Chris Lattner983a8bb2007-07-13 22:13:22 +00001163//===----------------------------------------------------------------------===//
1164// Type creation/memoization methods
1165//===----------------------------------------------------------------------===//
1166
Jay Foad39c79802011-01-12 09:06:06 +00001167QualType
John McCall33ddac02011-01-19 10:06:00 +00001168ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1169 unsigned fastQuals = quals.getFastQualifiers();
1170 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001171
1172 // Check if we've already instantiated this type.
1173 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001174 ExtQuals::Profile(ID, baseType, quals);
1175 void *insertPos = 0;
1176 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1177 assert(eq->getQualifiers() == quals);
1178 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001179 }
1180
John McCall33ddac02011-01-19 10:06:00 +00001181 // If the base type is not canonical, make the appropriate canonical type.
1182 QualType canon;
1183 if (!baseType->isCanonicalUnqualified()) {
1184 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1185 canonSplit.second.addConsistentQualifiers(quals);
1186 canon = getExtQualType(canonSplit.first, canonSplit.second);
1187
1188 // Re-find the insert position.
1189 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1190 }
1191
1192 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1193 ExtQualNodes.InsertNode(eq, insertPos);
1194 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001195}
1196
Jay Foad39c79802011-01-12 09:06:06 +00001197QualType
1198ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001199 QualType CanT = getCanonicalType(T);
1200 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001201 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001202
John McCall8ccfcb52009-09-24 19:53:00 +00001203 // If we are composing extended qualifiers together, merge together
1204 // into one ExtQuals node.
1205 QualifierCollector Quals;
1206 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001207
John McCall8ccfcb52009-09-24 19:53:00 +00001208 // If this type already has an address space specified, it cannot get
1209 // another one.
1210 assert(!Quals.hasAddressSpace() &&
1211 "Type cannot be in multiple addr spaces!");
1212 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001213
John McCall8ccfcb52009-09-24 19:53:00 +00001214 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001215}
1216
Chris Lattnerd60183d2009-02-18 22:53:11 +00001217QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001218 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001219 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001220 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001221 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001222
John McCall53fa7142010-12-24 02:08:15 +00001223 if (const PointerType *ptr = T->getAs<PointerType>()) {
1224 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001225 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001226 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1227 return getPointerType(ResultType);
1228 }
1229 }
Mike Stump11289f42009-09-09 15:08:12 +00001230
John McCall8ccfcb52009-09-24 19:53:00 +00001231 // If we are composing extended qualifiers together, merge together
1232 // into one ExtQuals node.
1233 QualifierCollector Quals;
1234 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001235
John McCall8ccfcb52009-09-24 19:53:00 +00001236 // If this type already has an ObjCGC specified, it cannot get
1237 // another one.
1238 assert(!Quals.hasObjCGCAttr() &&
1239 "Type cannot have multiple ObjCGCs!");
1240 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001241
John McCall8ccfcb52009-09-24 19:53:00 +00001242 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001243}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001244
John McCall4f5019e2010-12-19 02:44:49 +00001245const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1246 FunctionType::ExtInfo Info) {
1247 if (T->getExtInfo() == Info)
1248 return T;
1249
1250 QualType Result;
1251 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1252 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1253 } else {
1254 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1255 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1256 EPI.ExtInfo = Info;
1257 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1258 FPT->getNumArgs(), EPI);
1259 }
1260
1261 return cast<FunctionType>(Result.getTypePtr());
1262}
1263
Chris Lattnerc6395932007-06-22 20:56:16 +00001264/// getComplexType - Return the uniqued reference to the type for a complex
1265/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001266QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001267 // Unique pointers, to guarantee there is only one pointer of a particular
1268 // structure.
1269 llvm::FoldingSetNodeID ID;
1270 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001271
Chris Lattnerc6395932007-06-22 20:56:16 +00001272 void *InsertPos = 0;
1273 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1274 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001275
Chris Lattnerc6395932007-06-22 20:56:16 +00001276 // If the pointee type isn't canonical, this won't be a canonical type either,
1277 // so fill in the canonical type field.
1278 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001279 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001280 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001281
Chris Lattnerc6395932007-06-22 20:56:16 +00001282 // Get the new insert position for the node we care about.
1283 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001284 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001285 }
John McCall90d1c2d2009-09-24 23:30:46 +00001286 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001287 Types.push_back(New);
1288 ComplexTypes.InsertNode(New, InsertPos);
1289 return QualType(New, 0);
1290}
1291
Chris Lattner970e54e2006-11-12 00:37:36 +00001292/// getPointerType - Return the uniqued reference to the type for a pointer to
1293/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001294QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001295 // Unique pointers, to guarantee there is only one pointer of a particular
1296 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001297 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001298 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001299
Chris Lattner67521df2007-01-27 01:29:36 +00001300 void *InsertPos = 0;
1301 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001302 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001303
Chris Lattner7ccecb92006-11-12 08:50:50 +00001304 // If the pointee type isn't canonical, this won't be a canonical type either,
1305 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001306 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001307 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001308 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001309
Chris Lattner67521df2007-01-27 01:29:36 +00001310 // Get the new insert position for the node we care about.
1311 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001312 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001313 }
John McCall90d1c2d2009-09-24 23:30:46 +00001314 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001315 Types.push_back(New);
1316 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001317 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001318}
1319
Mike Stump11289f42009-09-09 15:08:12 +00001320/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001321/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001322QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001323 assert(T->isFunctionType() && "block of function types only");
1324 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001325 // structure.
1326 llvm::FoldingSetNodeID ID;
1327 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001328
Steve Naroffec33ed92008-08-27 16:04:49 +00001329 void *InsertPos = 0;
1330 if (BlockPointerType *PT =
1331 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1332 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001333
1334 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001335 // type either so fill in the canonical type field.
1336 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001337 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001338 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001339
Steve Naroffec33ed92008-08-27 16:04:49 +00001340 // Get the new insert position for the node we care about.
1341 BlockPointerType *NewIP =
1342 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001343 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001344 }
John McCall90d1c2d2009-09-24 23:30:46 +00001345 BlockPointerType *New
1346 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001347 Types.push_back(New);
1348 BlockPointerTypes.InsertNode(New, InsertPos);
1349 return QualType(New, 0);
1350}
1351
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001352/// getLValueReferenceType - Return the uniqued reference to the type for an
1353/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001354QualType
1355ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001356 // Unique pointers, to guarantee there is only one pointer of a particular
1357 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001358 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001359 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001360
1361 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001362 if (LValueReferenceType *RT =
1363 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001364 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001365
John McCallfc93cf92009-10-22 22:37:11 +00001366 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1367
Bill Wendling3708c182007-05-27 10:15:43 +00001368 // If the referencee type isn't canonical, this won't be a canonical type
1369 // either, so fill in the canonical type field.
1370 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001371 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1372 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1373 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001374
Bill Wendling3708c182007-05-27 10:15:43 +00001375 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001376 LValueReferenceType *NewIP =
1377 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001378 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001379 }
1380
John McCall90d1c2d2009-09-24 23:30:46 +00001381 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001382 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1383 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001384 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001385 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001386
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001387 return QualType(New, 0);
1388}
1389
1390/// getRValueReferenceType - Return the uniqued reference to the type for an
1391/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001392QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001393 // Unique pointers, to guarantee there is only one pointer of a particular
1394 // structure.
1395 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001396 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001397
1398 void *InsertPos = 0;
1399 if (RValueReferenceType *RT =
1400 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1401 return QualType(RT, 0);
1402
John McCallfc93cf92009-10-22 22:37:11 +00001403 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1404
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001405 // If the referencee type isn't canonical, this won't be a canonical type
1406 // either, so fill in the canonical type field.
1407 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001408 if (InnerRef || !T.isCanonical()) {
1409 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1410 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001411
1412 // Get the new insert position for the node we care about.
1413 RValueReferenceType *NewIP =
1414 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001415 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001416 }
1417
John McCall90d1c2d2009-09-24 23:30:46 +00001418 RValueReferenceType *New
1419 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001420 Types.push_back(New);
1421 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001422 return QualType(New, 0);
1423}
1424
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001425/// getMemberPointerType - Return the uniqued reference to the type for a
1426/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001427QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001428 // Unique pointers, to guarantee there is only one pointer of a particular
1429 // structure.
1430 llvm::FoldingSetNodeID ID;
1431 MemberPointerType::Profile(ID, T, Cls);
1432
1433 void *InsertPos = 0;
1434 if (MemberPointerType *PT =
1435 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1436 return QualType(PT, 0);
1437
1438 // If the pointee or class type isn't canonical, this won't be a canonical
1439 // type either, so fill in the canonical type field.
1440 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001441 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001442 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1443
1444 // Get the new insert position for the node we care about.
1445 MemberPointerType *NewIP =
1446 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001447 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001448 }
John McCall90d1c2d2009-09-24 23:30:46 +00001449 MemberPointerType *New
1450 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001451 Types.push_back(New);
1452 MemberPointerTypes.InsertNode(New, InsertPos);
1453 return QualType(New, 0);
1454}
1455
Mike Stump11289f42009-09-09 15:08:12 +00001456/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001457/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001458QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001459 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001460 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001461 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001462 assert((EltTy->isDependentType() ||
1463 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001464 "Constant array of VLAs is illegal!");
1465
Chris Lattnere2df3f92009-05-13 04:12:56 +00001466 // Convert the array size into a canonical width matching the pointer size for
1467 // the target.
1468 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001469 ArySize =
1470 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001471
Chris Lattner23b7eb62007-06-15 23:05:46 +00001472 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001473 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001474
Chris Lattner36f8e652007-01-27 08:31:04 +00001475 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001476 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001477 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001478 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001479
John McCall33ddac02011-01-19 10:06:00 +00001480 // If the element type isn't canonical or has qualifiers, this won't
1481 // be a canonical type either, so fill in the canonical type field.
1482 QualType Canon;
1483 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1484 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1485 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001486 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001487 Canon = getQualifiedType(Canon, canonSplit.second);
1488
Chris Lattner36f8e652007-01-27 08:31:04 +00001489 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001490 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001491 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001492 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001493 }
Mike Stump11289f42009-09-09 15:08:12 +00001494
John McCall90d1c2d2009-09-24 23:30:46 +00001495 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001496 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001497 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001498 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001499 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001500}
1501
John McCall06549462011-01-18 08:40:38 +00001502/// getVariableArrayDecayedType - Turns the given type, which may be
1503/// variably-modified, into the corresponding type with all the known
1504/// sizes replaced with [*].
1505QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1506 // Vastly most common case.
1507 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001508
John McCall06549462011-01-18 08:40:38 +00001509 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001510
John McCall06549462011-01-18 08:40:38 +00001511 SplitQualType split = type.getSplitDesugaredType();
1512 const Type *ty = split.first;
1513 switch (ty->getTypeClass()) {
1514#define TYPE(Class, Base)
1515#define ABSTRACT_TYPE(Class, Base)
1516#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1517#include "clang/AST/TypeNodes.def"
1518 llvm_unreachable("didn't desugar past all non-canonical types?");
1519
1520 // These types should never be variably-modified.
1521 case Type::Builtin:
1522 case Type::Complex:
1523 case Type::Vector:
1524 case Type::ExtVector:
1525 case Type::DependentSizedExtVector:
1526 case Type::ObjCObject:
1527 case Type::ObjCInterface:
1528 case Type::ObjCObjectPointer:
1529 case Type::Record:
1530 case Type::Enum:
1531 case Type::UnresolvedUsing:
1532 case Type::TypeOfExpr:
1533 case Type::TypeOf:
1534 case Type::Decltype:
1535 case Type::DependentName:
1536 case Type::InjectedClassName:
1537 case Type::TemplateSpecialization:
1538 case Type::DependentTemplateSpecialization:
1539 case Type::TemplateTypeParm:
1540 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001541 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001542 case Type::PackExpansion:
1543 llvm_unreachable("type should never be variably-modified");
1544
1545 // These types can be variably-modified but should never need to
1546 // further decay.
1547 case Type::FunctionNoProto:
1548 case Type::FunctionProto:
1549 case Type::BlockPointer:
1550 case Type::MemberPointer:
1551 return type;
1552
1553 // These types can be variably-modified. All these modifications
1554 // preserve structure except as noted by comments.
1555 // TODO: if we ever care about optimizing VLAs, there are no-op
1556 // optimizations available here.
1557 case Type::Pointer:
1558 result = getPointerType(getVariableArrayDecayedType(
1559 cast<PointerType>(ty)->getPointeeType()));
1560 break;
1561
1562 case Type::LValueReference: {
1563 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1564 result = getLValueReferenceType(
1565 getVariableArrayDecayedType(lv->getPointeeType()),
1566 lv->isSpelledAsLValue());
1567 break;
1568 }
1569
1570 case Type::RValueReference: {
1571 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1572 result = getRValueReferenceType(
1573 getVariableArrayDecayedType(lv->getPointeeType()));
1574 break;
1575 }
1576
1577 case Type::ConstantArray: {
1578 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1579 result = getConstantArrayType(
1580 getVariableArrayDecayedType(cat->getElementType()),
1581 cat->getSize(),
1582 cat->getSizeModifier(),
1583 cat->getIndexTypeCVRQualifiers());
1584 break;
1585 }
1586
1587 case Type::DependentSizedArray: {
1588 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1589 result = getDependentSizedArrayType(
1590 getVariableArrayDecayedType(dat->getElementType()),
1591 dat->getSizeExpr(),
1592 dat->getSizeModifier(),
1593 dat->getIndexTypeCVRQualifiers(),
1594 dat->getBracketsRange());
1595 break;
1596 }
1597
1598 // Turn incomplete types into [*] types.
1599 case Type::IncompleteArray: {
1600 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1601 result = getVariableArrayType(
1602 getVariableArrayDecayedType(iat->getElementType()),
1603 /*size*/ 0,
1604 ArrayType::Normal,
1605 iat->getIndexTypeCVRQualifiers(),
1606 SourceRange());
1607 break;
1608 }
1609
1610 // Turn VLA types into [*] types.
1611 case Type::VariableArray: {
1612 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1613 result = getVariableArrayType(
1614 getVariableArrayDecayedType(vat->getElementType()),
1615 /*size*/ 0,
1616 ArrayType::Star,
1617 vat->getIndexTypeCVRQualifiers(),
1618 vat->getBracketsRange());
1619 break;
1620 }
1621 }
1622
1623 // Apply the top-level qualifiers from the original.
1624 return getQualifiedType(result, split.second);
1625}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001626
Steve Naroffcadebd02007-08-30 18:14:25 +00001627/// getVariableArrayType - Returns a non-unique reference to the type for a
1628/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001629QualType ASTContext::getVariableArrayType(QualType EltTy,
1630 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001631 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001632 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001633 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001634 // Since we don't unique expressions, it isn't possible to unique VLA's
1635 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001636 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001637
John McCall33ddac02011-01-19 10:06:00 +00001638 // Be sure to pull qualifiers off the element type.
1639 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1640 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1641 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001642 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001643 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001644 }
1645
John McCall90d1c2d2009-09-24 23:30:46 +00001646 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001647 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001648
1649 VariableArrayTypes.push_back(New);
1650 Types.push_back(New);
1651 return QualType(New, 0);
1652}
1653
Douglas Gregor4619e432008-12-05 23:32:09 +00001654/// getDependentSizedArrayType - Returns a non-unique reference to
1655/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001656/// type.
John McCall33ddac02011-01-19 10:06:00 +00001657QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1658 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001659 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001660 unsigned elementTypeQuals,
1661 SourceRange brackets) const {
1662 assert((!numElements || numElements->isTypeDependent() ||
1663 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001664 "Size must be type- or value-dependent!");
1665
John McCall33ddac02011-01-19 10:06:00 +00001666 // Dependently-sized array types that do not have a specified number
1667 // of elements will have their sizes deduced from a dependent
1668 // initializer. We do no canonicalization here at all, which is okay
1669 // because they can't be used in most locations.
1670 if (!numElements) {
1671 DependentSizedArrayType *newType
1672 = new (*this, TypeAlignment)
1673 DependentSizedArrayType(*this, elementType, QualType(),
1674 numElements, ASM, elementTypeQuals,
1675 brackets);
1676 Types.push_back(newType);
1677 return QualType(newType, 0);
1678 }
1679
1680 // Otherwise, we actually build a new type every time, but we
1681 // also build a canonical type.
1682
1683 SplitQualType canonElementType = getCanonicalType(elementType).split();
1684
1685 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001686 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001687 DependentSizedArrayType::Profile(ID, *this,
1688 QualType(canonElementType.first, 0),
1689 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001690
John McCall33ddac02011-01-19 10:06:00 +00001691 // Look for an existing type with these properties.
1692 DependentSizedArrayType *canonTy =
1693 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001694
John McCall33ddac02011-01-19 10:06:00 +00001695 // If we don't have one, build one.
1696 if (!canonTy) {
1697 canonTy = new (*this, TypeAlignment)
1698 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1699 QualType(), numElements, ASM, elementTypeQuals,
1700 brackets);
1701 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1702 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001703 }
1704
John McCall33ddac02011-01-19 10:06:00 +00001705 // Apply qualifiers from the element type to the array.
1706 QualType canon = getQualifiedType(QualType(canonTy,0),
1707 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001708
John McCall33ddac02011-01-19 10:06:00 +00001709 // If we didn't need extra canonicalization for the element type,
1710 // then just use that as our result.
1711 if (QualType(canonElementType.first, 0) == elementType)
1712 return canon;
1713
1714 // Otherwise, we need to build a type which follows the spelling
1715 // of the element type.
1716 DependentSizedArrayType *sugaredType
1717 = new (*this, TypeAlignment)
1718 DependentSizedArrayType(*this, elementType, canon, numElements,
1719 ASM, elementTypeQuals, brackets);
1720 Types.push_back(sugaredType);
1721 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001722}
1723
John McCall33ddac02011-01-19 10:06:00 +00001724QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001725 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001726 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001727 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001728 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001729
John McCall33ddac02011-01-19 10:06:00 +00001730 void *insertPos = 0;
1731 if (IncompleteArrayType *iat =
1732 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1733 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001734
1735 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001736 // either, so fill in the canonical type field. We also have to pull
1737 // qualifiers off the element type.
1738 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001739
John McCall33ddac02011-01-19 10:06:00 +00001740 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1741 SplitQualType canonSplit = getCanonicalType(elementType).split();
1742 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1743 ASM, elementTypeQuals);
1744 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001745
1746 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001747 IncompleteArrayType *existing =
1748 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1749 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001750 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001751
John McCall33ddac02011-01-19 10:06:00 +00001752 IncompleteArrayType *newType = new (*this, TypeAlignment)
1753 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001754
John McCall33ddac02011-01-19 10:06:00 +00001755 IncompleteArrayTypes.InsertNode(newType, insertPos);
1756 Types.push_back(newType);
1757 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001758}
1759
Steve Naroff91fcddb2007-07-18 18:00:27 +00001760/// getVectorType - Return the unique reference to a vector type of
1761/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001762QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001763 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001764 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001765
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001766 // Check if we've already instantiated a vector of this type.
1767 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001768 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001769
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001770 void *InsertPos = 0;
1771 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1772 return QualType(VTP, 0);
1773
1774 // If the element type isn't canonical, this won't be a canonical type either,
1775 // so fill in the canonical type field.
1776 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001777 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001778 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001779
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001780 // Get the new insert position for the node we care about.
1781 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001782 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001783 }
John McCall90d1c2d2009-09-24 23:30:46 +00001784 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001785 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001786 VectorTypes.InsertNode(New, InsertPos);
1787 Types.push_back(New);
1788 return QualType(New, 0);
1789}
1790
Nate Begemance4d7fc2008-04-18 23:10:10 +00001791/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001792/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001793QualType
1794ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall33ddac02011-01-19 10:06:00 +00001795 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001796
Steve Naroff91fcddb2007-07-18 18:00:27 +00001797 // Check if we've already instantiated a vector of this type.
1798 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001799 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001800 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001801 void *InsertPos = 0;
1802 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1803 return QualType(VTP, 0);
1804
1805 // If the element type isn't canonical, this won't be a canonical type either,
1806 // so fill in the canonical type field.
1807 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001808 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001809 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001810
Steve Naroff91fcddb2007-07-18 18:00:27 +00001811 // Get the new insert position for the node we care about.
1812 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001813 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001814 }
John McCall90d1c2d2009-09-24 23:30:46 +00001815 ExtVectorType *New = new (*this, TypeAlignment)
1816 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001817 VectorTypes.InsertNode(New, InsertPos);
1818 Types.push_back(New);
1819 return QualType(New, 0);
1820}
1821
Jay Foad39c79802011-01-12 09:06:06 +00001822QualType
1823ASTContext::getDependentSizedExtVectorType(QualType vecType,
1824 Expr *SizeExpr,
1825 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001826 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001827 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001828 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001829
Douglas Gregor352169a2009-07-31 03:54:25 +00001830 void *InsertPos = 0;
1831 DependentSizedExtVectorType *Canon
1832 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1833 DependentSizedExtVectorType *New;
1834 if (Canon) {
1835 // We already have a canonical version of this array type; use it as
1836 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001837 New = new (*this, TypeAlignment)
1838 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1839 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001840 } else {
1841 QualType CanonVecTy = getCanonicalType(vecType);
1842 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001843 New = new (*this, TypeAlignment)
1844 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1845 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001846
1847 DependentSizedExtVectorType *CanonCheck
1848 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1849 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1850 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001851 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1852 } else {
1853 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1854 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001855 New = new (*this, TypeAlignment)
1856 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001857 }
1858 }
Mike Stump11289f42009-09-09 15:08:12 +00001859
Douglas Gregor758a8692009-06-17 21:51:59 +00001860 Types.push_back(New);
1861 return QualType(New, 0);
1862}
1863
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001864/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001865///
Jay Foad39c79802011-01-12 09:06:06 +00001866QualType
1867ASTContext::getFunctionNoProtoType(QualType ResultTy,
1868 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00001869 const CallingConv DefaultCC = Info.getCC();
1870 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1871 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001872 // Unique functions, to guarantee there is only one function of a particular
1873 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001874 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001875 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001876
Chris Lattner47955de2007-01-27 08:37:20 +00001877 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001878 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001879 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001880 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001881
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001882 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001883 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001884 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001885 Canonical =
1886 getFunctionNoProtoType(getCanonicalType(ResultTy),
1887 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001888
Chris Lattner47955de2007-01-27 08:37:20 +00001889 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001890 FunctionNoProtoType *NewIP =
1891 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001892 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001893 }
Mike Stump11289f42009-09-09 15:08:12 +00001894
Roman Divacky65b88cd2011-03-01 17:40:53 +00001895 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00001896 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00001897 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00001898 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001899 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001900 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001901}
1902
1903/// getFunctionType - Return a normal function type with a typed argument
1904/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001905QualType
1906ASTContext::getFunctionType(QualType ResultTy,
1907 const QualType *ArgArray, unsigned NumArgs,
1908 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001909 // Unique functions, to guarantee there is only one function of a particular
1910 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001911 llvm::FoldingSetNodeID ID;
John McCalldb40c7f2010-12-14 08:05:40 +00001912 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001913
1914 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001915 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001916 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001917 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001918
1919 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00001920 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001921 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001922 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001923 isCanonical = false;
1924
Roman Divacky65b88cd2011-03-01 17:40:53 +00001925 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
1926 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1927 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00001928
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001929 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001930 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001931 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001932 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001933 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001934 CanonicalArgs.reserve(NumArgs);
1935 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001936 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001937
John McCalldb40c7f2010-12-14 08:05:40 +00001938 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00001939 CanonicalEPI.ExceptionSpecType = EST_None;
1940 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00001941 CanonicalEPI.ExtInfo
1942 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1943
Chris Lattner76a00cf2008-04-06 22:59:24 +00001944 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001945 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00001946 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001947
Chris Lattnerfd4de792007-01-27 01:15:32 +00001948 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001949 FunctionProtoType *NewIP =
1950 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001951 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001952 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001953
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001954 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001955 // for two variable size arrays (for parameter and exception types) at the
1956 // end of them.
John McCalldb40c7f2010-12-14 08:05:40 +00001957 size_t Size = sizeof(FunctionProtoType) +
1958 NumArgs * sizeof(QualType) +
1959 EPI.NumExceptions * sizeof(QualType);
1960 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00001961 FunctionProtoType::ExtProtoInfo newEPI = EPI;
1962 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
1963 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001964 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001965 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001966 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001967}
Chris Lattneref51c202006-11-10 07:17:23 +00001968
John McCalle78aac42010-03-10 03:28:59 +00001969#ifndef NDEBUG
1970static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1971 if (!isa<CXXRecordDecl>(D)) return false;
1972 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1973 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1974 return true;
1975 if (RD->getDescribedClassTemplate() &&
1976 !isa<ClassTemplateSpecializationDecl>(RD))
1977 return true;
1978 return false;
1979}
1980#endif
1981
1982/// getInjectedClassNameType - Return the unique reference to the
1983/// injected class name type for the specified templated declaration.
1984QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00001985 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00001986 assert(NeedsInjectedClassNameType(Decl));
1987 if (Decl->TypeForDecl) {
1988 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001989 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001990 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1991 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1992 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1993 } else {
John McCall424cec92011-01-19 06:33:43 +00001994 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00001995 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00001996 Decl->TypeForDecl = newType;
1997 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00001998 }
1999 return QualType(Decl->TypeForDecl, 0);
2000}
2001
Douglas Gregor83a586e2008-04-13 21:07:44 +00002002/// getTypeDeclType - Return the unique reference to the type for the
2003/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002004QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002005 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002006 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002007
John McCall81e38502010-02-16 03:57:14 +00002008 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002009 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002010
John McCall96f0b5f2010-03-10 06:48:02 +00002011 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2012 "Template type parameter types are always available.");
2013
John McCall81e38502010-02-16 03:57:14 +00002014 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002015 assert(!Record->getPreviousDeclaration() &&
2016 "struct/union has previous declaration");
2017 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002018 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002019 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002020 assert(!Enum->getPreviousDeclaration() &&
2021 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002022 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002023 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002024 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002025 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2026 Decl->TypeForDecl = newType;
2027 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002028 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002029 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002030
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002031 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002032}
2033
Chris Lattner32d920b2007-01-26 02:01:53 +00002034/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00002035/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002036QualType
Jay Foad39c79802011-01-12 09:06:06 +00002037ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002038 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002039
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002040 if (Canonical.isNull())
2041 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002042 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002043 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002044 Decl->TypeForDecl = newType;
2045 Types.push_back(newType);
2046 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002047}
2048
Jay Foad39c79802011-01-12 09:06:06 +00002049QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002050 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2051
2052 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2053 if (PrevDecl->TypeForDecl)
2054 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2055
John McCall424cec92011-01-19 06:33:43 +00002056 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2057 Decl->TypeForDecl = newType;
2058 Types.push_back(newType);
2059 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002060}
2061
Jay Foad39c79802011-01-12 09:06:06 +00002062QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002063 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2064
2065 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2066 if (PrevDecl->TypeForDecl)
2067 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2068
John McCall424cec92011-01-19 06:33:43 +00002069 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2070 Decl->TypeForDecl = newType;
2071 Types.push_back(newType);
2072 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002073}
2074
John McCall81904512011-01-06 01:58:22 +00002075QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2076 QualType modifiedType,
2077 QualType equivalentType) {
2078 llvm::FoldingSetNodeID id;
2079 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2080
2081 void *insertPos = 0;
2082 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2083 if (type) return QualType(type, 0);
2084
2085 QualType canon = getCanonicalType(equivalentType);
2086 type = new (*this, TypeAlignment)
2087 AttributedType(canon, attrKind, modifiedType, equivalentType);
2088
2089 Types.push_back(type);
2090 AttributedTypes.InsertNode(type, insertPos);
2091
2092 return QualType(type, 0);
2093}
2094
2095
John McCallcebee162009-10-18 09:09:24 +00002096/// \brief Retrieve a substitution-result type.
2097QualType
2098ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002099 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002100 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002101 && "replacement types must always be canonical");
2102
2103 llvm::FoldingSetNodeID ID;
2104 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2105 void *InsertPos = 0;
2106 SubstTemplateTypeParmType *SubstParm
2107 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2108
2109 if (!SubstParm) {
2110 SubstParm = new (*this, TypeAlignment)
2111 SubstTemplateTypeParmType(Parm, Replacement);
2112 Types.push_back(SubstParm);
2113 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2114 }
2115
2116 return QualType(SubstParm, 0);
2117}
2118
Douglas Gregorada4b792011-01-14 02:55:32 +00002119/// \brief Retrieve a
2120QualType ASTContext::getSubstTemplateTypeParmPackType(
2121 const TemplateTypeParmType *Parm,
2122 const TemplateArgument &ArgPack) {
2123#ifndef NDEBUG
2124 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2125 PEnd = ArgPack.pack_end();
2126 P != PEnd; ++P) {
2127 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2128 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2129 }
2130#endif
2131
2132 llvm::FoldingSetNodeID ID;
2133 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2134 void *InsertPos = 0;
2135 if (SubstTemplateTypeParmPackType *SubstParm
2136 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2137 return QualType(SubstParm, 0);
2138
2139 QualType Canon;
2140 if (!Parm->isCanonicalUnqualified()) {
2141 Canon = getCanonicalType(QualType(Parm, 0));
2142 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2143 ArgPack);
2144 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2145 }
2146
2147 SubstTemplateTypeParmPackType *SubstParm
2148 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2149 ArgPack);
2150 Types.push_back(SubstParm);
2151 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2152 return QualType(SubstParm, 0);
2153}
2154
Douglas Gregoreff93e02009-02-05 23:33:38 +00002155/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002156/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002157/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002158QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002159 bool ParameterPack,
Jay Foad39c79802011-01-12 09:06:06 +00002160 IdentifierInfo *Name) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002161 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002162 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002163 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002164 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002165 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2166
2167 if (TypeParm)
2168 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002169
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002170 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002171 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002172 TypeParm = new (*this, TypeAlignment)
2173 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002174
2175 TemplateTypeParmType *TypeCheck
2176 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2177 assert(!TypeCheck && "Template type parameter canonical type broken");
2178 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002179 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002180 TypeParm = new (*this, TypeAlignment)
2181 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002182
2183 Types.push_back(TypeParm);
2184 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2185
2186 return QualType(TypeParm, 0);
2187}
2188
John McCalle78aac42010-03-10 03:28:59 +00002189TypeSourceInfo *
2190ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2191 SourceLocation NameLoc,
2192 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002193 QualType CanonType) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002194 assert(!Name.getAsDependentTemplateName() &&
2195 "No dependent template names here!");
John McCalle78aac42010-03-10 03:28:59 +00002196 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2197
2198 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2199 TemplateSpecializationTypeLoc TL
2200 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2201 TL.setTemplateNameLoc(NameLoc);
2202 TL.setLAngleLoc(Args.getLAngleLoc());
2203 TL.setRAngleLoc(Args.getRAngleLoc());
2204 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2205 TL.setArgLocInfo(i, Args[i].getLocInfo());
2206 return DI;
2207}
2208
Mike Stump11289f42009-09-09 15:08:12 +00002209QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002210ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002211 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002212 QualType Canon) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002213 assert(!Template.getAsDependentTemplateName() &&
2214 "No dependent template names here!");
2215
John McCall6b51f282009-11-23 01:53:49 +00002216 unsigned NumArgs = Args.size();
2217
John McCall0ad16662009-10-29 08:12:44 +00002218 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2219 ArgVec.reserve(NumArgs);
2220 for (unsigned i = 0; i != NumArgs; ++i)
2221 ArgVec.push_back(Args[i].getArgument());
2222
John McCall2408e322010-04-27 00:57:59 +00002223 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00002224 Canon);
John McCall0ad16662009-10-29 08:12:44 +00002225}
2226
2227QualType
2228ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002229 const TemplateArgument *Args,
2230 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002231 QualType Canon) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002232 assert(!Template.getAsDependentTemplateName() &&
2233 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002234 // Look through qualified template names.
2235 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2236 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002237
Douglas Gregor15301382009-07-30 17:40:51 +00002238 if (!Canon.isNull())
2239 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002240 else
2241 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00002242
Douglas Gregora8e02e72009-07-28 23:00:59 +00002243 // Allocate the (non-canonical) template specialization type, but don't
2244 // try to unique it: these types typically have location information that
2245 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002246 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002247 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002248 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002249 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002250 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002251 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002252 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002253
Douglas Gregor8bf42052009-02-09 18:46:07 +00002254 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002255 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002256}
2257
Mike Stump11289f42009-09-09 15:08:12 +00002258QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002259ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2260 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002261 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002262 assert(!Template.getAsDependentTemplateName() &&
2263 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002264 // Look through qualified template names.
2265 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2266 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002267
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002268 // Build the canonical template specialization type.
2269 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2270 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2271 CanonArgs.reserve(NumArgs);
2272 for (unsigned I = 0; I != NumArgs; ++I)
2273 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2274
2275 // Determine whether this canonical template specialization type already
2276 // exists.
2277 llvm::FoldingSetNodeID ID;
2278 TemplateSpecializationType::Profile(ID, CanonTemplate,
2279 CanonArgs.data(), NumArgs, *this);
2280
2281 void *InsertPos = 0;
2282 TemplateSpecializationType *Spec
2283 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2284
2285 if (!Spec) {
2286 // Allocate a new canonical template specialization type.
2287 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2288 sizeof(TemplateArgument) * NumArgs),
2289 TypeAlignment);
2290 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2291 CanonArgs.data(), NumArgs,
2292 QualType());
2293 Types.push_back(Spec);
2294 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2295 }
2296
2297 assert(Spec->isDependentType() &&
2298 "Non-dependent template-id type must have a canonical type");
2299 return QualType(Spec, 0);
2300}
2301
2302QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002303ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2304 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002305 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002306 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002307 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002308
2309 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002310 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002311 if (T)
2312 return QualType(T, 0);
2313
Douglas Gregorc42075a2010-02-04 18:10:26 +00002314 QualType Canon = NamedType;
2315 if (!Canon.isCanonical()) {
2316 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002317 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2318 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002319 (void)CheckT;
2320 }
2321
Abramo Bagnara6150c882010-05-11 21:36:43 +00002322 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002323 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002324 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002325 return QualType(T, 0);
2326}
2327
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002328QualType
Jay Foad39c79802011-01-12 09:06:06 +00002329ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002330 llvm::FoldingSetNodeID ID;
2331 ParenType::Profile(ID, InnerType);
2332
2333 void *InsertPos = 0;
2334 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2335 if (T)
2336 return QualType(T, 0);
2337
2338 QualType Canon = InnerType;
2339 if (!Canon.isCanonical()) {
2340 Canon = getCanonicalType(InnerType);
2341 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2342 assert(!CheckT && "Paren canonical type broken");
2343 (void)CheckT;
2344 }
2345
2346 T = new (*this) ParenType(InnerType, Canon);
2347 Types.push_back(T);
2348 ParenTypes.InsertNode(T, InsertPos);
2349 return QualType(T, 0);
2350}
2351
Douglas Gregor02085352010-03-31 20:19:30 +00002352QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2353 NestedNameSpecifier *NNS,
2354 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002355 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002356 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2357
2358 if (Canon.isNull()) {
2359 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002360 ElaboratedTypeKeyword CanonKeyword = Keyword;
2361 if (Keyword == ETK_None)
2362 CanonKeyword = ETK_Typename;
2363
2364 if (CanonNNS != NNS || CanonKeyword != Keyword)
2365 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002366 }
2367
2368 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002369 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002370
2371 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002372 DependentNameType *T
2373 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002374 if (T)
2375 return QualType(T, 0);
2376
Douglas Gregor02085352010-03-31 20:19:30 +00002377 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002378 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002379 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002380 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002381}
2382
Mike Stump11289f42009-09-09 15:08:12 +00002383QualType
John McCallc392f372010-06-11 00:33:02 +00002384ASTContext::getDependentTemplateSpecializationType(
2385 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002386 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002387 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002388 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002389 // TODO: avoid this copy
2390 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2391 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2392 ArgCopy.push_back(Args[I].getArgument());
2393 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2394 ArgCopy.size(),
2395 ArgCopy.data());
2396}
2397
2398QualType
2399ASTContext::getDependentTemplateSpecializationType(
2400 ElaboratedTypeKeyword Keyword,
2401 NestedNameSpecifier *NNS,
2402 const IdentifierInfo *Name,
2403 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002404 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002405 assert((!NNS || NNS->isDependent()) &&
2406 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002407
Douglas Gregorc42075a2010-02-04 18:10:26 +00002408 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002409 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2410 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002411
2412 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002413 DependentTemplateSpecializationType *T
2414 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002415 if (T)
2416 return QualType(T, 0);
2417
John McCallc392f372010-06-11 00:33:02 +00002418 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002419
John McCallc392f372010-06-11 00:33:02 +00002420 ElaboratedTypeKeyword CanonKeyword = Keyword;
2421 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2422
2423 bool AnyNonCanonArgs = false;
2424 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2425 for (unsigned I = 0; I != NumArgs; ++I) {
2426 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2427 if (!CanonArgs[I].structurallyEquals(Args[I]))
2428 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002429 }
2430
John McCallc392f372010-06-11 00:33:02 +00002431 QualType Canon;
2432 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2433 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2434 Name, NumArgs,
2435 CanonArgs.data());
2436
2437 // Find the insert position again.
2438 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2439 }
2440
2441 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2442 sizeof(TemplateArgument) * NumArgs),
2443 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002444 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002445 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002446 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002447 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002448 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002449}
2450
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002451QualType ASTContext::getPackExpansionType(QualType Pattern,
2452 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002453 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002454 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002455
2456 assert(Pattern->containsUnexpandedParameterPack() &&
2457 "Pack expansions must expand one or more parameter packs");
2458 void *InsertPos = 0;
2459 PackExpansionType *T
2460 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2461 if (T)
2462 return QualType(T, 0);
2463
2464 QualType Canon;
2465 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002466 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002467
2468 // Find the insert position again.
2469 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2470 }
2471
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002472 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002473 Types.push_back(T);
2474 PackExpansionTypes.InsertNode(T, InsertPos);
2475 return QualType(T, 0);
2476}
2477
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002478/// CmpProtocolNames - Comparison predicate for sorting protocols
2479/// alphabetically.
2480static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2481 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002482 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002483}
2484
John McCall8b07ec22010-05-15 11:32:37 +00002485static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002486 unsigned NumProtocols) {
2487 if (NumProtocols == 0) return true;
2488
2489 for (unsigned i = 1; i != NumProtocols; ++i)
2490 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2491 return false;
2492 return true;
2493}
2494
2495static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002496 unsigned &NumProtocols) {
2497 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002498
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002499 // Sort protocols, keyed by name.
2500 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2501
2502 // Remove duplicates.
2503 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2504 NumProtocols = ProtocolsEnd-Protocols;
2505}
2506
John McCall8b07ec22010-05-15 11:32:37 +00002507QualType ASTContext::getObjCObjectType(QualType BaseType,
2508 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002509 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002510 // If the base type is an interface and there aren't any protocols
2511 // to add, then the interface type will do just fine.
2512 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2513 return BaseType;
2514
2515 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002516 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002517 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002518 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002519 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2520 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002521
John McCall8b07ec22010-05-15 11:32:37 +00002522 // Build the canonical type, which has the canonical base type and
2523 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002524 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002525 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2526 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2527 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002528 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2529 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002530 unsigned UniqueCount = NumProtocols;
2531
John McCallfc93cf92009-10-22 22:37:11 +00002532 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002533 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2534 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002535 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002536 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2537 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002538 }
2539
2540 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002541 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2542 }
2543
2544 unsigned Size = sizeof(ObjCObjectTypeImpl);
2545 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2546 void *Mem = Allocate(Size, TypeAlignment);
2547 ObjCObjectTypeImpl *T =
2548 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2549
2550 Types.push_back(T);
2551 ObjCObjectTypes.InsertNode(T, InsertPos);
2552 return QualType(T, 0);
2553}
2554
2555/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2556/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002557QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002558 llvm::FoldingSetNodeID ID;
2559 ObjCObjectPointerType::Profile(ID, ObjectT);
2560
2561 void *InsertPos = 0;
2562 if (ObjCObjectPointerType *QT =
2563 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2564 return QualType(QT, 0);
2565
2566 // Find the canonical object type.
2567 QualType Canonical;
2568 if (!ObjectT.isCanonical()) {
2569 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2570
2571 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002572 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2573 }
2574
Douglas Gregorf85bee62010-02-08 22:59:26 +00002575 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002576 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2577 ObjCObjectPointerType *QType =
2578 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002579
Steve Narofffb4330f2009-06-17 22:40:22 +00002580 Types.push_back(QType);
2581 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002582 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002583}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002584
Douglas Gregor1c283312010-08-11 12:19:30 +00002585/// getObjCInterfaceType - Return the unique reference to the type for the
2586/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002587QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002588 if (Decl->TypeForDecl)
2589 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002590
Douglas Gregor1c283312010-08-11 12:19:30 +00002591 // FIXME: redeclarations?
2592 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2593 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2594 Decl->TypeForDecl = T;
2595 Types.push_back(T);
2596 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002597}
2598
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002599/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2600/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002601/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002602/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002603/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002604QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002605 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002606 if (tofExpr->isTypeDependent()) {
2607 llvm::FoldingSetNodeID ID;
2608 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002609
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002610 void *InsertPos = 0;
2611 DependentTypeOfExprType *Canon
2612 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2613 if (Canon) {
2614 // We already have a "canonical" version of an identical, dependent
2615 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002616 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002617 QualType((TypeOfExprType*)Canon, 0));
2618 }
2619 else {
2620 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002621 Canon
2622 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002623 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2624 toe = Canon;
2625 }
2626 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002627 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002628 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002629 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002630 Types.push_back(toe);
2631 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002632}
2633
Steve Naroffa773cd52007-08-01 18:02:17 +00002634/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2635/// TypeOfType AST's. The only motivation to unique these nodes would be
2636/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002637/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002638/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002639QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002640 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002641 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002642 Types.push_back(tot);
2643 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002644}
2645
Anders Carlssonad6bd352009-06-24 21:24:56 +00002646/// getDecltypeForExpr - Given an expr, will return the decltype for that
2647/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002648static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002649 if (e->isTypeDependent())
2650 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002651
Anders Carlssonad6bd352009-06-24 21:24:56 +00002652 // If e is an id expression or a class member access, decltype(e) is defined
2653 // as the type of the entity named by e.
2654 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2655 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2656 return VD->getType();
2657 }
2658 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2659 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2660 return FD->getType();
2661 }
2662 // If e is a function call or an invocation of an overloaded operator,
2663 // (parentheses around e are ignored), decltype(e) is defined as the
2664 // return type of that function.
2665 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2666 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002667
Anders Carlssonad6bd352009-06-24 21:24:56 +00002668 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002669
2670 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002671 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002672 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002673 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002674
Anders Carlssonad6bd352009-06-24 21:24:56 +00002675 return T;
2676}
2677
Anders Carlsson81df7b82009-06-24 19:06:50 +00002678/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2679/// DecltypeType AST's. The only motivation to unique these nodes would be
2680/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002681/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002682/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002683QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002684 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002685 if (e->isTypeDependent()) {
2686 llvm::FoldingSetNodeID ID;
2687 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002688
Douglas Gregora21f6c32009-07-30 23:36:40 +00002689 void *InsertPos = 0;
2690 DependentDecltypeType *Canon
2691 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2692 if (Canon) {
2693 // We already have a "canonical" version of an equivalent, dependent
2694 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002695 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002696 QualType((DecltypeType*)Canon, 0));
2697 }
2698 else {
2699 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002700 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002701 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2702 dt = Canon;
2703 }
2704 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002705 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002706 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002707 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002708 Types.push_back(dt);
2709 return QualType(dt, 0);
2710}
2711
Richard Smithb2bc2e62011-02-21 20:05:19 +00002712/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002713QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002714 void *InsertPos = 0;
2715 if (!DeducedType.isNull()) {
2716 // Look in the folding set for an existing type.
2717 llvm::FoldingSetNodeID ID;
2718 AutoType::Profile(ID, DeducedType);
2719 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2720 return QualType(AT, 0);
2721 }
2722
2723 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2724 Types.push_back(AT);
2725 if (InsertPos)
2726 AutoTypes.InsertNode(AT, InsertPos);
2727 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002728}
2729
Chris Lattnerfb072462007-01-23 05:45:31 +00002730/// getTagDeclType - Return the unique reference to the type for the
2731/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002732QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002733 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002734 // FIXME: What is the design on getTagDeclType when it requires casting
2735 // away const? mutable?
2736 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002737}
2738
Mike Stump11289f42009-09-09 15:08:12 +00002739/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2740/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2741/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002742CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002743 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002744}
Chris Lattnerfb072462007-01-23 05:45:31 +00002745
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002746/// getSignedWCharType - Return the type of "signed wchar_t".
2747/// Used when in C++, as a GCC extension.
2748QualType ASTContext::getSignedWCharType() const {
2749 // FIXME: derive from "Target" ?
2750 return WCharTy;
2751}
2752
2753/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2754/// Used when in C++, as a GCC extension.
2755QualType ASTContext::getUnsignedWCharType() const {
2756 // FIXME: derive from "Target" ?
2757 return UnsignedIntTy;
2758}
2759
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002760/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2761/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2762QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002763 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002764}
2765
Chris Lattnera21ad802008-04-02 05:18:44 +00002766//===----------------------------------------------------------------------===//
2767// Type Operators
2768//===----------------------------------------------------------------------===//
2769
Jay Foad39c79802011-01-12 09:06:06 +00002770CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002771 // Push qualifiers into arrays, and then discard any remaining
2772 // qualifiers.
2773 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002774 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002775 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002776 QualType Result;
2777 if (isa<ArrayType>(Ty)) {
2778 Result = getArrayDecayedType(QualType(Ty,0));
2779 } else if (isa<FunctionType>(Ty)) {
2780 Result = getPointerType(QualType(Ty, 0));
2781 } else {
2782 Result = QualType(Ty, 0);
2783 }
2784
2785 return CanQualType::CreateUnsafe(Result);
2786}
2787
Chris Lattner7adf0762008-08-04 07:31:14 +00002788
John McCall6c9dd522011-01-18 07:41:22 +00002789QualType ASTContext::getUnqualifiedArrayType(QualType type,
2790 Qualifiers &quals) {
2791 SplitQualType splitType = type.getSplitUnqualifiedType();
2792
2793 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2794 // the unqualified desugared type and then drops it on the floor.
2795 // We then have to strip that sugar back off with
2796 // getUnqualifiedDesugaredType(), which is silly.
2797 const ArrayType *AT =
2798 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2799
2800 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002801 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002802 quals = splitType.second;
2803 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002804 }
2805
John McCall6c9dd522011-01-18 07:41:22 +00002806 // Otherwise, recurse on the array's element type.
2807 QualType elementType = AT->getElementType();
2808 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2809
2810 // If that didn't change the element type, AT has no qualifiers, so we
2811 // can just use the results in splitType.
2812 if (elementType == unqualElementType) {
2813 assert(quals.empty()); // from the recursive call
2814 quals = splitType.second;
2815 return QualType(splitType.first, 0);
2816 }
2817
2818 // Otherwise, add in the qualifiers from the outermost type, then
2819 // build the type back up.
2820 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002821
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002822 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002823 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002824 CAT->getSizeModifier(), 0);
2825 }
2826
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002827 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002828 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002829 }
2830
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002831 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002832 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002833 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002834 VAT->getSizeModifier(),
2835 VAT->getIndexTypeCVRQualifiers(),
2836 VAT->getBracketsRange());
2837 }
2838
2839 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002840 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002841 DSAT->getSizeModifier(), 0,
2842 SourceRange());
2843}
2844
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002845/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2846/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2847/// they point to and return true. If T1 and T2 aren't pointer types
2848/// or pointer-to-member types, or if they are not similar at this
2849/// level, returns false and leaves T1 and T2 unchanged. Top-level
2850/// qualifiers on T1 and T2 are ignored. This function will typically
2851/// be called in a loop that successively "unwraps" pointer and
2852/// pointer-to-member types to compare them at each level.
2853bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2854 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2855 *T2PtrType = T2->getAs<PointerType>();
2856 if (T1PtrType && T2PtrType) {
2857 T1 = T1PtrType->getPointeeType();
2858 T2 = T2PtrType->getPointeeType();
2859 return true;
2860 }
2861
2862 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2863 *T2MPType = T2->getAs<MemberPointerType>();
2864 if (T1MPType && T2MPType &&
2865 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2866 QualType(T2MPType->getClass(), 0))) {
2867 T1 = T1MPType->getPointeeType();
2868 T2 = T2MPType->getPointeeType();
2869 return true;
2870 }
2871
2872 if (getLangOptions().ObjC1) {
2873 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2874 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2875 if (T1OPType && T2OPType) {
2876 T1 = T1OPType->getPointeeType();
2877 T2 = T2OPType->getPointeeType();
2878 return true;
2879 }
2880 }
2881
2882 // FIXME: Block pointers, too?
2883
2884 return false;
2885}
2886
Jay Foad39c79802011-01-12 09:06:06 +00002887DeclarationNameInfo
2888ASTContext::getNameForTemplate(TemplateName Name,
2889 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002890 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002891 // DNInfo work in progress: CHECKME: what about DNLoc?
2892 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2893
John McCall847e2a12009-11-24 18:42:40 +00002894 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002895 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002896 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002897 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2898 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002899 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002900 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2901 // DNInfo work in progress: FIXME: source locations?
2902 DeclarationNameLoc DNLoc;
2903 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2904 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2905 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002906 }
2907 }
2908
John McCalld28ae272009-12-02 08:04:21 +00002909 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2910 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002911 // DNInfo work in progress: CHECKME: what about DNLoc?
2912 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002913}
2914
Jay Foad39c79802011-01-12 09:06:06 +00002915TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002916 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2917 if (TemplateTemplateParmDecl *TTP
2918 = dyn_cast<TemplateTemplateParmDecl>(Template))
2919 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2920
2921 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002922 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002923 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002924
Douglas Gregor5590be02011-01-15 06:45:20 +00002925 if (SubstTemplateTemplateParmPackStorage *SubstPack
2926 = Name.getAsSubstTemplateTemplateParmPack()) {
2927 TemplateTemplateParmDecl *CanonParam
2928 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2929 TemplateArgument CanonArgPack
2930 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2931 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2932 }
2933
John McCalld28ae272009-12-02 08:04:21 +00002934 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002935
Douglas Gregor6bc50582009-05-07 06:41:52 +00002936 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2937 assert(DTN && "Non-dependent template names must refer to template decls.");
2938 return DTN->CanonicalTemplateName;
2939}
2940
Douglas Gregoradee3e32009-11-11 23:06:43 +00002941bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2942 X = getCanonicalTemplateName(X);
2943 Y = getCanonicalTemplateName(Y);
2944 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2945}
2946
Mike Stump11289f42009-09-09 15:08:12 +00002947TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00002948ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00002949 switch (Arg.getKind()) {
2950 case TemplateArgument::Null:
2951 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002952
Douglas Gregora8e02e72009-07-28 23:00:59 +00002953 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002954 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002955
Douglas Gregora8e02e72009-07-28 23:00:59 +00002956 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002957 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002958
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002959 case TemplateArgument::Template:
2960 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002961
2962 case TemplateArgument::TemplateExpansion:
2963 return TemplateArgument(getCanonicalTemplateName(
2964 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00002965 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002966
Douglas Gregora8e02e72009-07-28 23:00:59 +00002967 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002968 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002969 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002970
Douglas Gregora8e02e72009-07-28 23:00:59 +00002971 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002972 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002973
Douglas Gregora8e02e72009-07-28 23:00:59 +00002974 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00002975 if (Arg.pack_size() == 0)
2976 return Arg;
2977
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002978 TemplateArgument *CanonArgs
2979 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00002980 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002981 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002982 AEnd = Arg.pack_end();
2983 A != AEnd; (void)++A, ++Idx)
2984 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002985
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002986 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00002987 }
2988 }
2989
2990 // Silence GCC warning
2991 assert(false && "Unhandled template argument kind");
2992 return TemplateArgument();
2993}
2994
Douglas Gregor333489b2009-03-27 23:10:48 +00002995NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00002996ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00002997 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002998 return 0;
2999
3000 switch (NNS->getKind()) {
3001 case NestedNameSpecifier::Identifier:
3002 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003003 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003004 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3005 NNS->getAsIdentifier());
3006
3007 case NestedNameSpecifier::Namespace:
3008 // A namespace is canonical; build a nested-name-specifier with
3009 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003010 return NestedNameSpecifier::Create(*this, 0,
3011 NNS->getAsNamespace()->getOriginalNamespace());
3012
3013 case NestedNameSpecifier::NamespaceAlias:
3014 // A namespace is canonical; build a nested-name-specifier with
3015 // this namespace and no prefix.
3016 return NestedNameSpecifier::Create(*this, 0,
3017 NNS->getAsNamespaceAlias()->getNamespace()
3018 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003019
3020 case NestedNameSpecifier::TypeSpec:
3021 case NestedNameSpecifier::TypeSpecWithTemplate: {
3022 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003023
3024 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3025 // break it apart into its prefix and identifier, then reconsititute those
3026 // as the canonical nested-name-specifier. This is required to canonicalize
3027 // a dependent nested-name-specifier involving typedefs of dependent-name
3028 // types, e.g.,
3029 // typedef typename T::type T1;
3030 // typedef typename T1::type T2;
3031 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3032 NestedNameSpecifier *Prefix
3033 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3034 return NestedNameSpecifier::Create(*this, Prefix,
3035 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3036 }
3037
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003038 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003039 if (const DependentTemplateSpecializationType *DTST
3040 = T->getAs<DependentTemplateSpecializationType>()) {
3041 NestedNameSpecifier *Prefix
3042 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003043
3044 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3045 Prefix, DTST->getIdentifier(),
3046 DTST->getNumArgs(),
3047 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003048 T = getCanonicalType(T);
3049 }
3050
John McCall33ddac02011-01-19 10:06:00 +00003051 return NestedNameSpecifier::Create(*this, 0, false,
3052 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003053 }
3054
3055 case NestedNameSpecifier::Global:
3056 // The global specifier is canonical and unique.
3057 return NNS;
3058 }
3059
3060 // Required to silence a GCC warning
3061 return 0;
3062}
3063
Chris Lattner7adf0762008-08-04 07:31:14 +00003064
Jay Foad39c79802011-01-12 09:06:06 +00003065const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003066 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003067 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003068 // Handle the common positive case fast.
3069 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3070 return AT;
3071 }
Mike Stump11289f42009-09-09 15:08:12 +00003072
John McCall8ccfcb52009-09-24 19:53:00 +00003073 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003074 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003075 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003076
John McCall8ccfcb52009-09-24 19:53:00 +00003077 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003078 // implements C99 6.7.3p8: "If the specification of an array type includes
3079 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003080
Chris Lattner7adf0762008-08-04 07:31:14 +00003081 // If we get here, we either have type qualifiers on the type, or we have
3082 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003083 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003084
John McCall33ddac02011-01-19 10:06:00 +00003085 SplitQualType split = T.getSplitDesugaredType();
3086 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003087
Chris Lattner7adf0762008-08-04 07:31:14 +00003088 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003089 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3090 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003091 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003092
Chris Lattner7adf0762008-08-04 07:31:14 +00003093 // Otherwise, we have an array and we have qualifiers on it. Push the
3094 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003095 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003096
Chris Lattner7adf0762008-08-04 07:31:14 +00003097 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3098 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3099 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003100 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003101 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3102 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3103 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003104 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003105
Mike Stump11289f42009-09-09 15:08:12 +00003106 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003107 = dyn_cast<DependentSizedArrayType>(ATy))
3108 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003109 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003110 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003111 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003112 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003113 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003114
Chris Lattner7adf0762008-08-04 07:31:14 +00003115 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003116 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003117 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003118 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003119 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003120 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003121}
3122
Chris Lattnera21ad802008-04-02 05:18:44 +00003123/// getArrayDecayedType - Return the properly qualified result of decaying the
3124/// specified array type to a pointer. This operation is non-trivial when
3125/// handling typedefs etc. The canonical type of "T" must be an array type,
3126/// this returns a pointer to a properly qualified element of the array.
3127///
3128/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003129QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003130 // Get the element type with 'getAsArrayType' so that we don't lose any
3131 // typedefs in the element type of the array. This also handles propagation
3132 // of type qualifiers from the array type into the element type if present
3133 // (C99 6.7.3p8).
3134 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3135 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003136
Chris Lattner7adf0762008-08-04 07:31:14 +00003137 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003138
3139 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003140 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003141}
3142
John McCall33ddac02011-01-19 10:06:00 +00003143QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3144 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003145}
3146
John McCall33ddac02011-01-19 10:06:00 +00003147QualType ASTContext::getBaseElementType(QualType type) const {
3148 Qualifiers qs;
3149 while (true) {
3150 SplitQualType split = type.getSplitDesugaredType();
3151 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3152 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003153
John McCall33ddac02011-01-19 10:06:00 +00003154 type = array->getElementType();
3155 qs.addConsistentQualifiers(split.second);
3156 }
Mike Stump11289f42009-09-09 15:08:12 +00003157
John McCall33ddac02011-01-19 10:06:00 +00003158 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003159}
3160
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003161/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003162uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003163ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3164 uint64_t ElementCount = 1;
3165 do {
3166 ElementCount *= CA->getSize().getZExtValue();
3167 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3168 } while (CA);
3169 return ElementCount;
3170}
3171
Steve Naroff0af91202007-04-27 21:51:21 +00003172/// getFloatingRank - Return a relative rank for floating point types.
3173/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003174static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003175 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003176 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003177
John McCall9dd450b2009-09-21 23:43:11 +00003178 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3179 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003180 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003181 case BuiltinType::Float: return FloatRank;
3182 case BuiltinType::Double: return DoubleRank;
3183 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003184 }
3185}
3186
Mike Stump11289f42009-09-09 15:08:12 +00003187/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3188/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003189/// 'typeDomain' is a real floating point or complex type.
3190/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003191QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3192 QualType Domain) const {
3193 FloatingRank EltRank = getFloatingRank(Size);
3194 if (Domain->isComplexType()) {
3195 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003196 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003197 case FloatRank: return FloatComplexTy;
3198 case DoubleRank: return DoubleComplexTy;
3199 case LongDoubleRank: return LongDoubleComplexTy;
3200 }
Steve Naroff0af91202007-04-27 21:51:21 +00003201 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003202
3203 assert(Domain->isRealFloatingType() && "Unknown domain!");
3204 switch (EltRank) {
3205 default: assert(0 && "getFloatingRank(): illegal value for rank");
3206 case FloatRank: return FloatTy;
3207 case DoubleRank: return DoubleTy;
3208 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003209 }
Steve Naroffe4718892007-04-27 18:30:00 +00003210}
3211
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003212/// getFloatingTypeOrder - Compare the rank of the two specified floating
3213/// point types, ignoring the domain of the type (i.e. 'double' ==
3214/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003215/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003216int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003217 FloatingRank LHSR = getFloatingRank(LHS);
3218 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003219
Chris Lattnerb90739d2008-04-06 23:38:49 +00003220 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003221 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003222 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003223 return 1;
3224 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003225}
3226
Chris Lattner76a00cf2008-04-06 22:59:24 +00003227/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3228/// routine will assert if passed a built-in type that isn't an integer or enum,
3229/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003230unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003231 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003232 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003233 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003234
Chris Lattnerad3467e2010-12-25 23:25:43 +00003235 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3236 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003237 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3238
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003239 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3240 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3241
3242 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3243 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3244
Chris Lattner76a00cf2008-04-06 22:59:24 +00003245 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003246 default: assert(0 && "getIntegerRank(): not a built-in integer");
3247 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003248 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003249 case BuiltinType::Char_S:
3250 case BuiltinType::Char_U:
3251 case BuiltinType::SChar:
3252 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003253 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003254 case BuiltinType::Short:
3255 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003256 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003257 case BuiltinType::Int:
3258 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003259 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003260 case BuiltinType::Long:
3261 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003262 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003263 case BuiltinType::LongLong:
3264 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003265 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003266 case BuiltinType::Int128:
3267 case BuiltinType::UInt128:
3268 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003269 }
3270}
3271
Eli Friedman629ffb92009-08-20 04:21:42 +00003272/// \brief Whether this is a promotable bitfield reference according
3273/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3274///
3275/// \returns the type this bit-field will promote to, or NULL if no
3276/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003277QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003278 if (E->isTypeDependent() || E->isValueDependent())
3279 return QualType();
3280
Eli Friedman629ffb92009-08-20 04:21:42 +00003281 FieldDecl *Field = E->getBitField();
3282 if (!Field)
3283 return QualType();
3284
3285 QualType FT = Field->getType();
3286
3287 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3288 uint64_t BitWidth = BitWidthAP.getZExtValue();
3289 uint64_t IntSize = getTypeSize(IntTy);
3290 // GCC extension compatibility: if the bit-field size is less than or equal
3291 // to the size of int, it gets promoted no matter what its type is.
3292 // For instance, unsigned long bf : 4 gets promoted to signed int.
3293 if (BitWidth < IntSize)
3294 return IntTy;
3295
3296 if (BitWidth == IntSize)
3297 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3298
3299 // Types bigger than int are not subject to promotions, and therefore act
3300 // like the base type.
3301 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3302 // is ridiculous.
3303 return QualType();
3304}
3305
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003306/// getPromotedIntegerType - Returns the type that Promotable will
3307/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3308/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003309QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003310 assert(!Promotable.isNull());
3311 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003312 if (const EnumType *ET = Promotable->getAs<EnumType>())
3313 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003314 if (Promotable->isSignedIntegerType())
3315 return IntTy;
3316 uint64_t PromotableSize = getTypeSize(Promotable);
3317 uint64_t IntSize = getTypeSize(IntTy);
3318 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3319 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3320}
3321
Mike Stump11289f42009-09-09 15:08:12 +00003322/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003323/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003324/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003325int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003326 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3327 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003328 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003329
Chris Lattner76a00cf2008-04-06 22:59:24 +00003330 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3331 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003332
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003333 unsigned LHSRank = getIntegerRank(LHSC);
3334 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003335
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003336 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3337 if (LHSRank == RHSRank) return 0;
3338 return LHSRank > RHSRank ? 1 : -1;
3339 }
Mike Stump11289f42009-09-09 15:08:12 +00003340
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003341 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3342 if (LHSUnsigned) {
3343 // If the unsigned [LHS] type is larger, return it.
3344 if (LHSRank >= RHSRank)
3345 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003346
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003347 // If the signed type can represent all values of the unsigned type, it
3348 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003349 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003350 return -1;
3351 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003352
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003353 // If the unsigned [RHS] type is larger, return it.
3354 if (RHSRank >= LHSRank)
3355 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003356
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003357 // If the signed type can represent all values of the unsigned type, it
3358 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003359 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003360 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003361}
Anders Carlsson98f07902007-08-17 05:31:46 +00003362
Anders Carlsson6d417272009-11-14 21:45:58 +00003363static RecordDecl *
Jay Foad39c79802011-01-12 09:06:06 +00003364CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
Anders Carlsson6d417272009-11-14 21:45:58 +00003365 SourceLocation L, IdentifierInfo *Id) {
3366 if (Ctx.getLangOptions().CPlusPlus)
3367 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3368 else
3369 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3370}
3371
Mike Stump11289f42009-09-09 15:08:12 +00003372// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003373QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003374 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003375 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003376 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003377 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003378 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003379
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003380 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003381
Anders Carlsson98f07902007-08-17 05:31:46 +00003382 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003383 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003384 // int flags;
3385 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003386 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003387 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003388 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003389 FieldTypes[3] = LongTy;
3390
Anders Carlsson98f07902007-08-17 05:31:46 +00003391 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003392 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003393 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003394 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003395 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003396 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003397 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003398 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003399 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003400 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003401 }
3402
Douglas Gregord5058122010-02-11 01:19:42 +00003403 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003404 }
Mike Stump11289f42009-09-09 15:08:12 +00003405
Anders Carlsson98f07902007-08-17 05:31:46 +00003406 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003407}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003408
Douglas Gregor512b0772009-04-23 22:29:11 +00003409void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003410 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003411 assert(Rec && "Invalid CFConstantStringType");
3412 CFConstantStringTypeDecl = Rec->getDecl();
3413}
3414
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003415// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003416QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003417 if (!NSConstantStringTypeDecl) {
3418 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003419 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003420 &Idents.get("__builtin_NSString"));
3421 NSConstantStringTypeDecl->startDefinition();
3422
3423 QualType FieldTypes[3];
3424
3425 // const int *isa;
3426 FieldTypes[0] = getPointerType(IntTy.withConst());
3427 // const char *str;
3428 FieldTypes[1] = getPointerType(CharTy.withConst());
3429 // unsigned int length;
3430 FieldTypes[2] = UnsignedIntTy;
3431
3432 // Create fields
3433 for (unsigned i = 0; i < 3; ++i) {
3434 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003435 SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003436 SourceLocation(), 0,
3437 FieldTypes[i], /*TInfo=*/0,
3438 /*BitWidth=*/0,
3439 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003440 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003441 NSConstantStringTypeDecl->addDecl(Field);
3442 }
3443
3444 NSConstantStringTypeDecl->completeDefinition();
3445 }
3446
3447 return getTagDeclType(NSConstantStringTypeDecl);
3448}
3449
3450void ASTContext::setNSConstantStringType(QualType T) {
3451 const RecordType *Rec = T->getAs<RecordType>();
3452 assert(Rec && "Invalid NSConstantStringType");
3453 NSConstantStringTypeDecl = Rec->getDecl();
3454}
3455
Jay Foad39c79802011-01-12 09:06:06 +00003456QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003457 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003458 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003459 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003460 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003461 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003462
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003463 QualType FieldTypes[] = {
3464 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003465 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003466 getPointerType(UnsignedLongTy),
3467 getConstantArrayType(UnsignedLongTy,
3468 llvm::APInt(32, 5), ArrayType::Normal, 0)
3469 };
Mike Stump11289f42009-09-09 15:08:12 +00003470
Douglas Gregor91f84212008-12-11 16:49:14 +00003471 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003472 FieldDecl *Field = FieldDecl::Create(*this,
3473 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003474 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003475 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003476 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003477 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003478 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003479 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003480 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003481 }
Mike Stump11289f42009-09-09 15:08:12 +00003482
Douglas Gregord5058122010-02-11 01:19:42 +00003483 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003484 }
Mike Stump11289f42009-09-09 15:08:12 +00003485
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003486 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3487}
3488
Jay Foad39c79802011-01-12 09:06:06 +00003489QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003490 if (BlockDescriptorType)
3491 return getTagDeclType(BlockDescriptorType);
3492
3493 RecordDecl *T;
3494 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003495 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003496 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003497 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003498
3499 QualType FieldTypes[] = {
3500 UnsignedLongTy,
3501 UnsignedLongTy,
3502 };
3503
3504 const char *FieldNames[] = {
3505 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003506 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003507 };
3508
3509 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003510 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003511 SourceLocation(),
3512 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003513 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003514 /*BitWidth=*/0,
3515 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003516 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003517 T->addDecl(Field);
3518 }
3519
Douglas Gregord5058122010-02-11 01:19:42 +00003520 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003521
3522 BlockDescriptorType = T;
3523
3524 return getTagDeclType(BlockDescriptorType);
3525}
3526
3527void ASTContext::setBlockDescriptorType(QualType T) {
3528 const RecordType *Rec = T->getAs<RecordType>();
3529 assert(Rec && "Invalid BlockDescriptorType");
3530 BlockDescriptorType = Rec->getDecl();
3531}
3532
Jay Foad39c79802011-01-12 09:06:06 +00003533QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003534 if (BlockDescriptorExtendedType)
3535 return getTagDeclType(BlockDescriptorExtendedType);
3536
3537 RecordDecl *T;
3538 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003539 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003540 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003541 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003542
3543 QualType FieldTypes[] = {
3544 UnsignedLongTy,
3545 UnsignedLongTy,
3546 getPointerType(VoidPtrTy),
3547 getPointerType(VoidPtrTy)
3548 };
3549
3550 const char *FieldNames[] = {
3551 "reserved",
3552 "Size",
3553 "CopyFuncPtr",
3554 "DestroyFuncPtr"
3555 };
3556
3557 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003558 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003559 SourceLocation(),
3560 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003561 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003562 /*BitWidth=*/0,
3563 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003564 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003565 T->addDecl(Field);
3566 }
3567
Douglas Gregord5058122010-02-11 01:19:42 +00003568 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003569
3570 BlockDescriptorExtendedType = T;
3571
3572 return getTagDeclType(BlockDescriptorExtendedType);
3573}
3574
3575void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3576 const RecordType *Rec = T->getAs<RecordType>();
3577 assert(Rec && "Invalid BlockDescriptorType");
3578 BlockDescriptorExtendedType = Rec->getDecl();
3579}
3580
Jay Foad39c79802011-01-12 09:06:06 +00003581bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003582 if (Ty->isBlockPointerType())
3583 return true;
3584 if (isObjCNSObjectType(Ty))
3585 return true;
3586 if (Ty->isObjCObjectPointerType())
3587 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003588 if (getLangOptions().CPlusPlus) {
3589 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3590 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3591 return RD->hasConstCopyConstructor(*this);
3592
3593 }
3594 }
Mike Stump94967902009-10-21 18:16:27 +00003595 return false;
3596}
3597
Jay Foad39c79802011-01-12 09:06:06 +00003598QualType
3599ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003600 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003601 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003602 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003603 // unsigned int __flags;
3604 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003605 // void *__copy_helper; // as needed
3606 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003607 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003608 // } *
3609
Mike Stump94967902009-10-21 18:16:27 +00003610 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3611
3612 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003613 llvm::SmallString<36> Name;
3614 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3615 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003616 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003617 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003618 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003619 T->startDefinition();
3620 QualType Int32Ty = IntTy;
3621 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3622 QualType FieldTypes[] = {
3623 getPointerType(VoidPtrTy),
3624 getPointerType(getTagDeclType(T)),
3625 Int32Ty,
3626 Int32Ty,
3627 getPointerType(VoidPtrTy),
3628 getPointerType(VoidPtrTy),
3629 Ty
3630 };
3631
Daniel Dunbar56df9772010-08-17 22:39:59 +00003632 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003633 "__isa",
3634 "__forwarding",
3635 "__flags",
3636 "__size",
3637 "__copy_helper",
3638 "__destroy_helper",
3639 DeclName,
3640 };
3641
3642 for (size_t i = 0; i < 7; ++i) {
3643 if (!HasCopyAndDispose && i >=4 && i <= 5)
3644 continue;
3645 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003646 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003647 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003648 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003649 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003650 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003651 T->addDecl(Field);
3652 }
3653
Douglas Gregord5058122010-02-11 01:19:42 +00003654 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003655
3656 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003657}
3658
Douglas Gregor512b0772009-04-23 22:29:11 +00003659void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003660 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003661 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3662 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3663}
3664
Anders Carlsson18acd442007-10-29 06:33:42 +00003665// This returns true if a type has been typedefed to BOOL:
3666// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003667static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003668 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003669 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3670 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003671
Anders Carlssond8499822007-10-29 05:01:08 +00003672 return false;
3673}
3674
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003675/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003676/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003677CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003678 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003679
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003680 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003681 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003682 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003683 // Treat arrays as pointers, since that's how they're passed in.
3684 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003685 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003686 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003687}
3688
3689static inline
3690std::string charUnitsToString(const CharUnits &CU) {
3691 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003692}
3693
John McCall351762c2011-02-07 10:33:21 +00003694/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003695/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003696std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3697 std::string S;
3698
David Chisnall950a9512009-11-17 19:33:30 +00003699 const BlockDecl *Decl = Expr->getBlockDecl();
3700 QualType BlockTy =
3701 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3702 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003703 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003704 // Compute size of all parameters.
3705 // Start with computing size of a pointer in number of bytes.
3706 // FIXME: There might(should) be a better way of doing this computation!
3707 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003708 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3709 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003710 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003711 E = Decl->param_end(); PI != E; ++PI) {
3712 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003713 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003714 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003715 ParmOffset += sz;
3716 }
3717 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003718 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003719 // Block pointer and offset.
3720 S += "@?0";
3721 ParmOffset = PtrSize;
3722
3723 // Argument types.
3724 ParmOffset = PtrSize;
3725 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3726 Decl->param_end(); PI != E; ++PI) {
3727 ParmVarDecl *PVDecl = *PI;
3728 QualType PType = PVDecl->getOriginalType();
3729 if (const ArrayType *AT =
3730 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3731 // Use array's original type only if it has known number of
3732 // elements.
3733 if (!isa<ConstantArrayType>(AT))
3734 PType = PVDecl->getType();
3735 } else if (PType->isFunctionType())
3736 PType = PVDecl->getType();
3737 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003738 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003739 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003740 }
John McCall351762c2011-02-07 10:33:21 +00003741
3742 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003743}
3744
David Chisnall50e4eba2010-12-30 14:05:53 +00003745void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3746 std::string& S) {
3747 // Encode result type.
3748 getObjCEncodingForType(Decl->getResultType(), S);
3749 CharUnits ParmOffset;
3750 // Compute size of all parameters.
3751 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3752 E = Decl->param_end(); PI != E; ++PI) {
3753 QualType PType = (*PI)->getType();
3754 CharUnits sz = getObjCEncodingTypeSize(PType);
3755 assert (sz.isPositive() &&
3756 "getObjCEncodingForMethodDecl - Incomplete param type");
3757 ParmOffset += sz;
3758 }
3759 S += charUnitsToString(ParmOffset);
3760 ParmOffset = CharUnits::Zero();
3761
3762 // Argument types.
3763 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3764 E = Decl->param_end(); PI != E; ++PI) {
3765 ParmVarDecl *PVDecl = *PI;
3766 QualType PType = PVDecl->getOriginalType();
3767 if (const ArrayType *AT =
3768 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3769 // Use array's original type only if it has known number of
3770 // elements.
3771 if (!isa<ConstantArrayType>(AT))
3772 PType = PVDecl->getType();
3773 } else if (PType->isFunctionType())
3774 PType = PVDecl->getType();
3775 getObjCEncodingForType(PType, S);
3776 S += charUnitsToString(ParmOffset);
3777 ParmOffset += getObjCEncodingTypeSize(PType);
3778 }
3779}
3780
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003781/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003782/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003783void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003784 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003785 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003786 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003787 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003788 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003789 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003790 // Compute size of all parameters.
3791 // Start with computing size of a pointer in number of bytes.
3792 // FIXME: There might(should) be a better way of doing this computation!
3793 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003794 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003795 // The first two arguments (self and _cmd) are pointers; account for
3796 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003797 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003798 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003799 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003800 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003801 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003802 assert (sz.isPositive() &&
3803 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003804 ParmOffset += sz;
3805 }
Ken Dyck40775002010-01-11 17:06:35 +00003806 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003807 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003808 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003809
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003810 // Argument types.
3811 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003812 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003813 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003814 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003815 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003816 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003817 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3818 // Use array's original type only if it has known number of
3819 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003820 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003821 PType = PVDecl->getType();
3822 } else if (PType->isFunctionType())
3823 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003824 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003825 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003826 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003827 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003828 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003829 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003830 }
3831}
3832
Daniel Dunbar4932b362008-08-28 04:38:10 +00003833/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003834/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003835/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3836/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003837/// Property attributes are stored as a comma-delimited C string. The simple
3838/// attributes readonly and bycopy are encoded as single characters. The
3839/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3840/// encoded as single characters, followed by an identifier. Property types
3841/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003842/// these attributes are defined by the following enumeration:
3843/// @code
3844/// enum PropertyAttributes {
3845/// kPropertyReadOnly = 'R', // property is read-only.
3846/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3847/// kPropertyByref = '&', // property is a reference to the value last assigned
3848/// kPropertyDynamic = 'D', // property is dynamic
3849/// kPropertyGetter = 'G', // followed by getter selector name
3850/// kPropertySetter = 'S', // followed by setter selector name
3851/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3852/// kPropertyType = 't' // followed by old-style type encoding.
3853/// kPropertyWeak = 'W' // 'weak' property
3854/// kPropertyStrong = 'P' // property GC'able
3855/// kPropertyNonAtomic = 'N' // property non-atomic
3856/// };
3857/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003858void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003859 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003860 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003861 // Collect information from the property implementation decl(s).
3862 bool Dynamic = false;
3863 ObjCPropertyImplDecl *SynthesizePID = 0;
3864
3865 // FIXME: Duplicated code due to poor abstraction.
3866 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003867 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003868 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3869 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003870 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003871 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003872 ObjCPropertyImplDecl *PID = *i;
3873 if (PID->getPropertyDecl() == PD) {
3874 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3875 Dynamic = true;
3876 } else {
3877 SynthesizePID = PID;
3878 }
3879 }
3880 }
3881 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003882 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003883 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003884 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003885 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003886 ObjCPropertyImplDecl *PID = *i;
3887 if (PID->getPropertyDecl() == PD) {
3888 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3889 Dynamic = true;
3890 } else {
3891 SynthesizePID = PID;
3892 }
3893 }
Mike Stump11289f42009-09-09 15:08:12 +00003894 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003895 }
3896 }
3897
3898 // FIXME: This is not very efficient.
3899 S = "T";
3900
3901 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003902 // GCC has some special rules regarding encoding of properties which
3903 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003904 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003905 true /* outermost type */,
3906 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003907
3908 if (PD->isReadOnly()) {
3909 S += ",R";
3910 } else {
3911 switch (PD->getSetterKind()) {
3912 case ObjCPropertyDecl::Assign: break;
3913 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003914 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003915 }
3916 }
3917
3918 // It really isn't clear at all what this means, since properties
3919 // are "dynamic by default".
3920 if (Dynamic)
3921 S += ",D";
3922
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003923 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3924 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003925
Daniel Dunbar4932b362008-08-28 04:38:10 +00003926 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3927 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003928 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003929 }
3930
3931 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3932 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003933 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003934 }
3935
3936 if (SynthesizePID) {
3937 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3938 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003939 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003940 }
3941
3942 // FIXME: OBJCGC: weak & strong
3943}
3944
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003945/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003946/// Another legacy compatibility encoding: 32-bit longs are encoded as
3947/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003948/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3949///
3950void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003951 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003952 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00003953 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003954 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003955 else
Jay Foad39c79802011-01-12 09:06:06 +00003956 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003957 PointeeTy = IntTy;
3958 }
3959 }
3960}
3961
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003962void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00003963 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003964 // We follow the behavior of gcc, expanding structures which are
3965 // directly pointed to, and expanding embedded structures. Note that
3966 // these rules are sufficient to prevent recursive encoding of the
3967 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003968 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003969 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003970}
3971
David Chisnallb190a2c2010-06-04 01:10:52 +00003972static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3973 switch (T->getAs<BuiltinType>()->getKind()) {
3974 default: assert(0 && "Unhandled builtin type kind");
3975 case BuiltinType::Void: return 'v';
3976 case BuiltinType::Bool: return 'B';
3977 case BuiltinType::Char_U:
3978 case BuiltinType::UChar: return 'C';
3979 case BuiltinType::UShort: return 'S';
3980 case BuiltinType::UInt: return 'I';
3981 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00003982 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003983 case BuiltinType::UInt128: return 'T';
3984 case BuiltinType::ULongLong: return 'Q';
3985 case BuiltinType::Char_S:
3986 case BuiltinType::SChar: return 'c';
3987 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00003988 case BuiltinType::WChar_S:
3989 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00003990 case BuiltinType::Int: return 'i';
3991 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00003992 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003993 case BuiltinType::LongLong: return 'q';
3994 case BuiltinType::Int128: return 't';
3995 case BuiltinType::Float: return 'f';
3996 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00003997 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00003998 }
3999}
4000
Jay Foad39c79802011-01-12 09:06:06 +00004001static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004002 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004003 const Expr *E = FD->getBitWidth();
4004 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004005 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004006 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4007 // The GNU runtime requires more information; bitfields are encoded as b,
4008 // then the offset (in bits) of the first element, then the type of the
4009 // bitfield, then the size in bits. For example, in this structure:
4010 //
4011 // struct
4012 // {
4013 // int integer;
4014 // int flags:2;
4015 // };
4016 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4017 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4018 // information is not especially sensible, but we're stuck with it for
4019 // compatibility with GCC, although providing it breaks anything that
4020 // actually uses runtime introspection and wants to work on both runtimes...
4021 if (!Ctx->getLangOptions().NeXTRuntime) {
4022 const RecordDecl *RD = FD->getParent();
4023 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4024 // FIXME: This same linear search is also used in ExprConstant - it might
4025 // be better if the FieldDecl stored its offset. We'd be increasing the
4026 // size of the object slightly, but saving some time every time it is used.
4027 unsigned i = 0;
4028 for (RecordDecl::field_iterator Field = RD->field_begin(),
4029 FieldEnd = RD->field_end();
4030 Field != FieldEnd; (void)++Field, ++i) {
4031 if (*Field == FD)
4032 break;
4033 }
4034 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004035 if (T->isEnumeralType())
4036 S += 'i';
4037 else
Jay Foad39c79802011-01-12 09:06:06 +00004038 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004039 }
4040 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004041 S += llvm::utostr(N);
4042}
4043
Daniel Dunbar07d07852009-10-18 21:17:35 +00004044// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004045void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4046 bool ExpandPointedToStructures,
4047 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004048 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004049 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00004050 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004051 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004052 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004053 return EncodeBitField(this, S, T, FD);
4054 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004055 return;
4056 }
Mike Stump11289f42009-09-09 15:08:12 +00004057
John McCall9dd450b2009-09-21 23:43:11 +00004058 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004059 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004060 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004061 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004062 return;
4063 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004064
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004065 // encoding for pointer or r3eference types.
4066 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004067 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004068 if (PT->isObjCSelType()) {
4069 S += ':';
4070 return;
4071 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004072 PointeeTy = PT->getPointeeType();
4073 }
4074 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4075 PointeeTy = RT->getPointeeType();
4076 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004077 bool isReadOnly = false;
4078 // For historical/compatibility reasons, the read-only qualifier of the
4079 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4080 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004081 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004082 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004083 if (OutermostType && T.isConstQualified()) {
4084 isReadOnly = true;
4085 S += 'r';
4086 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004087 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004088 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004089 while (P->getAs<PointerType>())
4090 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004091 if (P.isConstQualified()) {
4092 isReadOnly = true;
4093 S += 'r';
4094 }
4095 }
4096 if (isReadOnly) {
4097 // Another legacy compatibility encoding. Some ObjC qualifier and type
4098 // combinations need to be rearranged.
4099 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004100 if (llvm::StringRef(S).endswith("nr"))
4101 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004102 }
Mike Stump11289f42009-09-09 15:08:12 +00004103
Anders Carlssond8499822007-10-29 05:01:08 +00004104 if (PointeeTy->isCharType()) {
4105 // char pointer types should be encoded as '*' unless it is a
4106 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004107 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004108 S += '*';
4109 return;
4110 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004111 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004112 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4113 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4114 S += '#';
4115 return;
4116 }
4117 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4118 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4119 S += '@';
4120 return;
4121 }
4122 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004123 }
Anders Carlssond8499822007-10-29 05:01:08 +00004124 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004125 getLegacyIntegralTypeEncoding(PointeeTy);
4126
Mike Stump11289f42009-09-09 15:08:12 +00004127 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004128 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004129 return;
4130 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004131
Chris Lattnere7cabb92009-07-13 00:10:46 +00004132 if (const ArrayType *AT =
4133 // Ignore type qualifiers etc.
4134 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004135 if (isa<IncompleteArrayType>(AT)) {
4136 // Incomplete arrays are encoded as a pointer to the array element.
4137 S += '^';
4138
Mike Stump11289f42009-09-09 15:08:12 +00004139 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004140 false, ExpandStructures, FD);
4141 } else {
4142 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004143
Anders Carlssond05f44b2009-02-22 01:38:57 +00004144 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4145 S += llvm::utostr(CAT->getSize().getZExtValue());
4146 else {
4147 //Variable length arrays are encoded as a regular array with 0 elements.
4148 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4149 S += '0';
4150 }
Mike Stump11289f42009-09-09 15:08:12 +00004151
4152 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004153 false, ExpandStructures, FD);
4154 S += ']';
4155 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004156 return;
4157 }
Mike Stump11289f42009-09-09 15:08:12 +00004158
John McCall9dd450b2009-09-21 23:43:11 +00004159 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004160 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004161 return;
4162 }
Mike Stump11289f42009-09-09 15:08:12 +00004163
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004164 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004165 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004166 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004167 // Anonymous structures print as '?'
4168 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4169 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004170 if (ClassTemplateSpecializationDecl *Spec
4171 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4172 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4173 std::string TemplateArgsStr
4174 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004175 TemplateArgs.data(),
4176 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004177 (*this).PrintingPolicy);
4178
4179 S += TemplateArgsStr;
4180 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004181 } else {
4182 S += '?';
4183 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004184 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004185 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004186 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4187 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004188 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004189 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004190 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004191 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004192 S += '"';
4193 }
Mike Stump11289f42009-09-09 15:08:12 +00004194
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004195 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004196 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004197 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004198 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004199 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004200 QualType qt = Field->getType();
4201 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004202 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004203 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004204 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004205 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004206 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004207 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004208 return;
4209 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004210
Chris Lattnere7cabb92009-07-13 00:10:46 +00004211 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004212 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004213 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004214 else
4215 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004216 return;
4217 }
Mike Stump11289f42009-09-09 15:08:12 +00004218
Chris Lattnere7cabb92009-07-13 00:10:46 +00004219 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004220 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004221 return;
4222 }
Mike Stump11289f42009-09-09 15:08:12 +00004223
John McCall8b07ec22010-05-15 11:32:37 +00004224 // Ignore protocol qualifiers when mangling at this level.
4225 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4226 T = OT->getBaseType();
4227
John McCall8ccfcb52009-09-24 19:53:00 +00004228 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004229 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004230 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004231 S += '{';
4232 const IdentifierInfo *II = OI->getIdentifier();
4233 S += II->getName();
4234 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004235 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4236 DeepCollectObjCIvars(OI, true, Ivars);
4237 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4238 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4239 if (Field->isBitField())
4240 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004241 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004242 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004243 }
4244 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004245 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004246 }
Mike Stump11289f42009-09-09 15:08:12 +00004247
John McCall9dd450b2009-09-21 23:43:11 +00004248 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004249 if (OPT->isObjCIdType()) {
4250 S += '@';
4251 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004252 }
Mike Stump11289f42009-09-09 15:08:12 +00004253
Steve Narofff0c86112009-10-28 22:03:49 +00004254 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4255 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4256 // Since this is a binary compatibility issue, need to consult with runtime
4257 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004258 S += '#';
4259 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004260 }
Mike Stump11289f42009-09-09 15:08:12 +00004261
Chris Lattnere7cabb92009-07-13 00:10:46 +00004262 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004263 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004264 ExpandPointedToStructures,
4265 ExpandStructures, FD);
4266 if (FD || EncodingProperty) {
4267 // Note that we do extended encoding of protocol qualifer list
4268 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004269 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004270 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4271 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004272 S += '<';
4273 S += (*I)->getNameAsString();
4274 S += '>';
4275 }
4276 S += '"';
4277 }
4278 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004279 }
Mike Stump11289f42009-09-09 15:08:12 +00004280
Chris Lattnere7cabb92009-07-13 00:10:46 +00004281 QualType PointeeTy = OPT->getPointeeType();
4282 if (!EncodingProperty &&
4283 isa<TypedefType>(PointeeTy.getTypePtr())) {
4284 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004285 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004286 // {...};
4287 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004288 getObjCEncodingForTypeImpl(PointeeTy, S,
4289 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004290 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004291 return;
4292 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004293
4294 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004295 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004296 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004297 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004298 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4299 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004300 S += '<';
4301 S += (*I)->getNameAsString();
4302 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004303 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004304 S += '"';
4305 }
4306 return;
4307 }
Mike Stump11289f42009-09-09 15:08:12 +00004308
John McCalla9e6e8d2010-05-17 23:56:34 +00004309 // gcc just blithely ignores member pointers.
4310 // TODO: maybe there should be a mangling for these
4311 if (T->getAs<MemberPointerType>())
4312 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004313
4314 if (T->isVectorType()) {
4315 // This matches gcc's encoding, even though technically it is
4316 // insufficient.
4317 // FIXME. We should do a better job than gcc.
4318 return;
4319 }
4320
Chris Lattnere7cabb92009-07-13 00:10:46 +00004321 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004322}
4323
Mike Stump11289f42009-09-09 15:08:12 +00004324void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004325 std::string& S) const {
4326 if (QT & Decl::OBJC_TQ_In)
4327 S += 'n';
4328 if (QT & Decl::OBJC_TQ_Inout)
4329 S += 'N';
4330 if (QT & Decl::OBJC_TQ_Out)
4331 S += 'o';
4332 if (QT & Decl::OBJC_TQ_Bycopy)
4333 S += 'O';
4334 if (QT & Decl::OBJC_TQ_Byref)
4335 S += 'R';
4336 if (QT & Decl::OBJC_TQ_Oneway)
4337 S += 'V';
4338}
4339
Chris Lattnere7cabb92009-07-13 00:10:46 +00004340void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004341 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004342
Anders Carlsson87c149b2007-10-11 01:00:40 +00004343 BuiltinVaListType = T;
4344}
4345
Chris Lattnere7cabb92009-07-13 00:10:46 +00004346void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004347 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004348}
4349
Chris Lattnere7cabb92009-07-13 00:10:46 +00004350void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004351 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004352}
4353
Chris Lattnere7cabb92009-07-13 00:10:46 +00004354void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004355 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004356}
4357
Chris Lattnere7cabb92009-07-13 00:10:46 +00004358void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004359 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004360}
4361
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004362void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004363 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004364 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004365
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004366 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004367}
4368
John McCalld28ae272009-12-02 08:04:21 +00004369/// \brief Retrieve the template name that corresponds to a non-empty
4370/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004371TemplateName
4372ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4373 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004374 unsigned size = End - Begin;
4375 assert(size > 1 && "set is not overloaded!");
4376
4377 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4378 size * sizeof(FunctionTemplateDecl*));
4379 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4380
4381 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004382 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004383 NamedDecl *D = *I;
4384 assert(isa<FunctionTemplateDecl>(D) ||
4385 (isa<UsingShadowDecl>(D) &&
4386 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4387 *Storage++ = D;
4388 }
4389
4390 return TemplateName(OT);
4391}
4392
Douglas Gregordc572a32009-03-30 22:58:21 +00004393/// \brief Retrieve the template name that represents a qualified
4394/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004395TemplateName
4396ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4397 bool TemplateKeyword,
4398 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004399 assert(NNS && "Missing nested-name-specifier in qualified template name");
4400
Douglas Gregorc42075a2010-02-04 18:10:26 +00004401 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004402 llvm::FoldingSetNodeID ID;
4403 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4404
4405 void *InsertPos = 0;
4406 QualifiedTemplateName *QTN =
4407 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4408 if (!QTN) {
4409 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4410 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4411 }
4412
4413 return TemplateName(QTN);
4414}
4415
4416/// \brief Retrieve the template name that represents a dependent
4417/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004418TemplateName
4419ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4420 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004421 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004422 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004423
4424 llvm::FoldingSetNodeID ID;
4425 DependentTemplateName::Profile(ID, NNS, Name);
4426
4427 void *InsertPos = 0;
4428 DependentTemplateName *QTN =
4429 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4430
4431 if (QTN)
4432 return TemplateName(QTN);
4433
4434 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4435 if (CanonNNS == NNS) {
4436 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4437 } else {
4438 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4439 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004440 DependentTemplateName *CheckQTN =
4441 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4442 assert(!CheckQTN && "Dependent type name canonicalization broken");
4443 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004444 }
4445
4446 DependentTemplateNames.InsertNode(QTN, InsertPos);
4447 return TemplateName(QTN);
4448}
4449
Douglas Gregor71395fa2009-11-04 00:56:37 +00004450/// \brief Retrieve the template name that represents a dependent
4451/// template name such as \c MetaFun::template operator+.
4452TemplateName
4453ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004454 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004455 assert((!NNS || NNS->isDependent()) &&
4456 "Nested name specifier must be dependent");
4457
4458 llvm::FoldingSetNodeID ID;
4459 DependentTemplateName::Profile(ID, NNS, Operator);
4460
4461 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004462 DependentTemplateName *QTN
4463 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004464
4465 if (QTN)
4466 return TemplateName(QTN);
4467
4468 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4469 if (CanonNNS == NNS) {
4470 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4471 } else {
4472 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4473 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004474
4475 DependentTemplateName *CheckQTN
4476 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4477 assert(!CheckQTN && "Dependent template name canonicalization broken");
4478 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004479 }
4480
4481 DependentTemplateNames.InsertNode(QTN, InsertPos);
4482 return TemplateName(QTN);
4483}
4484
Douglas Gregor5590be02011-01-15 06:45:20 +00004485TemplateName
4486ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4487 const TemplateArgument &ArgPack) const {
4488 ASTContext &Self = const_cast<ASTContext &>(*this);
4489 llvm::FoldingSetNodeID ID;
4490 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4491
4492 void *InsertPos = 0;
4493 SubstTemplateTemplateParmPackStorage *Subst
4494 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4495
4496 if (!Subst) {
4497 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4498 ArgPack.pack_size(),
4499 ArgPack.pack_begin());
4500 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4501 }
4502
4503 return TemplateName(Subst);
4504}
4505
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004506/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004507/// TargetInfo, produce the corresponding type. The unsigned @p Type
4508/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004509CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004510 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004511 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004512 case TargetInfo::SignedShort: return ShortTy;
4513 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4514 case TargetInfo::SignedInt: return IntTy;
4515 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4516 case TargetInfo::SignedLong: return LongTy;
4517 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4518 case TargetInfo::SignedLongLong: return LongLongTy;
4519 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4520 }
4521
4522 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004523 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004524}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004525
4526//===----------------------------------------------------------------------===//
4527// Type Predicates.
4528//===----------------------------------------------------------------------===//
4529
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004530/// isObjCNSObjectType - Return true if this is an NSObject object using
4531/// NSObject attribute on a c-style pointer type.
4532/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004533/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004534///
4535bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCall424cec92011-01-19 06:33:43 +00004536 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004537 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004538 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004539 return true;
4540 }
Mike Stump11289f42009-09-09 15:08:12 +00004541 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004542}
4543
Fariborz Jahanian96207692009-02-18 21:49:28 +00004544/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4545/// garbage collection attribute.
4546///
John McCall553d45a2011-01-12 00:34:59 +00004547Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4548 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4549 return Qualifiers::GCNone;
4550
4551 assert(getLangOptions().ObjC1);
4552 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4553
4554 // Default behaviour under objective-C's gc is for ObjC pointers
4555 // (or pointers to them) be treated as though they were declared
4556 // as __strong.
4557 if (GCAttrs == Qualifiers::GCNone) {
4558 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4559 return Qualifiers::Strong;
4560 else if (Ty->isPointerType())
4561 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4562 } else {
4563 // It's not valid to set GC attributes on anything that isn't a
4564 // pointer.
4565#ifndef NDEBUG
4566 QualType CT = Ty->getCanonicalTypeInternal();
4567 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4568 CT = AT->getElementType();
4569 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4570#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004571 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004572 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004573}
4574
Chris Lattner49af6a42008-04-07 06:51:04 +00004575//===----------------------------------------------------------------------===//
4576// Type Compatibility Testing
4577//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004578
Mike Stump11289f42009-09-09 15:08:12 +00004579/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004580/// compatible.
4581static bool areCompatVectorTypes(const VectorType *LHS,
4582 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004583 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004584 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004585 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004586}
4587
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004588bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4589 QualType SecondVec) {
4590 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4591 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4592
4593 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4594 return true;
4595
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004596 // Treat Neon vector types and most AltiVec vector types as if they are the
4597 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004598 const VectorType *First = FirstVec->getAs<VectorType>();
4599 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004600 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004601 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004602 First->getVectorKind() != VectorType::AltiVecPixel &&
4603 First->getVectorKind() != VectorType::AltiVecBool &&
4604 Second->getVectorKind() != VectorType::AltiVecPixel &&
4605 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004606 return true;
4607
4608 return false;
4609}
4610
Steve Naroff8e6aee52009-07-23 01:01:38 +00004611//===----------------------------------------------------------------------===//
4612// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4613//===----------------------------------------------------------------------===//
4614
4615/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4616/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004617bool
4618ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4619 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004620 if (lProto == rProto)
4621 return true;
4622 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4623 E = rProto->protocol_end(); PI != E; ++PI)
4624 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4625 return true;
4626 return false;
4627}
4628
Steve Naroff8e6aee52009-07-23 01:01:38 +00004629/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4630/// return true if lhs's protocols conform to rhs's protocol; false
4631/// otherwise.
4632bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4633 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4634 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4635 return false;
4636}
4637
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004638/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4639/// Class<p1, ...>.
4640bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4641 QualType rhs) {
4642 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4643 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4644 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4645
4646 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4647 E = lhsQID->qual_end(); I != E; ++I) {
4648 bool match = false;
4649 ObjCProtocolDecl *lhsProto = *I;
4650 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4651 E = rhsOPT->qual_end(); J != E; ++J) {
4652 ObjCProtocolDecl *rhsProto = *J;
4653 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4654 match = true;
4655 break;
4656 }
4657 }
4658 if (!match)
4659 return false;
4660 }
4661 return true;
4662}
4663
Steve Naroff8e6aee52009-07-23 01:01:38 +00004664/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4665/// ObjCQualifiedIDType.
4666bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4667 bool compare) {
4668 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004669 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004670 lhs->isObjCIdType() || lhs->isObjCClassType())
4671 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004672 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004673 rhs->isObjCIdType() || rhs->isObjCClassType())
4674 return true;
4675
4676 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004677 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004678
Steve Naroff8e6aee52009-07-23 01:01:38 +00004679 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004680
Steve Naroff8e6aee52009-07-23 01:01:38 +00004681 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004682 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004683 // make sure we check the class hierarchy.
4684 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4685 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4686 E = lhsQID->qual_end(); I != E; ++I) {
4687 // when comparing an id<P> on lhs with a static type on rhs,
4688 // see if static class implements all of id's protocols, directly or
4689 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004690 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004691 return false;
4692 }
4693 }
4694 // If there are no qualifiers and no interface, we have an 'id'.
4695 return true;
4696 }
Mike Stump11289f42009-09-09 15:08:12 +00004697 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004698 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4699 E = lhsQID->qual_end(); I != E; ++I) {
4700 ObjCProtocolDecl *lhsProto = *I;
4701 bool match = false;
4702
4703 // when comparing an id<P> on lhs with a static type on rhs,
4704 // see if static class implements all of id's protocols, directly or
4705 // through its super class and categories.
4706 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4707 E = rhsOPT->qual_end(); J != E; ++J) {
4708 ObjCProtocolDecl *rhsProto = *J;
4709 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4710 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4711 match = true;
4712 break;
4713 }
4714 }
Mike Stump11289f42009-09-09 15:08:12 +00004715 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004716 // make sure we check the class hierarchy.
4717 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4718 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4719 E = lhsQID->qual_end(); I != E; ++I) {
4720 // when comparing an id<P> on lhs with a static type on rhs,
4721 // see if static class implements all of id's protocols, directly or
4722 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004723 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004724 match = true;
4725 break;
4726 }
4727 }
4728 }
4729 if (!match)
4730 return false;
4731 }
Mike Stump11289f42009-09-09 15:08:12 +00004732
Steve Naroff8e6aee52009-07-23 01:01:38 +00004733 return true;
4734 }
Mike Stump11289f42009-09-09 15:08:12 +00004735
Steve Naroff8e6aee52009-07-23 01:01:38 +00004736 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4737 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4738
Mike Stump11289f42009-09-09 15:08:12 +00004739 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004740 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004741 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004742 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4743 E = lhsOPT->qual_end(); I != E; ++I) {
4744 ObjCProtocolDecl *lhsProto = *I;
4745 bool match = false;
4746
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004747 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004748 // see if static class implements all of id's protocols, directly or
4749 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004750 // First, lhs protocols in the qualifier list must be found, direct
4751 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004752 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4753 E = rhsQID->qual_end(); J != E; ++J) {
4754 ObjCProtocolDecl *rhsProto = *J;
4755 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4756 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4757 match = true;
4758 break;
4759 }
4760 }
4761 if (!match)
4762 return false;
4763 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004764
4765 // Static class's protocols, or its super class or category protocols
4766 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4767 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4768 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4769 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4770 // This is rather dubious but matches gcc's behavior. If lhs has
4771 // no type qualifier and its class has no static protocol(s)
4772 // assume that it is mismatch.
4773 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4774 return false;
4775 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4776 LHSInheritedProtocols.begin(),
4777 E = LHSInheritedProtocols.end(); I != E; ++I) {
4778 bool match = false;
4779 ObjCProtocolDecl *lhsProto = (*I);
4780 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4781 E = rhsQID->qual_end(); J != E; ++J) {
4782 ObjCProtocolDecl *rhsProto = *J;
4783 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4784 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4785 match = true;
4786 break;
4787 }
4788 }
4789 if (!match)
4790 return false;
4791 }
4792 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004793 return true;
4794 }
4795 return false;
4796}
4797
Eli Friedman47f77112008-08-22 00:56:42 +00004798/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004799/// compatible for assignment from RHS to LHS. This handles validation of any
4800/// protocol qualifiers on the LHS or RHS.
4801///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004802bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4803 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004804 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4805 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4806
Steve Naroff1329fa02009-07-15 18:40:39 +00004807 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004808 if (LHS->isObjCUnqualifiedIdOrClass() ||
4809 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004810 return true;
4811
John McCall8b07ec22010-05-15 11:32:37 +00004812 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004813 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4814 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004815 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004816
4817 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4818 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4819 QualType(RHSOPT,0));
4820
John McCall8b07ec22010-05-15 11:32:37 +00004821 // If we have 2 user-defined types, fall into that path.
4822 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004823 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004824
Steve Naroff8e6aee52009-07-23 01:01:38 +00004825 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004826}
4827
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004828/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4829/// for providing type-safty for objective-c pointers used to pass/return
4830/// arguments in block literals. When passed as arguments, passing 'A*' where
4831/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4832/// not OK. For the return type, the opposite is not OK.
4833bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4834 const ObjCObjectPointerType *LHSOPT,
4835 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004836 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004837 return true;
4838
4839 if (LHSOPT->isObjCBuiltinType()) {
4840 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4841 }
4842
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004843 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004844 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4845 QualType(RHSOPT,0),
4846 false);
4847
4848 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4849 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4850 if (LHS && RHS) { // We have 2 user-defined types.
4851 if (LHS != RHS) {
4852 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4853 return false;
4854 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4855 return true;
4856 }
4857 else
4858 return true;
4859 }
4860 return false;
4861}
4862
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004863/// getIntersectionOfProtocols - This routine finds the intersection of set
4864/// of protocols inherited from two distinct objective-c pointer objects.
4865/// It is used to build composite qualifier list of the composite type of
4866/// the conditional expression involving two objective-c pointer objects.
4867static
4868void getIntersectionOfProtocols(ASTContext &Context,
4869 const ObjCObjectPointerType *LHSOPT,
4870 const ObjCObjectPointerType *RHSOPT,
4871 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4872
John McCall8b07ec22010-05-15 11:32:37 +00004873 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4874 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4875 assert(LHS->getInterface() && "LHS must have an interface base");
4876 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004877
4878 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4879 unsigned LHSNumProtocols = LHS->getNumProtocols();
4880 if (LHSNumProtocols > 0)
4881 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4882 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004883 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004884 Context.CollectInheritedProtocols(LHS->getInterface(),
4885 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004886 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4887 LHSInheritedProtocols.end());
4888 }
4889
4890 unsigned RHSNumProtocols = RHS->getNumProtocols();
4891 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004892 ObjCProtocolDecl **RHSProtocols =
4893 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004894 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4895 if (InheritedProtocolSet.count(RHSProtocols[i]))
4896 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4897 }
4898 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004899 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004900 Context.CollectInheritedProtocols(RHS->getInterface(),
4901 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004902 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4903 RHSInheritedProtocols.begin(),
4904 E = RHSInheritedProtocols.end(); I != E; ++I)
4905 if (InheritedProtocolSet.count((*I)))
4906 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004907 }
4908}
4909
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004910/// areCommonBaseCompatible - Returns common base class of the two classes if
4911/// one found. Note that this is O'2 algorithm. But it will be called as the
4912/// last type comparison in a ?-exp of ObjC pointer types before a
4913/// warning is issued. So, its invokation is extremely rare.
4914QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004915 const ObjCObjectPointerType *Lptr,
4916 const ObjCObjectPointerType *Rptr) {
4917 const ObjCObjectType *LHS = Lptr->getObjectType();
4918 const ObjCObjectType *RHS = Rptr->getObjectType();
4919 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4920 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4921 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004922 return QualType();
4923
John McCall8b07ec22010-05-15 11:32:37 +00004924 while ((LDecl = LDecl->getSuperClass())) {
4925 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004926 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004927 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4928 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4929
4930 QualType Result = QualType(LHS, 0);
4931 if (!Protocols.empty())
4932 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4933 Result = getObjCObjectPointerType(Result);
4934 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004935 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004936 }
4937
4938 return QualType();
4939}
4940
John McCall8b07ec22010-05-15 11:32:37 +00004941bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4942 const ObjCObjectType *RHS) {
4943 assert(LHS->getInterface() && "LHS is not an interface type");
4944 assert(RHS->getInterface() && "RHS is not an interface type");
4945
Chris Lattner49af6a42008-04-07 06:51:04 +00004946 // Verify that the base decls are compatible: the RHS must be a subclass of
4947 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004948 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004949 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004950
Chris Lattner49af6a42008-04-07 06:51:04 +00004951 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4952 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004953 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004954 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004955
Chris Lattner49af6a42008-04-07 06:51:04 +00004956 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4957 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004958 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004959 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004960
John McCall8b07ec22010-05-15 11:32:37 +00004961 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4962 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004963 LHSPI != LHSPE; LHSPI++) {
4964 bool RHSImplementsProtocol = false;
4965
4966 // If the RHS doesn't implement the protocol on the left, the types
4967 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004968 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4969 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004970 RHSPI != RHSPE; RHSPI++) {
4971 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004972 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004973 break;
4974 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004975 }
4976 // FIXME: For better diagnostics, consider passing back the protocol name.
4977 if (!RHSImplementsProtocol)
4978 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004979 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004980 // The RHS implements all protocols listed on the LHS.
4981 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004982}
4983
Steve Naroffb7605152009-02-12 17:52:19 +00004984bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4985 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004986 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4987 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004988
Steve Naroff7cae42b2009-07-10 23:34:53 +00004989 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004990 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004991
4992 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4993 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004994}
4995
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004996bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4997 return canAssignObjCInterfaces(
4998 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4999 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5000}
5001
Mike Stump11289f42009-09-09 15:08:12 +00005002/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005003/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005004/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005005/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005006bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5007 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005008 if (getLangOptions().CPlusPlus)
5009 return hasSameType(LHS, RHS);
5010
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005011 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005012}
5013
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005014bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5015 return !mergeTypes(LHS, RHS, true).isNull();
5016}
5017
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005018/// mergeTransparentUnionType - if T is a transparent union type and a member
5019/// of T is compatible with SubType, return the merged type, else return
5020/// QualType()
5021QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5022 bool OfBlockPointer,
5023 bool Unqualified) {
5024 if (const RecordType *UT = T->getAsUnionType()) {
5025 RecordDecl *UD = UT->getDecl();
5026 if (UD->hasAttr<TransparentUnionAttr>()) {
5027 for (RecordDecl::field_iterator it = UD->field_begin(),
5028 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005029 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005030 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5031 if (!MT.isNull())
5032 return MT;
5033 }
5034 }
5035 }
5036
5037 return QualType();
5038}
5039
5040/// mergeFunctionArgumentTypes - merge two types which appear as function
5041/// argument types
5042QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5043 bool OfBlockPointer,
5044 bool Unqualified) {
5045 // GNU extension: two types are compatible if they appear as a function
5046 // argument, one of the types is a transparent union type and the other
5047 // type is compatible with a union member
5048 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5049 Unqualified);
5050 if (!lmerge.isNull())
5051 return lmerge;
5052
5053 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5054 Unqualified);
5055 if (!rmerge.isNull())
5056 return rmerge;
5057
5058 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5059}
5060
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005061QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005062 bool OfBlockPointer,
5063 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005064 const FunctionType *lbase = lhs->getAs<FunctionType>();
5065 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005066 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5067 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005068 bool allLTypes = true;
5069 bool allRTypes = true;
5070
5071 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005072 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005073 if (OfBlockPointer) {
5074 QualType RHS = rbase->getResultType();
5075 QualType LHS = lbase->getResultType();
5076 bool UnqualifiedResult = Unqualified;
5077 if (!UnqualifiedResult)
5078 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
5079 retType = mergeTypes(RHS, LHS, true, UnqualifiedResult);
5080 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005081 else
John McCall8c6b56f2010-12-15 01:06:38 +00005082 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5083 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005084 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005085
5086 if (Unqualified)
5087 retType = retType.getUnqualifiedType();
5088
5089 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5090 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5091 if (Unqualified) {
5092 LRetType = LRetType.getUnqualifiedType();
5093 RRetType = RRetType.getUnqualifiedType();
5094 }
5095
5096 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005097 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005098 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005099 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005100
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005101 // FIXME: double check this
5102 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5103 // rbase->getRegParmAttr() != 0 &&
5104 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005105 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5106 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005107
Douglas Gregor8c940862010-01-18 17:14:39 +00005108 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005109 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005110 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005111
John McCall8c6b56f2010-12-15 01:06:38 +00005112 // Regparm is part of the calling convention.
5113 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5114 return QualType();
5115
5116 // It's noreturn if either type is.
5117 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5118 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5119 if (NoReturn != lbaseInfo.getNoReturn())
5120 allLTypes = false;
5121 if (NoReturn != rbaseInfo.getNoReturn())
5122 allRTypes = false;
5123
5124 FunctionType::ExtInfo einfo(NoReturn,
5125 lbaseInfo.getRegParm(),
5126 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00005127
Eli Friedman47f77112008-08-22 00:56:42 +00005128 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005129 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5130 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005131 unsigned lproto_nargs = lproto->getNumArgs();
5132 unsigned rproto_nargs = rproto->getNumArgs();
5133
5134 // Compatible functions must have the same number of arguments
5135 if (lproto_nargs != rproto_nargs)
5136 return QualType();
5137
5138 // Variadic and non-variadic functions aren't compatible
5139 if (lproto->isVariadic() != rproto->isVariadic())
5140 return QualType();
5141
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005142 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5143 return QualType();
5144
Eli Friedman47f77112008-08-22 00:56:42 +00005145 // Check argument compatibility
5146 llvm::SmallVector<QualType, 10> types;
5147 for (unsigned i = 0; i < lproto_nargs; i++) {
5148 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5149 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005150 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5151 OfBlockPointer,
5152 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005153 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005154
5155 if (Unqualified)
5156 argtype = argtype.getUnqualifiedType();
5157
Eli Friedman47f77112008-08-22 00:56:42 +00005158 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005159 if (Unqualified) {
5160 largtype = largtype.getUnqualifiedType();
5161 rargtype = rargtype.getUnqualifiedType();
5162 }
5163
Chris Lattner465fa322008-10-05 17:34:18 +00005164 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5165 allLTypes = false;
5166 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5167 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005168 }
5169 if (allLTypes) return lhs;
5170 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005171
5172 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5173 EPI.ExtInfo = einfo;
5174 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005175 }
5176
5177 if (lproto) allRTypes = false;
5178 if (rproto) allLTypes = false;
5179
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005180 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005181 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005182 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005183 if (proto->isVariadic()) return QualType();
5184 // Check that the types are compatible with the types that
5185 // would result from default argument promotions (C99 6.7.5.3p15).
5186 // The only types actually affected are promotable integer
5187 // types and floats, which would be passed as a different
5188 // type depending on whether the prototype is visible.
5189 unsigned proto_nargs = proto->getNumArgs();
5190 for (unsigned i = 0; i < proto_nargs; ++i) {
5191 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005192
5193 // Look at the promotion type of enum types, since that is the type used
5194 // to pass enum values.
5195 if (const EnumType *Enum = argTy->getAs<EnumType>())
5196 argTy = Enum->getDecl()->getPromotionType();
5197
Eli Friedman47f77112008-08-22 00:56:42 +00005198 if (argTy->isPromotableIntegerType() ||
5199 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5200 return QualType();
5201 }
5202
5203 if (allLTypes) return lhs;
5204 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005205
5206 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5207 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005208 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005209 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005210 }
5211
5212 if (allLTypes) return lhs;
5213 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005214 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005215}
5216
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005217QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005218 bool OfBlockPointer,
5219 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005220 // C++ [expr]: If an expression initially has the type "reference to T", the
5221 // type is adjusted to "T" prior to any further analysis, the expression
5222 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005223 // expression is an lvalue unless the reference is an rvalue reference and
5224 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005225 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5226 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005227
5228 if (Unqualified) {
5229 LHS = LHS.getUnqualifiedType();
5230 RHS = RHS.getUnqualifiedType();
5231 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005232
Eli Friedman47f77112008-08-22 00:56:42 +00005233 QualType LHSCan = getCanonicalType(LHS),
5234 RHSCan = getCanonicalType(RHS);
5235
5236 // If two types are identical, they are compatible.
5237 if (LHSCan == RHSCan)
5238 return LHS;
5239
John McCall8ccfcb52009-09-24 19:53:00 +00005240 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005241 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5242 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005243 if (LQuals != RQuals) {
5244 // If any of these qualifiers are different, we have a type
5245 // mismatch.
5246 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5247 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5248 return QualType();
5249
5250 // Exactly one GC qualifier difference is allowed: __strong is
5251 // okay if the other type has no GC qualifier but is an Objective
5252 // C object pointer (i.e. implicitly strong by default). We fix
5253 // this by pretending that the unqualified type was actually
5254 // qualified __strong.
5255 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5256 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5257 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5258
5259 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5260 return QualType();
5261
5262 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5263 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5264 }
5265 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5266 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5267 }
Eli Friedman47f77112008-08-22 00:56:42 +00005268 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005269 }
5270
5271 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005272
Eli Friedmandcca6332009-06-01 01:22:52 +00005273 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5274 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005275
Chris Lattnerfd652912008-01-14 05:45:46 +00005276 // We want to consider the two function types to be the same for these
5277 // comparisons, just force one to the other.
5278 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5279 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005280
5281 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005282 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5283 LHSClass = Type::ConstantArray;
5284 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5285 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005286
John McCall8b07ec22010-05-15 11:32:37 +00005287 // ObjCInterfaces are just specialized ObjCObjects.
5288 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5289 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5290
Nate Begemance4d7fc2008-04-18 23:10:10 +00005291 // Canonicalize ExtVector -> Vector.
5292 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5293 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005294
Chris Lattner95554662008-04-07 05:43:21 +00005295 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005296 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005297 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005298 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005299 // Compatibility is based on the underlying type, not the promotion
5300 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005301 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005302 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5303 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005304 }
John McCall9dd450b2009-09-21 23:43:11 +00005305 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005306 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5307 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005308 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005309
Eli Friedman47f77112008-08-22 00:56:42 +00005310 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005311 }
Eli Friedman47f77112008-08-22 00:56:42 +00005312
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005313 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005314 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005315#define TYPE(Class, Base)
5316#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005317#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005318#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5319#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5320#include "clang/AST/TypeNodes.def"
5321 assert(false && "Non-canonical and dependent types shouldn't get here");
5322 return QualType();
5323
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005324 case Type::LValueReference:
5325 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005326 case Type::MemberPointer:
5327 assert(false && "C++ should never be in mergeTypes");
5328 return QualType();
5329
John McCall8b07ec22010-05-15 11:32:37 +00005330 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005331 case Type::IncompleteArray:
5332 case Type::VariableArray:
5333 case Type::FunctionProto:
5334 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005335 assert(false && "Types are eliminated above");
5336 return QualType();
5337
Chris Lattnerfd652912008-01-14 05:45:46 +00005338 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005339 {
5340 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005341 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5342 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005343 if (Unqualified) {
5344 LHSPointee = LHSPointee.getUnqualifiedType();
5345 RHSPointee = RHSPointee.getUnqualifiedType();
5346 }
5347 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5348 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005349 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005350 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005351 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005352 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005353 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005354 return getPointerType(ResultType);
5355 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005356 case Type::BlockPointer:
5357 {
5358 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005359 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5360 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005361 if (Unqualified) {
5362 LHSPointee = LHSPointee.getUnqualifiedType();
5363 RHSPointee = RHSPointee.getUnqualifiedType();
5364 }
5365 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5366 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005367 if (ResultType.isNull()) return QualType();
5368 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5369 return LHS;
5370 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5371 return RHS;
5372 return getBlockPointerType(ResultType);
5373 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005374 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005375 {
5376 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5377 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5378 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5379 return QualType();
5380
5381 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5382 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005383 if (Unqualified) {
5384 LHSElem = LHSElem.getUnqualifiedType();
5385 RHSElem = RHSElem.getUnqualifiedType();
5386 }
5387
5388 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005389 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005390 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5391 return LHS;
5392 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5393 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005394 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5395 ArrayType::ArraySizeModifier(), 0);
5396 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5397 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005398 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5399 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005400 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5401 return LHS;
5402 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5403 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005404 if (LVAT) {
5405 // FIXME: This isn't correct! But tricky to implement because
5406 // the array's size has to be the size of LHS, but the type
5407 // has to be different.
5408 return LHS;
5409 }
5410 if (RVAT) {
5411 // FIXME: This isn't correct! But tricky to implement because
5412 // the array's size has to be the size of RHS, but the type
5413 // has to be different.
5414 return RHS;
5415 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005416 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5417 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005418 return getIncompleteArrayType(ResultType,
5419 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005420 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005421 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005422 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005423 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005424 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005425 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005426 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005427 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005428 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005429 case Type::Complex:
5430 // Distinct complex types are incompatible.
5431 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005432 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005433 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005434 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5435 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005436 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005437 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005438 case Type::ObjCObject: {
5439 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005440 // FIXME: This should be type compatibility, e.g. whether
5441 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005442 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5443 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5444 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005445 return LHS;
5446
Eli Friedman47f77112008-08-22 00:56:42 +00005447 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005448 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005449 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005450 if (OfBlockPointer) {
5451 if (canAssignObjCInterfacesInBlockPointer(
5452 LHS->getAs<ObjCObjectPointerType>(),
5453 RHS->getAs<ObjCObjectPointerType>()))
5454 return LHS;
5455 return QualType();
5456 }
John McCall9dd450b2009-09-21 23:43:11 +00005457 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5458 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005459 return LHS;
5460
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005461 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005462 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005463 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005464
5465 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005466}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005467
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005468/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5469/// 'RHS' attributes and returns the merged version; including for function
5470/// return types.
5471QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5472 QualType LHSCan = getCanonicalType(LHS),
5473 RHSCan = getCanonicalType(RHS);
5474 // If two types are identical, they are compatible.
5475 if (LHSCan == RHSCan)
5476 return LHS;
5477 if (RHSCan->isFunctionType()) {
5478 if (!LHSCan->isFunctionType())
5479 return QualType();
5480 QualType OldReturnType =
5481 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5482 QualType NewReturnType =
5483 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5484 QualType ResReturnType =
5485 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5486 if (ResReturnType.isNull())
5487 return QualType();
5488 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5489 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5490 // In either case, use OldReturnType to build the new function type.
5491 const FunctionType *F = LHS->getAs<FunctionType>();
5492 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005493 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5494 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005495 QualType ResultType
5496 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005497 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005498 return ResultType;
5499 }
5500 }
5501 return QualType();
5502 }
5503
5504 // If the qualifiers are different, the types can still be merged.
5505 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5506 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5507 if (LQuals != RQuals) {
5508 // If any of these qualifiers are different, we have a type mismatch.
5509 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5510 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5511 return QualType();
5512
5513 // Exactly one GC qualifier difference is allowed: __strong is
5514 // okay if the other type has no GC qualifier but is an Objective
5515 // C object pointer (i.e. implicitly strong by default). We fix
5516 // this by pretending that the unqualified type was actually
5517 // qualified __strong.
5518 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5519 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5520 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5521
5522 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5523 return QualType();
5524
5525 if (GC_L == Qualifiers::Strong)
5526 return LHS;
5527 if (GC_R == Qualifiers::Strong)
5528 return RHS;
5529 return QualType();
5530 }
5531
5532 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5533 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5534 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5535 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5536 if (ResQT == LHSBaseQT)
5537 return LHS;
5538 if (ResQT == RHSBaseQT)
5539 return RHS;
5540 }
5541 return QualType();
5542}
5543
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005544//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005545// Integer Predicates
5546//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005547
Jay Foad39c79802011-01-12 09:06:06 +00005548unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005549 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005550 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005551 if (T->isBooleanType())
5552 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005553 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005554 return (unsigned)getTypeSize(T);
5555}
5556
5557QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005558 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005559
5560 // Turn <4 x signed int> -> <4 x unsigned int>
5561 if (const VectorType *VTy = T->getAs<VectorType>())
5562 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005563 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005564
5565 // For enums, we return the unsigned version of the base type.
5566 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005567 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005568
5569 const BuiltinType *BTy = T->getAs<BuiltinType>();
5570 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005571 switch (BTy->getKind()) {
5572 case BuiltinType::Char_S:
5573 case BuiltinType::SChar:
5574 return UnsignedCharTy;
5575 case BuiltinType::Short:
5576 return UnsignedShortTy;
5577 case BuiltinType::Int:
5578 return UnsignedIntTy;
5579 case BuiltinType::Long:
5580 return UnsignedLongTy;
5581 case BuiltinType::LongLong:
5582 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005583 case BuiltinType::Int128:
5584 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005585 default:
5586 assert(0 && "Unexpected signed integer type");
5587 return QualType();
5588 }
5589}
5590
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005591ASTMutationListener::~ASTMutationListener() { }
5592
Chris Lattnerecd79c62009-06-14 00:45:47 +00005593
5594//===----------------------------------------------------------------------===//
5595// Builtin Type Computation
5596//===----------------------------------------------------------------------===//
5597
5598/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005599/// pointer over the consumed characters. This returns the resultant type. If
5600/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5601/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5602/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005603///
5604/// RequiresICE is filled in on return to indicate whether the value is required
5605/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005606static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005607 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005608 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005609 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005610 // Modifiers.
5611 int HowLong = 0;
5612 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005613 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005614
Chris Lattnerdc226c22010-10-01 22:42:38 +00005615 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005616 bool Done = false;
5617 while (!Done) {
5618 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005619 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005620 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005621 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005622 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005623 case 'S':
5624 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5625 assert(!Signed && "Can't use 'S' modifier multiple times!");
5626 Signed = true;
5627 break;
5628 case 'U':
5629 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5630 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5631 Unsigned = true;
5632 break;
5633 case 'L':
5634 assert(HowLong <= 2 && "Can't have LLLL modifier");
5635 ++HowLong;
5636 break;
5637 }
5638 }
5639
5640 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005641
Chris Lattnerecd79c62009-06-14 00:45:47 +00005642 // Read the base type.
5643 switch (*Str++) {
5644 default: assert(0 && "Unknown builtin type letter!");
5645 case 'v':
5646 assert(HowLong == 0 && !Signed && !Unsigned &&
5647 "Bad modifiers used with 'v'!");
5648 Type = Context.VoidTy;
5649 break;
5650 case 'f':
5651 assert(HowLong == 0 && !Signed && !Unsigned &&
5652 "Bad modifiers used with 'f'!");
5653 Type = Context.FloatTy;
5654 break;
5655 case 'd':
5656 assert(HowLong < 2 && !Signed && !Unsigned &&
5657 "Bad modifiers used with 'd'!");
5658 if (HowLong)
5659 Type = Context.LongDoubleTy;
5660 else
5661 Type = Context.DoubleTy;
5662 break;
5663 case 's':
5664 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5665 if (Unsigned)
5666 Type = Context.UnsignedShortTy;
5667 else
5668 Type = Context.ShortTy;
5669 break;
5670 case 'i':
5671 if (HowLong == 3)
5672 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5673 else if (HowLong == 2)
5674 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5675 else if (HowLong == 1)
5676 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5677 else
5678 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5679 break;
5680 case 'c':
5681 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5682 if (Signed)
5683 Type = Context.SignedCharTy;
5684 else if (Unsigned)
5685 Type = Context.UnsignedCharTy;
5686 else
5687 Type = Context.CharTy;
5688 break;
5689 case 'b': // boolean
5690 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5691 Type = Context.BoolTy;
5692 break;
5693 case 'z': // size_t.
5694 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5695 Type = Context.getSizeType();
5696 break;
5697 case 'F':
5698 Type = Context.getCFConstantStringType();
5699 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005700 case 'G':
5701 Type = Context.getObjCIdType();
5702 break;
5703 case 'H':
5704 Type = Context.getObjCSelType();
5705 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005706 case 'a':
5707 Type = Context.getBuiltinVaListType();
5708 assert(!Type.isNull() && "builtin va list type not initialized!");
5709 break;
5710 case 'A':
5711 // This is a "reference" to a va_list; however, what exactly
5712 // this means depends on how va_list is defined. There are two
5713 // different kinds of va_list: ones passed by value, and ones
5714 // passed by reference. An example of a by-value va_list is
5715 // x86, where va_list is a char*. An example of by-ref va_list
5716 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5717 // we want this argument to be a char*&; for x86-64, we want
5718 // it to be a __va_list_tag*.
5719 Type = Context.getBuiltinVaListType();
5720 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005721 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005722 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005723 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005724 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005725 break;
5726 case 'V': {
5727 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005728 unsigned NumElements = strtoul(Str, &End, 10);
5729 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005730 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005731
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005732 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5733 RequiresICE, false);
5734 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005735
5736 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005737 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005738 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005739 break;
5740 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005741 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005742 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5743 false);
5744 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005745 Type = Context.getComplexType(ElementType);
5746 break;
5747 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005748 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005749 Type = Context.getFILEType();
5750 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005751 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005752 return QualType();
5753 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005754 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005755 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005756 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005757 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005758 else
5759 Type = Context.getjmp_bufType();
5760
Mike Stump2adb4da2009-07-28 23:47:15 +00005761 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005762 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005763 return QualType();
5764 }
5765 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005766 }
Mike Stump11289f42009-09-09 15:08:12 +00005767
Chris Lattnerdc226c22010-10-01 22:42:38 +00005768 // If there are modifiers and if we're allowed to parse them, go for it.
5769 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005770 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005771 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005772 default: Done = true; --Str; break;
5773 case '*':
5774 case '&': {
5775 // Both pointers and references can have their pointee types
5776 // qualified with an address space.
5777 char *End;
5778 unsigned AddrSpace = strtoul(Str, &End, 10);
5779 if (End != Str && AddrSpace != 0) {
5780 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5781 Str = End;
5782 }
5783 if (c == '*')
5784 Type = Context.getPointerType(Type);
5785 else
5786 Type = Context.getLValueReferenceType(Type);
5787 break;
5788 }
5789 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5790 case 'C':
5791 Type = Type.withConst();
5792 break;
5793 case 'D':
5794 Type = Context.getVolatileType(Type);
5795 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005796 }
5797 }
Chris Lattner84733392010-10-01 07:13:18 +00005798
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005799 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005800 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005801
Chris Lattnerecd79c62009-06-14 00:45:47 +00005802 return Type;
5803}
5804
5805/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005806QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005807 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005808 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005809 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005810
Chris Lattnerecd79c62009-06-14 00:45:47 +00005811 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005812
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005813 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005814 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005815 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5816 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005817 if (Error != GE_None)
5818 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005819
5820 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5821
Chris Lattnerecd79c62009-06-14 00:45:47 +00005822 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005823 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005824 if (Error != GE_None)
5825 return QualType();
5826
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005827 // If this argument is required to be an IntegerConstantExpression and the
5828 // caller cares, fill in the bitmask we return.
5829 if (RequiresICE && IntegerConstantArgs)
5830 *IntegerConstantArgs |= 1 << ArgTypes.size();
5831
Chris Lattnerecd79c62009-06-14 00:45:47 +00005832 // Do array -> pointer decay. The builtin should use the decayed type.
5833 if (Ty->isArrayType())
5834 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005835
Chris Lattnerecd79c62009-06-14 00:45:47 +00005836 ArgTypes.push_back(Ty);
5837 }
5838
5839 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5840 "'.' should only occur at end of builtin type list!");
5841
John McCall991eb4b2010-12-21 00:44:39 +00005842 FunctionType::ExtInfo EI;
5843 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5844
5845 bool Variadic = (TypeStr[0] == '.');
5846
5847 // We really shouldn't be making a no-proto type here, especially in C++.
5848 if (ArgTypes.empty() && Variadic)
5849 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005850
John McCalldb40c7f2010-12-14 08:05:40 +00005851 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005852 EPI.ExtInfo = EI;
5853 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00005854
5855 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005856}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005857
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005858GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5859 GVALinkage External = GVA_StrongExternal;
5860
5861 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005862 switch (L) {
5863 case NoLinkage:
5864 case InternalLinkage:
5865 case UniqueExternalLinkage:
5866 return GVA_Internal;
5867
5868 case ExternalLinkage:
5869 switch (FD->getTemplateSpecializationKind()) {
5870 case TSK_Undeclared:
5871 case TSK_ExplicitSpecialization:
5872 External = GVA_StrongExternal;
5873 break;
5874
5875 case TSK_ExplicitInstantiationDefinition:
5876 return GVA_ExplicitTemplateInstantiation;
5877
5878 case TSK_ExplicitInstantiationDeclaration:
5879 case TSK_ImplicitInstantiation:
5880 External = GVA_TemplateInstantiation;
5881 break;
5882 }
5883 }
5884
5885 if (!FD->isInlined())
5886 return External;
5887
5888 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5889 // GNU or C99 inline semantics. Determine whether this symbol should be
5890 // externally visible.
5891 if (FD->isInlineDefinitionExternallyVisible())
5892 return External;
5893
5894 // C99 inline semantics, where the symbol is not externally visible.
5895 return GVA_C99Inline;
5896 }
5897
5898 // C++0x [temp.explicit]p9:
5899 // [ Note: The intent is that an inline function that is the subject of
5900 // an explicit instantiation declaration will still be implicitly
5901 // instantiated when used so that the body can be considered for
5902 // inlining, but that no out-of-line copy of the inline function would be
5903 // generated in the translation unit. -- end note ]
5904 if (FD->getTemplateSpecializationKind()
5905 == TSK_ExplicitInstantiationDeclaration)
5906 return GVA_C99Inline;
5907
5908 return GVA_CXXInline;
5909}
5910
5911GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5912 // If this is a static data member, compute the kind of template
5913 // specialization. Otherwise, this variable is not part of a
5914 // template.
5915 TemplateSpecializationKind TSK = TSK_Undeclared;
5916 if (VD->isStaticDataMember())
5917 TSK = VD->getTemplateSpecializationKind();
5918
5919 Linkage L = VD->getLinkage();
5920 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5921 VD->getType()->getLinkage() == UniqueExternalLinkage)
5922 L = UniqueExternalLinkage;
5923
5924 switch (L) {
5925 case NoLinkage:
5926 case InternalLinkage:
5927 case UniqueExternalLinkage:
5928 return GVA_Internal;
5929
5930 case ExternalLinkage:
5931 switch (TSK) {
5932 case TSK_Undeclared:
5933 case TSK_ExplicitSpecialization:
5934 return GVA_StrongExternal;
5935
5936 case TSK_ExplicitInstantiationDeclaration:
5937 llvm_unreachable("Variable should not be instantiated");
5938 // Fall through to treat this like any other instantiation.
5939
5940 case TSK_ExplicitInstantiationDefinition:
5941 return GVA_ExplicitTemplateInstantiation;
5942
5943 case TSK_ImplicitInstantiation:
5944 return GVA_TemplateInstantiation;
5945 }
5946 }
5947
5948 return GVA_StrongExternal;
5949}
5950
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005951bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005952 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5953 if (!VD->isFileVarDecl())
5954 return false;
5955 } else if (!isa<FunctionDecl>(D))
5956 return false;
5957
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005958 // Weak references don't produce any output by themselves.
5959 if (D->hasAttr<WeakRefAttr>())
5960 return false;
5961
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005962 // Aliases and used decls are required.
5963 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5964 return true;
5965
5966 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5967 // Forward declarations aren't required.
5968 if (!FD->isThisDeclarationADefinition())
5969 return false;
5970
5971 // Constructors and destructors are required.
5972 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5973 return true;
5974
5975 // The key function for a class is required.
5976 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5977 const CXXRecordDecl *RD = MD->getParent();
5978 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5979 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5980 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5981 return true;
5982 }
5983 }
5984
5985 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5986
5987 // static, static inline, always_inline, and extern inline functions can
5988 // always be deferred. Normal inline functions can be deferred in C99/C++.
5989 // Implicit template instantiations can also be deferred in C++.
5990 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5991 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5992 return false;
5993 return true;
5994 }
5995
5996 const VarDecl *VD = cast<VarDecl>(D);
5997 assert(VD->isFileVarDecl() && "Expected file scoped var");
5998
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005999 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6000 return false;
6001
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006002 // Structs that have non-trivial constructors or destructors are required.
6003
6004 // FIXME: Handle references.
6005 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6006 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006007 if (RD->hasDefinition() &&
6008 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006009 return true;
6010 }
6011 }
6012
6013 GVALinkage L = GetGVALinkageForVariable(VD);
6014 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6015 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6016 return false;
6017 }
6018
6019 return true;
6020}
Charles Davis53c59df2010-08-16 03:33:14 +00006021
Charles Davis99202b32010-11-09 18:04:24 +00006022CallingConv ASTContext::getDefaultMethodCallConv() {
6023 // Pass through to the C++ ABI object
6024 return ABI->getDefaultMethodCallConv();
6025}
6026
Jay Foad39c79802011-01-12 09:06:06 +00006027bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006028 // Pass through to the C++ ABI object
6029 return ABI->isNearlyEmpty(RD);
6030}
6031
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006032MangleContext *ASTContext::createMangleContext() {
6033 switch (Target.getCXXABI()) {
6034 case CXXABI_ARM:
6035 case CXXABI_Itanium:
6036 return createItaniumMangleContext(*this, getDiagnostics());
6037 case CXXABI_Microsoft:
6038 return createMicrosoftMangleContext(*this, getDiagnostics());
6039 }
6040 assert(0 && "Unsupported ABI");
6041 return 0;
6042}
6043
Charles Davis53c59df2010-08-16 03:33:14 +00006044CXXABI::~CXXABI() {}