blob: dcbfd9deec50c4dfce0f4202f535a46c38e62d2e [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(),
110 SourceLocation(), TTP->getDepth(),
111 TTP->getIndex(), 0, false,
112 TTP->isParameterPack()));
113 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000114 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
115 QualType T = getCanonicalType(NTTP->getType());
116 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
117 NonTypeTemplateParmDecl *Param;
118 if (NTTP->isExpandedParameterPack()) {
119 llvm::SmallVector<QualType, 2> ExpandedTypes;
120 llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
121 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
122 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
123 ExpandedTInfos.push_back(
124 getTrivialTypeSourceInfo(ExpandedTypes.back()));
125 }
126
127 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
128 SourceLocation(),
129 NTTP->getDepth(),
130 NTTP->getPosition(), 0,
131 T,
132 TInfo,
133 ExpandedTypes.data(),
134 ExpandedTypes.size(),
135 ExpandedTInfos.data());
136 } else {
137 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
138 SourceLocation(),
139 NTTP->getDepth(),
140 NTTP->getPosition(), 0,
141 T,
142 NTTP->isParameterPack(),
143 TInfo);
144 }
145 CanonParams.push_back(Param);
146
147 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000148 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
149 cast<TemplateTemplateParmDecl>(*P)));
150 }
151
152 TemplateTemplateParmDecl *CanonTTP
153 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
154 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000155 TTP->getPosition(),
156 TTP->isParameterPack(),
157 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000158 TemplateParameterList::Create(*this, SourceLocation(),
159 SourceLocation(),
160 CanonParams.data(),
161 CanonParams.size(),
162 SourceLocation()));
163
164 // Get the new insert position for the node we care about.
165 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
166 assert(Canonical == 0 && "Shouldn't be in the map!");
167 (void)Canonical;
168
169 // Create the canonical template template parameter entry.
170 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
171 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
172 return CanonTTP;
173}
174
Charles Davis53c59df2010-08-16 03:33:14 +0000175CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000176 if (!LangOpts.CPlusPlus) return 0;
177
Charles Davis6bcb07a2010-08-19 02:18:14 +0000178 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000179 case CXXABI_ARM:
180 return CreateARMCXXABI(*this);
181 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000182 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000183 case CXXABI_Microsoft:
184 return CreateMicrosoftCXXABI(*this);
185 }
John McCall86353412010-08-21 22:46:04 +0000186 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000187}
188
Chris Lattner465fa322008-10-05 17:34:18 +0000189ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000190 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000191 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000192 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000193 unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000194 TemplateSpecializationTypes(this_()),
195 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000196 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
197 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000198 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000199 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +0000200 cudaConfigureCallDecl(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000201 NullTypeSourceInfo(QualType()),
Charles Davis53c59df2010-08-16 03:33:14 +0000202 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000203 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000204 BuiltinInfo(builtins),
205 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000206 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000207 LastSDM(0, 0),
208 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000209 ObjCIdRedefinitionType = QualType();
210 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000211 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000212 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000213 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000214 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000215}
216
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000217ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000218 // Release the DenseMaps associated with DeclContext objects.
219 // FIXME: Is this the ideal solution?
220 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000221
Douglas Gregor5b11d492010-07-25 17:53:33 +0000222 // Call all of the deallocation functions.
223 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
224 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000225
Douglas Gregor832940b2010-03-02 23:58:15 +0000226 // Release all of the memory associated with overridden C++ methods.
227 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
228 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
229 OM != OMEnd; ++OM)
230 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000231
Ted Kremenek076baeb2010-06-08 23:00:58 +0000232 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000233 // because they can contain DenseMaps.
234 for (llvm::DenseMap<const ObjCContainerDecl*,
235 const ASTRecordLayout*>::iterator
236 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
237 // Increment in loop to prevent using deallocated memory.
238 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
239 R->Destroy(*this);
240
Ted Kremenek076baeb2010-06-08 23:00:58 +0000241 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
242 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
243 // Increment in loop to prevent using deallocated memory.
244 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
245 R->Destroy(*this);
246 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000247
248 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
249 AEnd = DeclAttrs.end();
250 A != AEnd; ++A)
251 A->second->~AttrVec();
252}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000253
Douglas Gregor1a809332010-05-23 18:26:36 +0000254void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
255 Deallocations.push_back(std::make_pair(Callback, Data));
256}
257
Mike Stump11289f42009-09-09 15:08:12 +0000258void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000259ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
260 ExternalSource.reset(Source.take());
261}
262
Chris Lattner4eb445d2007-01-26 01:27:23 +0000263void ASTContext::PrintStats() const {
264 fprintf(stderr, "*** AST Context Stats:\n");
265 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000266
Douglas Gregora30d0462009-05-26 14:40:08 +0000267 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000268#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000269#define ABSTRACT_TYPE(Name, Parent)
270#include "clang/AST/TypeNodes.def"
271 0 // Extra
272 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000273
Chris Lattner4eb445d2007-01-26 01:27:23 +0000274 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
275 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000276 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000277 }
278
Douglas Gregora30d0462009-05-26 14:40:08 +0000279 unsigned Idx = 0;
280 unsigned TotalBytes = 0;
281#define TYPE(Name, Parent) \
282 if (counts[Idx]) \
283 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
284 TotalBytes += counts[Idx] * sizeof(Name##Type); \
285 ++Idx;
286#define ABSTRACT_TYPE(Name, Parent)
287#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000288
Douglas Gregora30d0462009-05-26 14:40:08 +0000289 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000290
Douglas Gregor7454c562010-07-02 20:37:36 +0000291 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000292 fprintf(stderr, " %u/%u implicit default constructors created\n",
293 NumImplicitDefaultConstructorsDeclared,
294 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000295 fprintf(stderr, " %u/%u implicit copy constructors created\n",
296 NumImplicitCopyConstructorsDeclared,
297 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000298 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
299 NumImplicitCopyAssignmentOperatorsDeclared,
300 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000301 fprintf(stderr, " %u/%u implicit destructors created\n",
302 NumImplicitDestructorsDeclared, NumImplicitDestructors);
303
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000304 if (ExternalSource.get()) {
305 fprintf(stderr, "\n");
306 ExternalSource->PrintStats();
307 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000308
Douglas Gregor5b11d492010-07-25 17:53:33 +0000309 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000310}
311
312
John McCall48f2d582009-10-23 23:03:21 +0000313void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000314 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000315 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000316 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000317}
318
Chris Lattner970e54e2006-11-12 00:37:36 +0000319void ASTContext::InitBuiltinTypes() {
320 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000321
Chris Lattner970e54e2006-11-12 00:37:36 +0000322 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000323 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000324
Chris Lattner970e54e2006-11-12 00:37:36 +0000325 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000326 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000327 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000328 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000329 InitBuiltinType(CharTy, BuiltinType::Char_S);
330 else
331 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000332 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000333 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
334 InitBuiltinType(ShortTy, BuiltinType::Short);
335 InitBuiltinType(IntTy, BuiltinType::Int);
336 InitBuiltinType(LongTy, BuiltinType::Long);
337 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000338
Chris Lattner970e54e2006-11-12 00:37:36 +0000339 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000340 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
341 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
342 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
343 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
344 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000345
Chris Lattner970e54e2006-11-12 00:37:36 +0000346 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000347 InitBuiltinType(FloatTy, BuiltinType::Float);
348 InitBuiltinType(DoubleTy, BuiltinType::Double);
349 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000350
Chris Lattnerf122cef2009-04-30 02:43:43 +0000351 // GNU extension, 128-bit integers.
352 InitBuiltinType(Int128Ty, BuiltinType::Int128);
353 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
354
Chris Lattnerad3467e2010-12-25 23:25:43 +0000355 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
356 if (!LangOpts.ShortWChar)
357 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
358 else // -fshort-wchar makes wchar_t be unsigned.
359 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
360 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000361 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000362
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000363 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
364 InitBuiltinType(Char16Ty, BuiltinType::Char16);
365 else // C99
366 Char16Ty = getFromTargetType(Target.getChar16Type());
367
368 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
369 InitBuiltinType(Char32Ty, BuiltinType::Char32);
370 else // C99
371 Char32Ty = getFromTargetType(Target.getChar32Type());
372
Douglas Gregor4619e432008-12-05 23:32:09 +0000373 // Placeholder type for type-dependent expressions whose type is
374 // completely unknown. No code should ever check a type against
375 // DependentTy and users should never see it; however, it is here to
376 // help diagnose failures to properly check for type-dependent
377 // expressions.
378 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000379
John McCall36e7fe32010-10-12 00:20:44 +0000380 // Placeholder type for functions.
381 InitBuiltinType(OverloadTy, BuiltinType::Overload);
382
Mike Stump11289f42009-09-09 15:08:12 +0000383 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000384 // not yet been deduced.
John McCall36e7fe32010-10-12 00:20:44 +0000385 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000386
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.
635 unsigned fieldAlign = layout.getAlignment();
636
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>
655ASTContext::getTypeInfoInChars(const Type *T) {
656 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>
662ASTContext::getTypeInfoInChars(QualType T) {
663 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());
Devang Pateldbb72632008-06-04 21:54:36 +0000851 Align = Layout.getAlignment();
852 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());
Chris Lattner8b23c252008-04-06 22:05:18 +0000870 Align = 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
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000878 case Type::Paren:
879 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
880
Douglas Gregoref462e62009-04-30 17:32:17 +0000881 case Type::Typedef: {
882 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000883 std::pair<uint64_t, unsigned> Info
884 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
885 Align = std::max(Typedef->getMaxAlignment(), Info.second);
886 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000887 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000888 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000889
890 case Type::TypeOfExpr:
891 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
892 .getTypePtr());
893
894 case Type::TypeOf:
895 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
896
Anders Carlsson81df7b82009-06-24 19:06:50 +0000897 case Type::Decltype:
898 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
899 .getTypePtr());
900
Abramo Bagnara6150c882010-05-11 21:36:43 +0000901 case Type::Elaborated:
902 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000903
John McCall81904512011-01-06 01:58:22 +0000904 case Type::Attributed:
905 return getTypeInfo(
906 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
907
Douglas Gregoref462e62009-04-30 17:32:17 +0000908 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000909 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000910 "Cannot request the size of a dependent type");
911 // FIXME: this is likely to be wrong once we support template
912 // aliases, since a template alias could refer to a typedef that
913 // has an __aligned__ attribute on it.
914 return getTypeInfo(getCanonicalType(T));
915 }
Mike Stump11289f42009-09-09 15:08:12 +0000916
Chris Lattner53cfe802007-07-18 17:52:12 +0000917 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000918 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000919}
920
Ken Dyckcc56c542011-01-15 18:38:59 +0000921/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
922CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
923 return CharUnits::fromQuantity(BitSize / getCharWidth());
924}
925
Ken Dyckb0fcc592011-02-11 01:54:29 +0000926/// toBits - Convert a size in characters to a size in characters.
927int64_t ASTContext::toBits(CharUnits CharSize) const {
928 return CharSize.getQuantity() * getCharWidth();
929}
930
Ken Dyck8c89d592009-12-22 14:23:30 +0000931/// getTypeSizeInChars - Return the size of the specified type, in characters.
932/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000933CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000934 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000935}
Jay Foad39c79802011-01-12 09:06:06 +0000936CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000937 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000938}
939
Ken Dycka6046ab2010-01-26 17:25:18 +0000940/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000941/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000942CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000943 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000944}
Jay Foad39c79802011-01-12 09:06:06 +0000945CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000946 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000947}
948
Chris Lattnera3402cd2009-01-27 18:08:34 +0000949/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
950/// type for the current target in bits. This can be different than the ABI
951/// alignment in cases where it is beneficial for performance to overalign
952/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +0000953unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +0000954 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000955
956 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000957 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000958 T = CT->getElementType().getTypePtr();
959 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
960 T->isSpecificBuiltinType(BuiltinType::LongLong))
961 return std::max(ABIAlign, (unsigned)getTypeSize(T));
962
Chris Lattnera3402cd2009-01-27 18:08:34 +0000963 return ABIAlign;
964}
965
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000966/// ShallowCollectObjCIvars -
967/// Collect all ivars, including those synthesized, in the current class.
968///
969void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +0000970 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000971 // FIXME. This need be removed but there are two many places which
972 // assume const-ness of ObjCInterfaceDecl
973 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
974 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
975 Iv= Iv->getNextIvar())
976 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000977}
978
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000979/// DeepCollectObjCIvars -
980/// This routine first collects all declared, but not synthesized, ivars in
981/// super class and then collects all ivars, including those synthesized for
982/// current class. This routine is used for implementation of current class
983/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000984///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000985void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
986 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +0000987 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000988 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
989 DeepCollectObjCIvars(SuperClass, false, Ivars);
990 if (!leafClass) {
991 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
992 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000993 Ivars.push_back(*I);
994 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000995 else
996 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000997}
998
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000999/// CollectInheritedProtocols - Collect all protocols in current class and
1000/// those inherited by it.
1001void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001002 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001003 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001004 // We can use protocol_iterator here instead of
1005 // all_referenced_protocol_iterator since we are walking all categories.
1006 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1007 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001008 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001009 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001010 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001011 PE = Proto->protocol_end(); P != PE; ++P) {
1012 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001013 CollectInheritedProtocols(*P, Protocols);
1014 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001015 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001016
1017 // Categories of this Interface.
1018 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1019 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1020 CollectInheritedProtocols(CDeclChain, Protocols);
1021 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1022 while (SD) {
1023 CollectInheritedProtocols(SD, Protocols);
1024 SD = SD->getSuperClass();
1025 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001026 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001027 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001028 PE = OC->protocol_end(); P != PE; ++P) {
1029 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001030 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001031 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1032 PE = Proto->protocol_end(); P != PE; ++P)
1033 CollectInheritedProtocols(*P, Protocols);
1034 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001035 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001036 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1037 PE = OP->protocol_end(); P != PE; ++P) {
1038 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001039 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001040 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1041 PE = Proto->protocol_end(); P != PE; ++P)
1042 CollectInheritedProtocols(*P, Protocols);
1043 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001044 }
1045}
1046
Jay Foad39c79802011-01-12 09:06:06 +00001047unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001048 unsigned count = 0;
1049 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001050 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1051 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001052 count += CDecl->ivar_size();
1053
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001054 // Count ivar defined in this class's implementation. This
1055 // includes synthesized ivars.
1056 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001057 count += ImplDecl->ivar_size();
1058
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001059 return count;
1060}
1061
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001062/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1063ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1064 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1065 I = ObjCImpls.find(D);
1066 if (I != ObjCImpls.end())
1067 return cast<ObjCImplementationDecl>(I->second);
1068 return 0;
1069}
1070/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1071ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1072 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1073 I = ObjCImpls.find(D);
1074 if (I != ObjCImpls.end())
1075 return cast<ObjCCategoryImplDecl>(I->second);
1076 return 0;
1077}
1078
1079/// \brief Set the implementation of ObjCInterfaceDecl.
1080void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1081 ObjCImplementationDecl *ImplD) {
1082 assert(IFaceD && ImplD && "Passed null params");
1083 ObjCImpls[IFaceD] = ImplD;
1084}
1085/// \brief Set the implementation of ObjCCategoryDecl.
1086void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1087 ObjCCategoryImplDecl *ImplD) {
1088 assert(CatD && ImplD && "Passed null params");
1089 ObjCImpls[CatD] = ImplD;
1090}
1091
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001092/// \brief Get the copy initialization expression of VarDecl,or NULL if
1093/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001094Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001095 assert(VD && "Passed null params");
1096 assert(VD->hasAttr<BlocksAttr>() &&
1097 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001098 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001099 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001100 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1101}
1102
1103/// \brief Set the copy inialization expression of a block var decl.
1104void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1105 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001106 assert(VD->hasAttr<BlocksAttr>() &&
1107 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001108 BlockVarCopyInits[VD] = Init;
1109}
1110
John McCallbcd03502009-12-07 02:54:59 +00001111/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001112///
John McCallbcd03502009-12-07 02:54:59 +00001113/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001114/// the TypeLoc wrappers.
1115///
1116/// \param T the type that will be the basis for type source info. This type
1117/// should refer to how the declarator was written in source code, not to
1118/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001119TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001120 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001121 if (!DataSize)
1122 DataSize = TypeLoc::getFullDataSizeForType(T);
1123 else
1124 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001125 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001126
John McCallbcd03502009-12-07 02:54:59 +00001127 TypeSourceInfo *TInfo =
1128 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1129 new (TInfo) TypeSourceInfo(T);
1130 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001131}
1132
John McCallbcd03502009-12-07 02:54:59 +00001133TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001134 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001135 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001136 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001137 return DI;
1138}
1139
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001140const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001141ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001142 return getObjCLayout(D, 0);
1143}
1144
1145const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001146ASTContext::getASTObjCImplementationLayout(
1147 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001148 return getObjCLayout(D->getClassInterface(), D);
1149}
1150
Chris Lattner983a8bb2007-07-13 22:13:22 +00001151//===----------------------------------------------------------------------===//
1152// Type creation/memoization methods
1153//===----------------------------------------------------------------------===//
1154
Jay Foad39c79802011-01-12 09:06:06 +00001155QualType
John McCall33ddac02011-01-19 10:06:00 +00001156ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1157 unsigned fastQuals = quals.getFastQualifiers();
1158 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001159
1160 // Check if we've already instantiated this type.
1161 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001162 ExtQuals::Profile(ID, baseType, quals);
1163 void *insertPos = 0;
1164 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1165 assert(eq->getQualifiers() == quals);
1166 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001167 }
1168
John McCall33ddac02011-01-19 10:06:00 +00001169 // If the base type is not canonical, make the appropriate canonical type.
1170 QualType canon;
1171 if (!baseType->isCanonicalUnqualified()) {
1172 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1173 canonSplit.second.addConsistentQualifiers(quals);
1174 canon = getExtQualType(canonSplit.first, canonSplit.second);
1175
1176 // Re-find the insert position.
1177 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1178 }
1179
1180 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1181 ExtQualNodes.InsertNode(eq, insertPos);
1182 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001183}
1184
Jay Foad39c79802011-01-12 09:06:06 +00001185QualType
1186ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001187 QualType CanT = getCanonicalType(T);
1188 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001189 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001190
John McCall8ccfcb52009-09-24 19:53:00 +00001191 // If we are composing extended qualifiers together, merge together
1192 // into one ExtQuals node.
1193 QualifierCollector Quals;
1194 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001195
John McCall8ccfcb52009-09-24 19:53:00 +00001196 // If this type already has an address space specified, it cannot get
1197 // another one.
1198 assert(!Quals.hasAddressSpace() &&
1199 "Type cannot be in multiple addr spaces!");
1200 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001201
John McCall8ccfcb52009-09-24 19:53:00 +00001202 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001203}
1204
Chris Lattnerd60183d2009-02-18 22:53:11 +00001205QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001206 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001207 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001208 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001209 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001210
John McCall53fa7142010-12-24 02:08:15 +00001211 if (const PointerType *ptr = T->getAs<PointerType>()) {
1212 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001213 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001214 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1215 return getPointerType(ResultType);
1216 }
1217 }
Mike Stump11289f42009-09-09 15:08:12 +00001218
John McCall8ccfcb52009-09-24 19:53:00 +00001219 // If we are composing extended qualifiers together, merge together
1220 // into one ExtQuals node.
1221 QualifierCollector Quals;
1222 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001223
John McCall8ccfcb52009-09-24 19:53:00 +00001224 // If this type already has an ObjCGC specified, it cannot get
1225 // another one.
1226 assert(!Quals.hasObjCGCAttr() &&
1227 "Type cannot have multiple ObjCGCs!");
1228 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001229
John McCall8ccfcb52009-09-24 19:53:00 +00001230 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001231}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001232
John McCall4f5019e2010-12-19 02:44:49 +00001233const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1234 FunctionType::ExtInfo Info) {
1235 if (T->getExtInfo() == Info)
1236 return T;
1237
1238 QualType Result;
1239 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1240 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1241 } else {
1242 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1243 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1244 EPI.ExtInfo = Info;
1245 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1246 FPT->getNumArgs(), EPI);
1247 }
1248
1249 return cast<FunctionType>(Result.getTypePtr());
1250}
1251
Chris Lattnerc6395932007-06-22 20:56:16 +00001252/// getComplexType - Return the uniqued reference to the type for a complex
1253/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001254QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001255 // Unique pointers, to guarantee there is only one pointer of a particular
1256 // structure.
1257 llvm::FoldingSetNodeID ID;
1258 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001259
Chris Lattnerc6395932007-06-22 20:56:16 +00001260 void *InsertPos = 0;
1261 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1262 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001263
Chris Lattnerc6395932007-06-22 20:56:16 +00001264 // If the pointee type isn't canonical, this won't be a canonical type either,
1265 // so fill in the canonical type field.
1266 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001267 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001268 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001269
Chris Lattnerc6395932007-06-22 20:56:16 +00001270 // Get the new insert position for the node we care about.
1271 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001272 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001273 }
John McCall90d1c2d2009-09-24 23:30:46 +00001274 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001275 Types.push_back(New);
1276 ComplexTypes.InsertNode(New, InsertPos);
1277 return QualType(New, 0);
1278}
1279
Chris Lattner970e54e2006-11-12 00:37:36 +00001280/// getPointerType - Return the uniqued reference to the type for a pointer to
1281/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001282QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001283 // Unique pointers, to guarantee there is only one pointer of a particular
1284 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001285 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001286 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001287
Chris Lattner67521df2007-01-27 01:29:36 +00001288 void *InsertPos = 0;
1289 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001290 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001291
Chris Lattner7ccecb92006-11-12 08:50:50 +00001292 // If the pointee type isn't canonical, this won't be a canonical type either,
1293 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001294 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001295 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001296 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001297
Chris Lattner67521df2007-01-27 01:29:36 +00001298 // Get the new insert position for the node we care about.
1299 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001300 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001301 }
John McCall90d1c2d2009-09-24 23:30:46 +00001302 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001303 Types.push_back(New);
1304 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001305 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001306}
1307
Mike Stump11289f42009-09-09 15:08:12 +00001308/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001309/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001310QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001311 assert(T->isFunctionType() && "block of function types only");
1312 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001313 // structure.
1314 llvm::FoldingSetNodeID ID;
1315 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001316
Steve Naroffec33ed92008-08-27 16:04:49 +00001317 void *InsertPos = 0;
1318 if (BlockPointerType *PT =
1319 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1320 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001321
1322 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001323 // type either so fill in the canonical type field.
1324 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001325 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001326 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001327
Steve Naroffec33ed92008-08-27 16:04:49 +00001328 // Get the new insert position for the node we care about.
1329 BlockPointerType *NewIP =
1330 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001331 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001332 }
John McCall90d1c2d2009-09-24 23:30:46 +00001333 BlockPointerType *New
1334 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001335 Types.push_back(New);
1336 BlockPointerTypes.InsertNode(New, InsertPos);
1337 return QualType(New, 0);
1338}
1339
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001340/// getLValueReferenceType - Return the uniqued reference to the type for an
1341/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001342QualType
1343ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001344 // Unique pointers, to guarantee there is only one pointer of a particular
1345 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001346 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001347 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001348
1349 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001350 if (LValueReferenceType *RT =
1351 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001352 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001353
John McCallfc93cf92009-10-22 22:37:11 +00001354 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1355
Bill Wendling3708c182007-05-27 10:15:43 +00001356 // If the referencee type isn't canonical, this won't be a canonical type
1357 // either, so fill in the canonical type field.
1358 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001359 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1360 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1361 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001362
Bill Wendling3708c182007-05-27 10:15:43 +00001363 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001364 LValueReferenceType *NewIP =
1365 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001366 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001367 }
1368
John McCall90d1c2d2009-09-24 23:30:46 +00001369 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001370 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1371 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001372 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001373 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001374
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001375 return QualType(New, 0);
1376}
1377
1378/// getRValueReferenceType - Return the uniqued reference to the type for an
1379/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001380QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001381 // Unique pointers, to guarantee there is only one pointer of a particular
1382 // structure.
1383 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001384 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001385
1386 void *InsertPos = 0;
1387 if (RValueReferenceType *RT =
1388 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1389 return QualType(RT, 0);
1390
John McCallfc93cf92009-10-22 22:37:11 +00001391 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1392
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001393 // If the referencee type isn't canonical, this won't be a canonical type
1394 // either, so fill in the canonical type field.
1395 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001396 if (InnerRef || !T.isCanonical()) {
1397 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1398 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001399
1400 // Get the new insert position for the node we care about.
1401 RValueReferenceType *NewIP =
1402 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001403 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001404 }
1405
John McCall90d1c2d2009-09-24 23:30:46 +00001406 RValueReferenceType *New
1407 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001408 Types.push_back(New);
1409 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001410 return QualType(New, 0);
1411}
1412
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001413/// getMemberPointerType - Return the uniqued reference to the type for a
1414/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001415QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001416 // Unique pointers, to guarantee there is only one pointer of a particular
1417 // structure.
1418 llvm::FoldingSetNodeID ID;
1419 MemberPointerType::Profile(ID, T, Cls);
1420
1421 void *InsertPos = 0;
1422 if (MemberPointerType *PT =
1423 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1424 return QualType(PT, 0);
1425
1426 // If the pointee or class type isn't canonical, this won't be a canonical
1427 // type either, so fill in the canonical type field.
1428 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001429 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001430 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1431
1432 // Get the new insert position for the node we care about.
1433 MemberPointerType *NewIP =
1434 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001435 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001436 }
John McCall90d1c2d2009-09-24 23:30:46 +00001437 MemberPointerType *New
1438 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001439 Types.push_back(New);
1440 MemberPointerTypes.InsertNode(New, InsertPos);
1441 return QualType(New, 0);
1442}
1443
Mike Stump11289f42009-09-09 15:08:12 +00001444/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001445/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001446QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001447 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001448 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001449 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001450 assert((EltTy->isDependentType() ||
1451 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001452 "Constant array of VLAs is illegal!");
1453
Chris Lattnere2df3f92009-05-13 04:12:56 +00001454 // Convert the array size into a canonical width matching the pointer size for
1455 // the target.
1456 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001457 ArySize =
1458 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattner23b7eb62007-06-15 23:05:46 +00001460 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001461 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001462
Chris Lattner36f8e652007-01-27 08:31:04 +00001463 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001464 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001465 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001466 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001467
John McCall33ddac02011-01-19 10:06:00 +00001468 // If the element type isn't canonical or has qualifiers, this won't
1469 // be a canonical type either, so fill in the canonical type field.
1470 QualType Canon;
1471 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1472 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1473 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001474 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001475 Canon = getQualifiedType(Canon, canonSplit.second);
1476
Chris Lattner36f8e652007-01-27 08:31:04 +00001477 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001478 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001479 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001480 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001481 }
Mike Stump11289f42009-09-09 15:08:12 +00001482
John McCall90d1c2d2009-09-24 23:30:46 +00001483 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001484 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001485 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001486 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001487 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001488}
1489
John McCall06549462011-01-18 08:40:38 +00001490/// getVariableArrayDecayedType - Turns the given type, which may be
1491/// variably-modified, into the corresponding type with all the known
1492/// sizes replaced with [*].
1493QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1494 // Vastly most common case.
1495 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001496
John McCall06549462011-01-18 08:40:38 +00001497 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001498
John McCall06549462011-01-18 08:40:38 +00001499 SplitQualType split = type.getSplitDesugaredType();
1500 const Type *ty = split.first;
1501 switch (ty->getTypeClass()) {
1502#define TYPE(Class, Base)
1503#define ABSTRACT_TYPE(Class, Base)
1504#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1505#include "clang/AST/TypeNodes.def"
1506 llvm_unreachable("didn't desugar past all non-canonical types?");
1507
1508 // These types should never be variably-modified.
1509 case Type::Builtin:
1510 case Type::Complex:
1511 case Type::Vector:
1512 case Type::ExtVector:
1513 case Type::DependentSizedExtVector:
1514 case Type::ObjCObject:
1515 case Type::ObjCInterface:
1516 case Type::ObjCObjectPointer:
1517 case Type::Record:
1518 case Type::Enum:
1519 case Type::UnresolvedUsing:
1520 case Type::TypeOfExpr:
1521 case Type::TypeOf:
1522 case Type::Decltype:
1523 case Type::DependentName:
1524 case Type::InjectedClassName:
1525 case Type::TemplateSpecialization:
1526 case Type::DependentTemplateSpecialization:
1527 case Type::TemplateTypeParm:
1528 case Type::SubstTemplateTypeParmPack:
1529 case Type::PackExpansion:
1530 llvm_unreachable("type should never be variably-modified");
1531
1532 // These types can be variably-modified but should never need to
1533 // further decay.
1534 case Type::FunctionNoProto:
1535 case Type::FunctionProto:
1536 case Type::BlockPointer:
1537 case Type::MemberPointer:
1538 return type;
1539
1540 // These types can be variably-modified. All these modifications
1541 // preserve structure except as noted by comments.
1542 // TODO: if we ever care about optimizing VLAs, there are no-op
1543 // optimizations available here.
1544 case Type::Pointer:
1545 result = getPointerType(getVariableArrayDecayedType(
1546 cast<PointerType>(ty)->getPointeeType()));
1547 break;
1548
1549 case Type::LValueReference: {
1550 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1551 result = getLValueReferenceType(
1552 getVariableArrayDecayedType(lv->getPointeeType()),
1553 lv->isSpelledAsLValue());
1554 break;
1555 }
1556
1557 case Type::RValueReference: {
1558 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1559 result = getRValueReferenceType(
1560 getVariableArrayDecayedType(lv->getPointeeType()));
1561 break;
1562 }
1563
1564 case Type::ConstantArray: {
1565 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1566 result = getConstantArrayType(
1567 getVariableArrayDecayedType(cat->getElementType()),
1568 cat->getSize(),
1569 cat->getSizeModifier(),
1570 cat->getIndexTypeCVRQualifiers());
1571 break;
1572 }
1573
1574 case Type::DependentSizedArray: {
1575 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1576 result = getDependentSizedArrayType(
1577 getVariableArrayDecayedType(dat->getElementType()),
1578 dat->getSizeExpr(),
1579 dat->getSizeModifier(),
1580 dat->getIndexTypeCVRQualifiers(),
1581 dat->getBracketsRange());
1582 break;
1583 }
1584
1585 // Turn incomplete types into [*] types.
1586 case Type::IncompleteArray: {
1587 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1588 result = getVariableArrayType(
1589 getVariableArrayDecayedType(iat->getElementType()),
1590 /*size*/ 0,
1591 ArrayType::Normal,
1592 iat->getIndexTypeCVRQualifiers(),
1593 SourceRange());
1594 break;
1595 }
1596
1597 // Turn VLA types into [*] types.
1598 case Type::VariableArray: {
1599 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1600 result = getVariableArrayType(
1601 getVariableArrayDecayedType(vat->getElementType()),
1602 /*size*/ 0,
1603 ArrayType::Star,
1604 vat->getIndexTypeCVRQualifiers(),
1605 vat->getBracketsRange());
1606 break;
1607 }
1608 }
1609
1610 // Apply the top-level qualifiers from the original.
1611 return getQualifiedType(result, split.second);
1612}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001613
Steve Naroffcadebd02007-08-30 18:14:25 +00001614/// getVariableArrayType - Returns a non-unique reference to the type for a
1615/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001616QualType ASTContext::getVariableArrayType(QualType EltTy,
1617 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001618 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001619 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001620 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001621 // Since we don't unique expressions, it isn't possible to unique VLA's
1622 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001623 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001624
John McCall33ddac02011-01-19 10:06:00 +00001625 // Be sure to pull qualifiers off the element type.
1626 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1627 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1628 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001629 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001630 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001631 }
1632
John McCall90d1c2d2009-09-24 23:30:46 +00001633 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001634 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001635
1636 VariableArrayTypes.push_back(New);
1637 Types.push_back(New);
1638 return QualType(New, 0);
1639}
1640
Douglas Gregor4619e432008-12-05 23:32:09 +00001641/// getDependentSizedArrayType - Returns a non-unique reference to
1642/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001643/// type.
John McCall33ddac02011-01-19 10:06:00 +00001644QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1645 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001646 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001647 unsigned elementTypeQuals,
1648 SourceRange brackets) const {
1649 assert((!numElements || numElements->isTypeDependent() ||
1650 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001651 "Size must be type- or value-dependent!");
1652
John McCall33ddac02011-01-19 10:06:00 +00001653 // Dependently-sized array types that do not have a specified number
1654 // of elements will have their sizes deduced from a dependent
1655 // initializer. We do no canonicalization here at all, which is okay
1656 // because they can't be used in most locations.
1657 if (!numElements) {
1658 DependentSizedArrayType *newType
1659 = new (*this, TypeAlignment)
1660 DependentSizedArrayType(*this, elementType, QualType(),
1661 numElements, ASM, elementTypeQuals,
1662 brackets);
1663 Types.push_back(newType);
1664 return QualType(newType, 0);
1665 }
1666
1667 // Otherwise, we actually build a new type every time, but we
1668 // also build a canonical type.
1669
1670 SplitQualType canonElementType = getCanonicalType(elementType).split();
1671
1672 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001673 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001674 DependentSizedArrayType::Profile(ID, *this,
1675 QualType(canonElementType.first, 0),
1676 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001677
John McCall33ddac02011-01-19 10:06:00 +00001678 // Look for an existing type with these properties.
1679 DependentSizedArrayType *canonTy =
1680 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001681
John McCall33ddac02011-01-19 10:06:00 +00001682 // If we don't have one, build one.
1683 if (!canonTy) {
1684 canonTy = new (*this, TypeAlignment)
1685 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1686 QualType(), numElements, ASM, elementTypeQuals,
1687 brackets);
1688 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1689 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001690 }
1691
John McCall33ddac02011-01-19 10:06:00 +00001692 // Apply qualifiers from the element type to the array.
1693 QualType canon = getQualifiedType(QualType(canonTy,0),
1694 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001695
John McCall33ddac02011-01-19 10:06:00 +00001696 // If we didn't need extra canonicalization for the element type,
1697 // then just use that as our result.
1698 if (QualType(canonElementType.first, 0) == elementType)
1699 return canon;
1700
1701 // Otherwise, we need to build a type which follows the spelling
1702 // of the element type.
1703 DependentSizedArrayType *sugaredType
1704 = new (*this, TypeAlignment)
1705 DependentSizedArrayType(*this, elementType, canon, numElements,
1706 ASM, elementTypeQuals, brackets);
1707 Types.push_back(sugaredType);
1708 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001709}
1710
John McCall33ddac02011-01-19 10:06:00 +00001711QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001712 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001713 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001714 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001715 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001716
John McCall33ddac02011-01-19 10:06:00 +00001717 void *insertPos = 0;
1718 if (IncompleteArrayType *iat =
1719 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1720 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001721
1722 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001723 // either, so fill in the canonical type field. We also have to pull
1724 // qualifiers off the element type.
1725 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001726
John McCall33ddac02011-01-19 10:06:00 +00001727 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1728 SplitQualType canonSplit = getCanonicalType(elementType).split();
1729 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1730 ASM, elementTypeQuals);
1731 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001732
1733 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001734 IncompleteArrayType *existing =
1735 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1736 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001737 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001738
John McCall33ddac02011-01-19 10:06:00 +00001739 IncompleteArrayType *newType = new (*this, TypeAlignment)
1740 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001741
John McCall33ddac02011-01-19 10:06:00 +00001742 IncompleteArrayTypes.InsertNode(newType, insertPos);
1743 Types.push_back(newType);
1744 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001745}
1746
Steve Naroff91fcddb2007-07-18 18:00:27 +00001747/// getVectorType - Return the unique reference to a vector type of
1748/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001749QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001750 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001751 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001752
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001753 // Check if we've already instantiated a vector of this type.
1754 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001755 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001756
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001757 void *InsertPos = 0;
1758 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1759 return QualType(VTP, 0);
1760
1761 // If the element type isn't canonical, this won't be a canonical type either,
1762 // so fill in the canonical type field.
1763 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001764 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001765 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001766
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001767 // Get the new insert position for the node we care about.
1768 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001769 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001770 }
John McCall90d1c2d2009-09-24 23:30:46 +00001771 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001772 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001773 VectorTypes.InsertNode(New, InsertPos);
1774 Types.push_back(New);
1775 return QualType(New, 0);
1776}
1777
Nate Begemance4d7fc2008-04-18 23:10:10 +00001778/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001779/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001780QualType
1781ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall33ddac02011-01-19 10:06:00 +00001782 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001783
Steve Naroff91fcddb2007-07-18 18:00:27 +00001784 // Check if we've already instantiated a vector of this type.
1785 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001786 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001787 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001788 void *InsertPos = 0;
1789 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1790 return QualType(VTP, 0);
1791
1792 // If the element type isn't canonical, this won't be a canonical type either,
1793 // so fill in the canonical type field.
1794 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001795 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001796 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001797
Steve Naroff91fcddb2007-07-18 18:00:27 +00001798 // Get the new insert position for the node we care about.
1799 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001800 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001801 }
John McCall90d1c2d2009-09-24 23:30:46 +00001802 ExtVectorType *New = new (*this, TypeAlignment)
1803 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001804 VectorTypes.InsertNode(New, InsertPos);
1805 Types.push_back(New);
1806 return QualType(New, 0);
1807}
1808
Jay Foad39c79802011-01-12 09:06:06 +00001809QualType
1810ASTContext::getDependentSizedExtVectorType(QualType vecType,
1811 Expr *SizeExpr,
1812 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001813 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001814 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001815 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001816
Douglas Gregor352169a2009-07-31 03:54:25 +00001817 void *InsertPos = 0;
1818 DependentSizedExtVectorType *Canon
1819 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1820 DependentSizedExtVectorType *New;
1821 if (Canon) {
1822 // We already have a canonical version of this array type; use it as
1823 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001824 New = new (*this, TypeAlignment)
1825 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1826 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001827 } else {
1828 QualType CanonVecTy = getCanonicalType(vecType);
1829 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001830 New = new (*this, TypeAlignment)
1831 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1832 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001833
1834 DependentSizedExtVectorType *CanonCheck
1835 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1836 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1837 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001838 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1839 } else {
1840 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1841 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001842 New = new (*this, TypeAlignment)
1843 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001844 }
1845 }
Mike Stump11289f42009-09-09 15:08:12 +00001846
Douglas Gregor758a8692009-06-17 21:51:59 +00001847 Types.push_back(New);
1848 return QualType(New, 0);
1849}
1850
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001851/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001852///
Jay Foad39c79802011-01-12 09:06:06 +00001853QualType
1854ASTContext::getFunctionNoProtoType(QualType ResultTy,
1855 const FunctionType::ExtInfo &Info) const {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001856 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001857 // Unique functions, to guarantee there is only one function of a particular
1858 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001859 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001860 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Chris Lattner47955de2007-01-27 08:37:20 +00001862 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001863 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001864 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001865 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001866
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001867 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001868 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001869 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001870 Canonical =
1871 getFunctionNoProtoType(getCanonicalType(ResultTy),
1872 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001873
Chris Lattner47955de2007-01-27 08:37:20 +00001874 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001875 FunctionNoProtoType *NewIP =
1876 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001877 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001878 }
Mike Stump11289f42009-09-09 15:08:12 +00001879
John McCall90d1c2d2009-09-24 23:30:46 +00001880 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001881 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001882 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001883 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001884 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001885}
1886
1887/// getFunctionType - Return a normal function type with a typed argument
1888/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001889QualType
1890ASTContext::getFunctionType(QualType ResultTy,
1891 const QualType *ArgArray, unsigned NumArgs,
1892 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001893 // Unique functions, to guarantee there is only one function of a particular
1894 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001895 llvm::FoldingSetNodeID ID;
John McCalldb40c7f2010-12-14 08:05:40 +00001896 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001897
1898 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001899 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001900 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001901 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001902
1903 // Determine whether the type being created is already canonical or not.
John McCalldb40c7f2010-12-14 08:05:40 +00001904 bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001905 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001906 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001907 isCanonical = false;
1908
John McCalldb40c7f2010-12-14 08:05:40 +00001909 const CallingConv CallConv = EPI.ExtInfo.getCC();
1910
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001911 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001912 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001913 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001914 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001915 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001916 CanonicalArgs.reserve(NumArgs);
1917 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001918 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001919
John McCalldb40c7f2010-12-14 08:05:40 +00001920 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1921 if (CanonicalEPI.HasExceptionSpec) {
1922 CanonicalEPI.HasExceptionSpec = false;
1923 CanonicalEPI.HasAnyExceptionSpec = false;
1924 CanonicalEPI.NumExceptions = 0;
1925 }
1926 CanonicalEPI.ExtInfo
1927 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1928
Chris Lattner76a00cf2008-04-06 22:59:24 +00001929 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001930 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00001931 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001932
Chris Lattnerfd4de792007-01-27 01:15:32 +00001933 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001934 FunctionProtoType *NewIP =
1935 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001936 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001937 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001938
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001939 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001940 // for two variable size arrays (for parameter and exception types) at the
1941 // end of them.
John McCalldb40c7f2010-12-14 08:05:40 +00001942 size_t Size = sizeof(FunctionProtoType) +
1943 NumArgs * sizeof(QualType) +
1944 EPI.NumExceptions * sizeof(QualType);
1945 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
1946 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, EPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001947 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001948 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001949 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001950}
Chris Lattneref51c202006-11-10 07:17:23 +00001951
John McCalle78aac42010-03-10 03:28:59 +00001952#ifndef NDEBUG
1953static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1954 if (!isa<CXXRecordDecl>(D)) return false;
1955 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1956 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1957 return true;
1958 if (RD->getDescribedClassTemplate() &&
1959 !isa<ClassTemplateSpecializationDecl>(RD))
1960 return true;
1961 return false;
1962}
1963#endif
1964
1965/// getInjectedClassNameType - Return the unique reference to the
1966/// injected class name type for the specified templated declaration.
1967QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00001968 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00001969 assert(NeedsInjectedClassNameType(Decl));
1970 if (Decl->TypeForDecl) {
1971 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001972 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001973 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1974 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1975 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1976 } else {
John McCall424cec92011-01-19 06:33:43 +00001977 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00001978 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00001979 Decl->TypeForDecl = newType;
1980 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00001981 }
1982 return QualType(Decl->TypeForDecl, 0);
1983}
1984
Douglas Gregor83a586e2008-04-13 21:07:44 +00001985/// getTypeDeclType - Return the unique reference to the type for the
1986/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00001987QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001988 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001989 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001990
John McCall81e38502010-02-16 03:57:14 +00001991 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001992 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001993
John McCall96f0b5f2010-03-10 06:48:02 +00001994 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1995 "Template type parameter types are always available.");
1996
John McCall81e38502010-02-16 03:57:14 +00001997 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001998 assert(!Record->getPreviousDeclaration() &&
1999 "struct/union has previous declaration");
2000 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002001 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002002 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002003 assert(!Enum->getPreviousDeclaration() &&
2004 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002005 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002006 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002007 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002008 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2009 Decl->TypeForDecl = newType;
2010 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002011 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002012 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002013
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002014 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002015}
2016
Chris Lattner32d920b2007-01-26 02:01:53 +00002017/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00002018/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002019QualType
Jay Foad39c79802011-01-12 09:06:06 +00002020ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002021 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002022
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002023 if (Canonical.isNull())
2024 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002025 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002026 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002027 Decl->TypeForDecl = newType;
2028 Types.push_back(newType);
2029 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002030}
2031
Jay Foad39c79802011-01-12 09:06:06 +00002032QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002033 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2034
2035 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2036 if (PrevDecl->TypeForDecl)
2037 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2038
John McCall424cec92011-01-19 06:33:43 +00002039 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2040 Decl->TypeForDecl = newType;
2041 Types.push_back(newType);
2042 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002043}
2044
Jay Foad39c79802011-01-12 09:06:06 +00002045QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002046 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2047
2048 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2049 if (PrevDecl->TypeForDecl)
2050 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2051
John McCall424cec92011-01-19 06:33:43 +00002052 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2053 Decl->TypeForDecl = newType;
2054 Types.push_back(newType);
2055 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002056}
2057
John McCall81904512011-01-06 01:58:22 +00002058QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2059 QualType modifiedType,
2060 QualType equivalentType) {
2061 llvm::FoldingSetNodeID id;
2062 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2063
2064 void *insertPos = 0;
2065 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2066 if (type) return QualType(type, 0);
2067
2068 QualType canon = getCanonicalType(equivalentType);
2069 type = new (*this, TypeAlignment)
2070 AttributedType(canon, attrKind, modifiedType, equivalentType);
2071
2072 Types.push_back(type);
2073 AttributedTypes.InsertNode(type, insertPos);
2074
2075 return QualType(type, 0);
2076}
2077
2078
John McCallcebee162009-10-18 09:09:24 +00002079/// \brief Retrieve a substitution-result type.
2080QualType
2081ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002082 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002083 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002084 && "replacement types must always be canonical");
2085
2086 llvm::FoldingSetNodeID ID;
2087 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2088 void *InsertPos = 0;
2089 SubstTemplateTypeParmType *SubstParm
2090 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2091
2092 if (!SubstParm) {
2093 SubstParm = new (*this, TypeAlignment)
2094 SubstTemplateTypeParmType(Parm, Replacement);
2095 Types.push_back(SubstParm);
2096 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2097 }
2098
2099 return QualType(SubstParm, 0);
2100}
2101
Douglas Gregorada4b792011-01-14 02:55:32 +00002102/// \brief Retrieve a
2103QualType ASTContext::getSubstTemplateTypeParmPackType(
2104 const TemplateTypeParmType *Parm,
2105 const TemplateArgument &ArgPack) {
2106#ifndef NDEBUG
2107 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2108 PEnd = ArgPack.pack_end();
2109 P != PEnd; ++P) {
2110 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2111 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2112 }
2113#endif
2114
2115 llvm::FoldingSetNodeID ID;
2116 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2117 void *InsertPos = 0;
2118 if (SubstTemplateTypeParmPackType *SubstParm
2119 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2120 return QualType(SubstParm, 0);
2121
2122 QualType Canon;
2123 if (!Parm->isCanonicalUnqualified()) {
2124 Canon = getCanonicalType(QualType(Parm, 0));
2125 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2126 ArgPack);
2127 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2128 }
2129
2130 SubstTemplateTypeParmPackType *SubstParm
2131 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2132 ArgPack);
2133 Types.push_back(SubstParm);
2134 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2135 return QualType(SubstParm, 0);
2136}
2137
Douglas Gregoreff93e02009-02-05 23:33:38 +00002138/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002139/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002140/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002141QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002142 bool ParameterPack,
Jay Foad39c79802011-01-12 09:06:06 +00002143 IdentifierInfo *Name) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002144 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002145 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002146 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002147 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002148 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2149
2150 if (TypeParm)
2151 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002152
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002153 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002154 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002155 TypeParm = new (*this, TypeAlignment)
2156 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002157
2158 TemplateTypeParmType *TypeCheck
2159 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2160 assert(!TypeCheck && "Template type parameter canonical type broken");
2161 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002162 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002163 TypeParm = new (*this, TypeAlignment)
2164 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002165
2166 Types.push_back(TypeParm);
2167 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2168
2169 return QualType(TypeParm, 0);
2170}
2171
John McCalle78aac42010-03-10 03:28:59 +00002172TypeSourceInfo *
2173ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2174 SourceLocation NameLoc,
2175 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002176 QualType CanonType) const {
John McCalle78aac42010-03-10 03:28:59 +00002177 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2178
2179 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2180 TemplateSpecializationTypeLoc TL
2181 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2182 TL.setTemplateNameLoc(NameLoc);
2183 TL.setLAngleLoc(Args.getLAngleLoc());
2184 TL.setRAngleLoc(Args.getRAngleLoc());
2185 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2186 TL.setArgLocInfo(i, Args[i].getLocInfo());
2187 return DI;
2188}
2189
Mike Stump11289f42009-09-09 15:08:12 +00002190QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002191ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002192 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002193 QualType Canon) const {
John McCall6b51f282009-11-23 01:53:49 +00002194 unsigned NumArgs = Args.size();
2195
John McCall0ad16662009-10-29 08:12:44 +00002196 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2197 ArgVec.reserve(NumArgs);
2198 for (unsigned i = 0; i != NumArgs; ++i)
2199 ArgVec.push_back(Args[i].getArgument());
2200
John McCall2408e322010-04-27 00:57:59 +00002201 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00002202 Canon);
John McCall0ad16662009-10-29 08:12:44 +00002203}
2204
2205QualType
2206ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002207 const TemplateArgument *Args,
2208 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002209 QualType Canon) const {
Douglas Gregor15301382009-07-30 17:40:51 +00002210 if (!Canon.isNull())
2211 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002212 else
2213 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00002214
Douglas Gregora8e02e72009-07-28 23:00:59 +00002215 // Allocate the (non-canonical) template specialization type, but don't
2216 // try to unique it: these types typically have location information that
2217 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002218 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002219 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002220 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002221 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002222 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002223 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002224 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002225
Douglas Gregor8bf42052009-02-09 18:46:07 +00002226 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002227 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002228}
2229
Mike Stump11289f42009-09-09 15:08:12 +00002230QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002231ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2232 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002233 unsigned NumArgs) const {
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002234 // Build the canonical template specialization type.
2235 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2236 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2237 CanonArgs.reserve(NumArgs);
2238 for (unsigned I = 0; I != NumArgs; ++I)
2239 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2240
2241 // Determine whether this canonical template specialization type already
2242 // exists.
2243 llvm::FoldingSetNodeID ID;
2244 TemplateSpecializationType::Profile(ID, CanonTemplate,
2245 CanonArgs.data(), NumArgs, *this);
2246
2247 void *InsertPos = 0;
2248 TemplateSpecializationType *Spec
2249 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2250
2251 if (!Spec) {
2252 // Allocate a new canonical template specialization type.
2253 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2254 sizeof(TemplateArgument) * NumArgs),
2255 TypeAlignment);
2256 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2257 CanonArgs.data(), NumArgs,
2258 QualType());
2259 Types.push_back(Spec);
2260 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2261 }
2262
2263 assert(Spec->isDependentType() &&
2264 "Non-dependent template-id type must have a canonical type");
2265 return QualType(Spec, 0);
2266}
2267
2268QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002269ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2270 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002271 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002272 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002273 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002274
2275 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002276 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002277 if (T)
2278 return QualType(T, 0);
2279
Douglas Gregorc42075a2010-02-04 18:10:26 +00002280 QualType Canon = NamedType;
2281 if (!Canon.isCanonical()) {
2282 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002283 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2284 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002285 (void)CheckT;
2286 }
2287
Abramo Bagnara6150c882010-05-11 21:36:43 +00002288 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002289 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002290 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002291 return QualType(T, 0);
2292}
2293
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002294QualType
Jay Foad39c79802011-01-12 09:06:06 +00002295ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002296 llvm::FoldingSetNodeID ID;
2297 ParenType::Profile(ID, InnerType);
2298
2299 void *InsertPos = 0;
2300 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2301 if (T)
2302 return QualType(T, 0);
2303
2304 QualType Canon = InnerType;
2305 if (!Canon.isCanonical()) {
2306 Canon = getCanonicalType(InnerType);
2307 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2308 assert(!CheckT && "Paren canonical type broken");
2309 (void)CheckT;
2310 }
2311
2312 T = new (*this) ParenType(InnerType, Canon);
2313 Types.push_back(T);
2314 ParenTypes.InsertNode(T, InsertPos);
2315 return QualType(T, 0);
2316}
2317
Douglas Gregor02085352010-03-31 20:19:30 +00002318QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2319 NestedNameSpecifier *NNS,
2320 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002321 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002322 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2323
2324 if (Canon.isNull()) {
2325 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002326 ElaboratedTypeKeyword CanonKeyword = Keyword;
2327 if (Keyword == ETK_None)
2328 CanonKeyword = ETK_Typename;
2329
2330 if (CanonNNS != NNS || CanonKeyword != Keyword)
2331 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002332 }
2333
2334 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002335 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002336
2337 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002338 DependentNameType *T
2339 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002340 if (T)
2341 return QualType(T, 0);
2342
Douglas Gregor02085352010-03-31 20:19:30 +00002343 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002344 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002345 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002346 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002347}
2348
Mike Stump11289f42009-09-09 15:08:12 +00002349QualType
John McCallc392f372010-06-11 00:33:02 +00002350ASTContext::getDependentTemplateSpecializationType(
2351 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002352 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002353 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002354 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002355 // TODO: avoid this copy
2356 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2357 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2358 ArgCopy.push_back(Args[I].getArgument());
2359 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2360 ArgCopy.size(),
2361 ArgCopy.data());
2362}
2363
2364QualType
2365ASTContext::getDependentTemplateSpecializationType(
2366 ElaboratedTypeKeyword Keyword,
2367 NestedNameSpecifier *NNS,
2368 const IdentifierInfo *Name,
2369 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002370 const TemplateArgument *Args) const {
Douglas Gregordce2b622009-04-01 00:28:59 +00002371 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2372
Douglas Gregorc42075a2010-02-04 18:10:26 +00002373 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002374 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2375 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002376
2377 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002378 DependentTemplateSpecializationType *T
2379 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002380 if (T)
2381 return QualType(T, 0);
2382
John McCallc392f372010-06-11 00:33:02 +00002383 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002384
John McCallc392f372010-06-11 00:33:02 +00002385 ElaboratedTypeKeyword CanonKeyword = Keyword;
2386 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2387
2388 bool AnyNonCanonArgs = false;
2389 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2390 for (unsigned I = 0; I != NumArgs; ++I) {
2391 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2392 if (!CanonArgs[I].structurallyEquals(Args[I]))
2393 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002394 }
2395
John McCallc392f372010-06-11 00:33:02 +00002396 QualType Canon;
2397 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2398 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2399 Name, NumArgs,
2400 CanonArgs.data());
2401
2402 // Find the insert position again.
2403 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2404 }
2405
2406 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2407 sizeof(TemplateArgument) * NumArgs),
2408 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002409 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002410 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002411 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002412 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002413 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002414}
2415
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002416QualType ASTContext::getPackExpansionType(QualType Pattern,
2417 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002418 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002419 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002420
2421 assert(Pattern->containsUnexpandedParameterPack() &&
2422 "Pack expansions must expand one or more parameter packs");
2423 void *InsertPos = 0;
2424 PackExpansionType *T
2425 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2426 if (T)
2427 return QualType(T, 0);
2428
2429 QualType Canon;
2430 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002431 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002432
2433 // Find the insert position again.
2434 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2435 }
2436
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002437 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002438 Types.push_back(T);
2439 PackExpansionTypes.InsertNode(T, InsertPos);
2440 return QualType(T, 0);
2441}
2442
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002443/// CmpProtocolNames - Comparison predicate for sorting protocols
2444/// alphabetically.
2445static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2446 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002447 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002448}
2449
John McCall8b07ec22010-05-15 11:32:37 +00002450static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002451 unsigned NumProtocols) {
2452 if (NumProtocols == 0) return true;
2453
2454 for (unsigned i = 1; i != NumProtocols; ++i)
2455 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2456 return false;
2457 return true;
2458}
2459
2460static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002461 unsigned &NumProtocols) {
2462 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002463
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002464 // Sort protocols, keyed by name.
2465 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2466
2467 // Remove duplicates.
2468 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2469 NumProtocols = ProtocolsEnd-Protocols;
2470}
2471
John McCall8b07ec22010-05-15 11:32:37 +00002472QualType ASTContext::getObjCObjectType(QualType BaseType,
2473 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002474 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002475 // If the base type is an interface and there aren't any protocols
2476 // to add, then the interface type will do just fine.
2477 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2478 return BaseType;
2479
2480 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002481 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002482 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002483 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002484 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2485 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002486
John McCall8b07ec22010-05-15 11:32:37 +00002487 // Build the canonical type, which has the canonical base type and
2488 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002489 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002490 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2491 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2492 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002493 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2494 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002495 unsigned UniqueCount = NumProtocols;
2496
John McCallfc93cf92009-10-22 22:37:11 +00002497 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002498 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2499 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002500 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002501 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2502 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002503 }
2504
2505 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002506 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2507 }
2508
2509 unsigned Size = sizeof(ObjCObjectTypeImpl);
2510 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2511 void *Mem = Allocate(Size, TypeAlignment);
2512 ObjCObjectTypeImpl *T =
2513 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2514
2515 Types.push_back(T);
2516 ObjCObjectTypes.InsertNode(T, InsertPos);
2517 return QualType(T, 0);
2518}
2519
2520/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2521/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002522QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002523 llvm::FoldingSetNodeID ID;
2524 ObjCObjectPointerType::Profile(ID, ObjectT);
2525
2526 void *InsertPos = 0;
2527 if (ObjCObjectPointerType *QT =
2528 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2529 return QualType(QT, 0);
2530
2531 // Find the canonical object type.
2532 QualType Canonical;
2533 if (!ObjectT.isCanonical()) {
2534 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2535
2536 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002537 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2538 }
2539
Douglas Gregorf85bee62010-02-08 22:59:26 +00002540 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002541 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2542 ObjCObjectPointerType *QType =
2543 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002544
Steve Narofffb4330f2009-06-17 22:40:22 +00002545 Types.push_back(QType);
2546 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002547 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002548}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002549
Douglas Gregor1c283312010-08-11 12:19:30 +00002550/// getObjCInterfaceType - Return the unique reference to the type for the
2551/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002552QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002553 if (Decl->TypeForDecl)
2554 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002555
Douglas Gregor1c283312010-08-11 12:19:30 +00002556 // FIXME: redeclarations?
2557 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2558 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2559 Decl->TypeForDecl = T;
2560 Types.push_back(T);
2561 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002562}
2563
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002564/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2565/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002566/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002567/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002568/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002569QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002570 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002571 if (tofExpr->isTypeDependent()) {
2572 llvm::FoldingSetNodeID ID;
2573 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002574
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002575 void *InsertPos = 0;
2576 DependentTypeOfExprType *Canon
2577 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2578 if (Canon) {
2579 // We already have a "canonical" version of an identical, dependent
2580 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002581 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002582 QualType((TypeOfExprType*)Canon, 0));
2583 }
2584 else {
2585 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002586 Canon
2587 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002588 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2589 toe = Canon;
2590 }
2591 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002592 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002593 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002594 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002595 Types.push_back(toe);
2596 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002597}
2598
Steve Naroffa773cd52007-08-01 18:02:17 +00002599/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2600/// TypeOfType AST's. The only motivation to unique these nodes would be
2601/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002602/// an issue. 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::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002605 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002606 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002607 Types.push_back(tot);
2608 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002609}
2610
Anders Carlssonad6bd352009-06-24 21:24:56 +00002611/// getDecltypeForExpr - Given an expr, will return the decltype for that
2612/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002613static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002614 if (e->isTypeDependent())
2615 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002616
Anders Carlssonad6bd352009-06-24 21:24:56 +00002617 // If e is an id expression or a class member access, decltype(e) is defined
2618 // as the type of the entity named by e.
2619 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2620 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2621 return VD->getType();
2622 }
2623 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2624 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2625 return FD->getType();
2626 }
2627 // If e is a function call or an invocation of an overloaded operator,
2628 // (parentheses around e are ignored), decltype(e) is defined as the
2629 // return type of that function.
2630 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2631 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002632
Anders Carlssonad6bd352009-06-24 21:24:56 +00002633 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002634
2635 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002636 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002637 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002638 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002639
Anders Carlssonad6bd352009-06-24 21:24:56 +00002640 return T;
2641}
2642
Anders Carlsson81df7b82009-06-24 19:06:50 +00002643/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2644/// DecltypeType AST's. The only motivation to unique these nodes would be
2645/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002646/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002647/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002648QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002649 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002650 if (e->isTypeDependent()) {
2651 llvm::FoldingSetNodeID ID;
2652 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002653
Douglas Gregora21f6c32009-07-30 23:36:40 +00002654 void *InsertPos = 0;
2655 DependentDecltypeType *Canon
2656 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2657 if (Canon) {
2658 // We already have a "canonical" version of an equivalent, dependent
2659 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002660 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002661 QualType((DecltypeType*)Canon, 0));
2662 }
2663 else {
2664 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002665 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002666 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2667 dt = Canon;
2668 }
2669 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002670 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002671 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002672 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002673 Types.push_back(dt);
2674 return QualType(dt, 0);
2675}
2676
Chris Lattnerfb072462007-01-23 05:45:31 +00002677/// getTagDeclType - Return the unique reference to the type for the
2678/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002679QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002680 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002681 // FIXME: What is the design on getTagDeclType when it requires casting
2682 // away const? mutable?
2683 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002684}
2685
Mike Stump11289f42009-09-09 15:08:12 +00002686/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2687/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2688/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002689CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002690 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002691}
Chris Lattnerfb072462007-01-23 05:45:31 +00002692
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002693/// getSignedWCharType - Return the type of "signed wchar_t".
2694/// Used when in C++, as a GCC extension.
2695QualType ASTContext::getSignedWCharType() const {
2696 // FIXME: derive from "Target" ?
2697 return WCharTy;
2698}
2699
2700/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2701/// Used when in C++, as a GCC extension.
2702QualType ASTContext::getUnsignedWCharType() const {
2703 // FIXME: derive from "Target" ?
2704 return UnsignedIntTy;
2705}
2706
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002707/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2708/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2709QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002710 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002711}
2712
Chris Lattnera21ad802008-04-02 05:18:44 +00002713//===----------------------------------------------------------------------===//
2714// Type Operators
2715//===----------------------------------------------------------------------===//
2716
Jay Foad39c79802011-01-12 09:06:06 +00002717CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002718 // Push qualifiers into arrays, and then discard any remaining
2719 // qualifiers.
2720 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002721 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002722 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002723 QualType Result;
2724 if (isa<ArrayType>(Ty)) {
2725 Result = getArrayDecayedType(QualType(Ty,0));
2726 } else if (isa<FunctionType>(Ty)) {
2727 Result = getPointerType(QualType(Ty, 0));
2728 } else {
2729 Result = QualType(Ty, 0);
2730 }
2731
2732 return CanQualType::CreateUnsafe(Result);
2733}
2734
Chris Lattner7adf0762008-08-04 07:31:14 +00002735
John McCall6c9dd522011-01-18 07:41:22 +00002736QualType ASTContext::getUnqualifiedArrayType(QualType type,
2737 Qualifiers &quals) {
2738 SplitQualType splitType = type.getSplitUnqualifiedType();
2739
2740 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2741 // the unqualified desugared type and then drops it on the floor.
2742 // We then have to strip that sugar back off with
2743 // getUnqualifiedDesugaredType(), which is silly.
2744 const ArrayType *AT =
2745 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2746
2747 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002748 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002749 quals = splitType.second;
2750 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002751 }
2752
John McCall6c9dd522011-01-18 07:41:22 +00002753 // Otherwise, recurse on the array's element type.
2754 QualType elementType = AT->getElementType();
2755 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2756
2757 // If that didn't change the element type, AT has no qualifiers, so we
2758 // can just use the results in splitType.
2759 if (elementType == unqualElementType) {
2760 assert(quals.empty()); // from the recursive call
2761 quals = splitType.second;
2762 return QualType(splitType.first, 0);
2763 }
2764
2765 // Otherwise, add in the qualifiers from the outermost type, then
2766 // build the type back up.
2767 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002768
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002769 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002770 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002771 CAT->getSizeModifier(), 0);
2772 }
2773
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002774 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002775 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002776 }
2777
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002778 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002779 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002780 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002781 VAT->getSizeModifier(),
2782 VAT->getIndexTypeCVRQualifiers(),
2783 VAT->getBracketsRange());
2784 }
2785
2786 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002787 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002788 DSAT->getSizeModifier(), 0,
2789 SourceRange());
2790}
2791
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002792/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2793/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2794/// they point to and return true. If T1 and T2 aren't pointer types
2795/// or pointer-to-member types, or if they are not similar at this
2796/// level, returns false and leaves T1 and T2 unchanged. Top-level
2797/// qualifiers on T1 and T2 are ignored. This function will typically
2798/// be called in a loop that successively "unwraps" pointer and
2799/// pointer-to-member types to compare them at each level.
2800bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2801 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2802 *T2PtrType = T2->getAs<PointerType>();
2803 if (T1PtrType && T2PtrType) {
2804 T1 = T1PtrType->getPointeeType();
2805 T2 = T2PtrType->getPointeeType();
2806 return true;
2807 }
2808
2809 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2810 *T2MPType = T2->getAs<MemberPointerType>();
2811 if (T1MPType && T2MPType &&
2812 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2813 QualType(T2MPType->getClass(), 0))) {
2814 T1 = T1MPType->getPointeeType();
2815 T2 = T2MPType->getPointeeType();
2816 return true;
2817 }
2818
2819 if (getLangOptions().ObjC1) {
2820 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2821 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2822 if (T1OPType && T2OPType) {
2823 T1 = T1OPType->getPointeeType();
2824 T2 = T2OPType->getPointeeType();
2825 return true;
2826 }
2827 }
2828
2829 // FIXME: Block pointers, too?
2830
2831 return false;
2832}
2833
Jay Foad39c79802011-01-12 09:06:06 +00002834DeclarationNameInfo
2835ASTContext::getNameForTemplate(TemplateName Name,
2836 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002837 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002838 // DNInfo work in progress: CHECKME: what about DNLoc?
2839 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2840
John McCall847e2a12009-11-24 18:42:40 +00002841 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002842 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002843 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002844 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2845 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002846 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002847 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2848 // DNInfo work in progress: FIXME: source locations?
2849 DeclarationNameLoc DNLoc;
2850 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2851 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2852 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002853 }
2854 }
2855
John McCalld28ae272009-12-02 08:04:21 +00002856 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2857 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002858 // DNInfo work in progress: CHECKME: what about DNLoc?
2859 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002860}
2861
Jay Foad39c79802011-01-12 09:06:06 +00002862TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002863 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2864 if (TemplateTemplateParmDecl *TTP
2865 = dyn_cast<TemplateTemplateParmDecl>(Template))
2866 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2867
2868 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002869 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002870 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002871
Douglas Gregor5590be02011-01-15 06:45:20 +00002872 if (SubstTemplateTemplateParmPackStorage *SubstPack
2873 = Name.getAsSubstTemplateTemplateParmPack()) {
2874 TemplateTemplateParmDecl *CanonParam
2875 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2876 TemplateArgument CanonArgPack
2877 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2878 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2879 }
2880
John McCalld28ae272009-12-02 08:04:21 +00002881 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002882
Douglas Gregor6bc50582009-05-07 06:41:52 +00002883 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2884 assert(DTN && "Non-dependent template names must refer to template decls.");
2885 return DTN->CanonicalTemplateName;
2886}
2887
Douglas Gregoradee3e32009-11-11 23:06:43 +00002888bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2889 X = getCanonicalTemplateName(X);
2890 Y = getCanonicalTemplateName(Y);
2891 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2892}
2893
Mike Stump11289f42009-09-09 15:08:12 +00002894TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00002895ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00002896 switch (Arg.getKind()) {
2897 case TemplateArgument::Null:
2898 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002899
Douglas Gregora8e02e72009-07-28 23:00:59 +00002900 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002901 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002902
Douglas Gregora8e02e72009-07-28 23:00:59 +00002903 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002904 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002905
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002906 case TemplateArgument::Template:
2907 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002908
2909 case TemplateArgument::TemplateExpansion:
2910 return TemplateArgument(getCanonicalTemplateName(
2911 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00002912 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002913
Douglas Gregora8e02e72009-07-28 23:00:59 +00002914 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002915 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002916 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002917
Douglas Gregora8e02e72009-07-28 23:00:59 +00002918 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002919 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002920
Douglas Gregora8e02e72009-07-28 23:00:59 +00002921 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00002922 if (Arg.pack_size() == 0)
2923 return Arg;
2924
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002925 TemplateArgument *CanonArgs
2926 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00002927 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002928 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002929 AEnd = Arg.pack_end();
2930 A != AEnd; (void)++A, ++Idx)
2931 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002932
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002933 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00002934 }
2935 }
2936
2937 // Silence GCC warning
2938 assert(false && "Unhandled template argument kind");
2939 return TemplateArgument();
2940}
2941
Douglas Gregor333489b2009-03-27 23:10:48 +00002942NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00002943ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00002944 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002945 return 0;
2946
2947 switch (NNS->getKind()) {
2948 case NestedNameSpecifier::Identifier:
2949 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002950 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002951 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2952 NNS->getAsIdentifier());
2953
2954 case NestedNameSpecifier::Namespace:
2955 // A namespace is canonical; build a nested-name-specifier with
2956 // this namespace and no prefix.
2957 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2958
2959 case NestedNameSpecifier::TypeSpec:
2960 case NestedNameSpecifier::TypeSpecWithTemplate: {
2961 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00002962
2963 // If we have some kind of dependent-named type (e.g., "typename T::type"),
2964 // break it apart into its prefix and identifier, then reconsititute those
2965 // as the canonical nested-name-specifier. This is required to canonicalize
2966 // a dependent nested-name-specifier involving typedefs of dependent-name
2967 // types, e.g.,
2968 // typedef typename T::type T1;
2969 // typedef typename T1::type T2;
2970 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
2971 NestedNameSpecifier *Prefix
2972 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
2973 return NestedNameSpecifier::Create(*this, Prefix,
2974 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
2975 }
2976
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00002977 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00002978 if (const DependentTemplateSpecializationType *DTST
2979 = T->getAs<DependentTemplateSpecializationType>()) {
2980 NestedNameSpecifier *Prefix
2981 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
2982 TemplateName Name
2983 = getDependentTemplateName(Prefix, DTST->getIdentifier());
2984 T = getTemplateSpecializationType(Name,
2985 DTST->getArgs(), DTST->getNumArgs());
2986 T = getCanonicalType(T);
2987 }
2988
John McCall33ddac02011-01-19 10:06:00 +00002989 return NestedNameSpecifier::Create(*this, 0, false,
2990 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00002991 }
2992
2993 case NestedNameSpecifier::Global:
2994 // The global specifier is canonical and unique.
2995 return NNS;
2996 }
2997
2998 // Required to silence a GCC warning
2999 return 0;
3000}
3001
Chris Lattner7adf0762008-08-04 07:31:14 +00003002
Jay Foad39c79802011-01-12 09:06:06 +00003003const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003004 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003005 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003006 // Handle the common positive case fast.
3007 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3008 return AT;
3009 }
Mike Stump11289f42009-09-09 15:08:12 +00003010
John McCall8ccfcb52009-09-24 19:53:00 +00003011 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003012 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003013 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003014
John McCall8ccfcb52009-09-24 19:53:00 +00003015 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003016 // implements C99 6.7.3p8: "If the specification of an array type includes
3017 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003018
Chris Lattner7adf0762008-08-04 07:31:14 +00003019 // If we get here, we either have type qualifiers on the type, or we have
3020 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003021 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003022
John McCall33ddac02011-01-19 10:06:00 +00003023 SplitQualType split = T.getSplitDesugaredType();
3024 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003025
Chris Lattner7adf0762008-08-04 07:31:14 +00003026 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003027 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3028 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003029 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003030
Chris Lattner7adf0762008-08-04 07:31:14 +00003031 // Otherwise, we have an array and we have qualifiers on it. Push the
3032 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003033 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003034
Chris Lattner7adf0762008-08-04 07:31:14 +00003035 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3036 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3037 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003038 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003039 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3040 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3041 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003042 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003043
Mike Stump11289f42009-09-09 15:08:12 +00003044 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003045 = dyn_cast<DependentSizedArrayType>(ATy))
3046 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003047 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003048 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003049 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003050 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003051 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003052
Chris Lattner7adf0762008-08-04 07:31:14 +00003053 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003054 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003055 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003056 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003057 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003058 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003059}
3060
Chris Lattnera21ad802008-04-02 05:18:44 +00003061/// getArrayDecayedType - Return the properly qualified result of decaying the
3062/// specified array type to a pointer. This operation is non-trivial when
3063/// handling typedefs etc. The canonical type of "T" must be an array type,
3064/// this returns a pointer to a properly qualified element of the array.
3065///
3066/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003067QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003068 // Get the element type with 'getAsArrayType' so that we don't lose any
3069 // typedefs in the element type of the array. This also handles propagation
3070 // of type qualifiers from the array type into the element type if present
3071 // (C99 6.7.3p8).
3072 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3073 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003074
Chris Lattner7adf0762008-08-04 07:31:14 +00003075 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003076
3077 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003078 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003079}
3080
John McCall33ddac02011-01-19 10:06:00 +00003081QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3082 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003083}
3084
John McCall33ddac02011-01-19 10:06:00 +00003085QualType ASTContext::getBaseElementType(QualType type) const {
3086 Qualifiers qs;
3087 while (true) {
3088 SplitQualType split = type.getSplitDesugaredType();
3089 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3090 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003091
John McCall33ddac02011-01-19 10:06:00 +00003092 type = array->getElementType();
3093 qs.addConsistentQualifiers(split.second);
3094 }
Mike Stump11289f42009-09-09 15:08:12 +00003095
John McCall33ddac02011-01-19 10:06:00 +00003096 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003097}
3098
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003099/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003100uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003101ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3102 uint64_t ElementCount = 1;
3103 do {
3104 ElementCount *= CA->getSize().getZExtValue();
3105 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3106 } while (CA);
3107 return ElementCount;
3108}
3109
Steve Naroff0af91202007-04-27 21:51:21 +00003110/// getFloatingRank - Return a relative rank for floating point types.
3111/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003112static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003113 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003114 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003115
John McCall9dd450b2009-09-21 23:43:11 +00003116 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3117 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003118 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003119 case BuiltinType::Float: return FloatRank;
3120 case BuiltinType::Double: return DoubleRank;
3121 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003122 }
3123}
3124
Mike Stump11289f42009-09-09 15:08:12 +00003125/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3126/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003127/// 'typeDomain' is a real floating point or complex type.
3128/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003129QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3130 QualType Domain) const {
3131 FloatingRank EltRank = getFloatingRank(Size);
3132 if (Domain->isComplexType()) {
3133 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003134 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003135 case FloatRank: return FloatComplexTy;
3136 case DoubleRank: return DoubleComplexTy;
3137 case LongDoubleRank: return LongDoubleComplexTy;
3138 }
Steve Naroff0af91202007-04-27 21:51:21 +00003139 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003140
3141 assert(Domain->isRealFloatingType() && "Unknown domain!");
3142 switch (EltRank) {
3143 default: assert(0 && "getFloatingRank(): illegal value for rank");
3144 case FloatRank: return FloatTy;
3145 case DoubleRank: return DoubleTy;
3146 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003147 }
Steve Naroffe4718892007-04-27 18:30:00 +00003148}
3149
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003150/// getFloatingTypeOrder - Compare the rank of the two specified floating
3151/// point types, ignoring the domain of the type (i.e. 'double' ==
3152/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003153/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003154int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003155 FloatingRank LHSR = getFloatingRank(LHS);
3156 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003157
Chris Lattnerb90739d2008-04-06 23:38:49 +00003158 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003159 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003160 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003161 return 1;
3162 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003163}
3164
Chris Lattner76a00cf2008-04-06 22:59:24 +00003165/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3166/// routine will assert if passed a built-in type that isn't an integer or enum,
3167/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003168unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003169 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003170 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003171 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003172
Chris Lattnerad3467e2010-12-25 23:25:43 +00003173 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3174 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003175 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3176
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003177 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3178 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3179
3180 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3181 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3182
Chris Lattner76a00cf2008-04-06 22:59:24 +00003183 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003184 default: assert(0 && "getIntegerRank(): not a built-in integer");
3185 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003186 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003187 case BuiltinType::Char_S:
3188 case BuiltinType::Char_U:
3189 case BuiltinType::SChar:
3190 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003191 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003192 case BuiltinType::Short:
3193 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003194 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003195 case BuiltinType::Int:
3196 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003197 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003198 case BuiltinType::Long:
3199 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003200 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003201 case BuiltinType::LongLong:
3202 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003203 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003204 case BuiltinType::Int128:
3205 case BuiltinType::UInt128:
3206 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003207 }
3208}
3209
Eli Friedman629ffb92009-08-20 04:21:42 +00003210/// \brief Whether this is a promotable bitfield reference according
3211/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3212///
3213/// \returns the type this bit-field will promote to, or NULL if no
3214/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003215QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003216 if (E->isTypeDependent() || E->isValueDependent())
3217 return QualType();
3218
Eli Friedman629ffb92009-08-20 04:21:42 +00003219 FieldDecl *Field = E->getBitField();
3220 if (!Field)
3221 return QualType();
3222
3223 QualType FT = Field->getType();
3224
3225 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3226 uint64_t BitWidth = BitWidthAP.getZExtValue();
3227 uint64_t IntSize = getTypeSize(IntTy);
3228 // GCC extension compatibility: if the bit-field size is less than or equal
3229 // to the size of int, it gets promoted no matter what its type is.
3230 // For instance, unsigned long bf : 4 gets promoted to signed int.
3231 if (BitWidth < IntSize)
3232 return IntTy;
3233
3234 if (BitWidth == IntSize)
3235 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3236
3237 // Types bigger than int are not subject to promotions, and therefore act
3238 // like the base type.
3239 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3240 // is ridiculous.
3241 return QualType();
3242}
3243
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003244/// getPromotedIntegerType - Returns the type that Promotable will
3245/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3246/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003247QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003248 assert(!Promotable.isNull());
3249 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003250 if (const EnumType *ET = Promotable->getAs<EnumType>())
3251 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003252 if (Promotable->isSignedIntegerType())
3253 return IntTy;
3254 uint64_t PromotableSize = getTypeSize(Promotable);
3255 uint64_t IntSize = getTypeSize(IntTy);
3256 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3257 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3258}
3259
Mike Stump11289f42009-09-09 15:08:12 +00003260/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003261/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003262/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003263int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003264 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3265 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003266 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003267
Chris Lattner76a00cf2008-04-06 22:59:24 +00003268 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3269 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003270
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003271 unsigned LHSRank = getIntegerRank(LHSC);
3272 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003273
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003274 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3275 if (LHSRank == RHSRank) return 0;
3276 return LHSRank > RHSRank ? 1 : -1;
3277 }
Mike Stump11289f42009-09-09 15:08:12 +00003278
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003279 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3280 if (LHSUnsigned) {
3281 // If the unsigned [LHS] type is larger, return it.
3282 if (LHSRank >= RHSRank)
3283 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003284
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003285 // If the signed type can represent all values of the unsigned type, it
3286 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003287 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003288 return -1;
3289 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003290
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003291 // If the unsigned [RHS] type is larger, return it.
3292 if (RHSRank >= LHSRank)
3293 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003294
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003295 // If the signed type can represent all values of the unsigned type, it
3296 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003297 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003298 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003299}
Anders Carlsson98f07902007-08-17 05:31:46 +00003300
Anders Carlsson6d417272009-11-14 21:45:58 +00003301static RecordDecl *
Jay Foad39c79802011-01-12 09:06:06 +00003302CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
Anders Carlsson6d417272009-11-14 21:45:58 +00003303 SourceLocation L, IdentifierInfo *Id) {
3304 if (Ctx.getLangOptions().CPlusPlus)
3305 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3306 else
3307 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3308}
3309
Mike Stump11289f42009-09-09 15:08:12 +00003310// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003311QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003312 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003313 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003314 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003315 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003316 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003317
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003318 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003319
Anders Carlsson98f07902007-08-17 05:31:46 +00003320 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003321 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003322 // int flags;
3323 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003324 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003325 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003326 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003327 FieldTypes[3] = LongTy;
3328
Anders Carlsson98f07902007-08-17 05:31:46 +00003329 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003330 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003331 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003332 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003333 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003334 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003335 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003336 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003337 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003338 }
3339
Douglas Gregord5058122010-02-11 01:19:42 +00003340 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003341 }
Mike Stump11289f42009-09-09 15:08:12 +00003342
Anders Carlsson98f07902007-08-17 05:31:46 +00003343 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003344}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003345
Douglas Gregor512b0772009-04-23 22:29:11 +00003346void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003347 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003348 assert(Rec && "Invalid CFConstantStringType");
3349 CFConstantStringTypeDecl = Rec->getDecl();
3350}
3351
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003352// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003353QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003354 if (!NSConstantStringTypeDecl) {
3355 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003356 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003357 &Idents.get("__builtin_NSString"));
3358 NSConstantStringTypeDecl->startDefinition();
3359
3360 QualType FieldTypes[3];
3361
3362 // const int *isa;
3363 FieldTypes[0] = getPointerType(IntTy.withConst());
3364 // const char *str;
3365 FieldTypes[1] = getPointerType(CharTy.withConst());
3366 // unsigned int length;
3367 FieldTypes[2] = UnsignedIntTy;
3368
3369 // Create fields
3370 for (unsigned i = 0; i < 3; ++i) {
3371 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3372 SourceLocation(), 0,
3373 FieldTypes[i], /*TInfo=*/0,
3374 /*BitWidth=*/0,
3375 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003376 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003377 NSConstantStringTypeDecl->addDecl(Field);
3378 }
3379
3380 NSConstantStringTypeDecl->completeDefinition();
3381 }
3382
3383 return getTagDeclType(NSConstantStringTypeDecl);
3384}
3385
3386void ASTContext::setNSConstantStringType(QualType T) {
3387 const RecordType *Rec = T->getAs<RecordType>();
3388 assert(Rec && "Invalid NSConstantStringType");
3389 NSConstantStringTypeDecl = Rec->getDecl();
3390}
3391
Jay Foad39c79802011-01-12 09:06:06 +00003392QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003393 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003394 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003395 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003396 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003397 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003398
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003399 QualType FieldTypes[] = {
3400 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003401 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003402 getPointerType(UnsignedLongTy),
3403 getConstantArrayType(UnsignedLongTy,
3404 llvm::APInt(32, 5), ArrayType::Normal, 0)
3405 };
Mike Stump11289f42009-09-09 15:08:12 +00003406
Douglas Gregor91f84212008-12-11 16:49:14 +00003407 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003408 FieldDecl *Field = FieldDecl::Create(*this,
3409 ObjCFastEnumerationStateTypeDecl,
3410 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003411 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003412 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003413 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003414 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003415 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003416 }
Mike Stump11289f42009-09-09 15:08:12 +00003417
Douglas Gregord5058122010-02-11 01:19:42 +00003418 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003419 }
Mike Stump11289f42009-09-09 15:08:12 +00003420
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003421 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3422}
3423
Jay Foad39c79802011-01-12 09:06:06 +00003424QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003425 if (BlockDescriptorType)
3426 return getTagDeclType(BlockDescriptorType);
3427
3428 RecordDecl *T;
3429 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003430 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003431 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003432 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003433
3434 QualType FieldTypes[] = {
3435 UnsignedLongTy,
3436 UnsignedLongTy,
3437 };
3438
3439 const char *FieldNames[] = {
3440 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003441 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003442 };
3443
3444 for (size_t i = 0; i < 2; ++i) {
3445 FieldDecl *Field = FieldDecl::Create(*this,
3446 T,
3447 SourceLocation(),
3448 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003449 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003450 /*BitWidth=*/0,
3451 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003452 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003453 T->addDecl(Field);
3454 }
3455
Douglas Gregord5058122010-02-11 01:19:42 +00003456 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003457
3458 BlockDescriptorType = T;
3459
3460 return getTagDeclType(BlockDescriptorType);
3461}
3462
3463void ASTContext::setBlockDescriptorType(QualType T) {
3464 const RecordType *Rec = T->getAs<RecordType>();
3465 assert(Rec && "Invalid BlockDescriptorType");
3466 BlockDescriptorType = Rec->getDecl();
3467}
3468
Jay Foad39c79802011-01-12 09:06:06 +00003469QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003470 if (BlockDescriptorExtendedType)
3471 return getTagDeclType(BlockDescriptorExtendedType);
3472
3473 RecordDecl *T;
3474 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003475 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003476 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003477 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003478
3479 QualType FieldTypes[] = {
3480 UnsignedLongTy,
3481 UnsignedLongTy,
3482 getPointerType(VoidPtrTy),
3483 getPointerType(VoidPtrTy)
3484 };
3485
3486 const char *FieldNames[] = {
3487 "reserved",
3488 "Size",
3489 "CopyFuncPtr",
3490 "DestroyFuncPtr"
3491 };
3492
3493 for (size_t i = 0; i < 4; ++i) {
3494 FieldDecl *Field = FieldDecl::Create(*this,
3495 T,
3496 SourceLocation(),
3497 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003498 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003499 /*BitWidth=*/0,
3500 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003501 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003502 T->addDecl(Field);
3503 }
3504
Douglas Gregord5058122010-02-11 01:19:42 +00003505 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003506
3507 BlockDescriptorExtendedType = T;
3508
3509 return getTagDeclType(BlockDescriptorExtendedType);
3510}
3511
3512void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3513 const RecordType *Rec = T->getAs<RecordType>();
3514 assert(Rec && "Invalid BlockDescriptorType");
3515 BlockDescriptorExtendedType = Rec->getDecl();
3516}
3517
Jay Foad39c79802011-01-12 09:06:06 +00003518bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003519 if (Ty->isBlockPointerType())
3520 return true;
3521 if (isObjCNSObjectType(Ty))
3522 return true;
3523 if (Ty->isObjCObjectPointerType())
3524 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003525 if (getLangOptions().CPlusPlus) {
3526 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3527 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3528 return RD->hasConstCopyConstructor(*this);
3529
3530 }
3531 }
Mike Stump94967902009-10-21 18:16:27 +00003532 return false;
3533}
3534
Jay Foad39c79802011-01-12 09:06:06 +00003535QualType
3536ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003537 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003538 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003539 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003540 // unsigned int __flags;
3541 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003542 // void *__copy_helper; // as needed
3543 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003544 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003545 // } *
3546
Mike Stump94967902009-10-21 18:16:27 +00003547 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3548
3549 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003550 llvm::SmallString<36> Name;
3551 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3552 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003553 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003554 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003555 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003556 T->startDefinition();
3557 QualType Int32Ty = IntTy;
3558 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3559 QualType FieldTypes[] = {
3560 getPointerType(VoidPtrTy),
3561 getPointerType(getTagDeclType(T)),
3562 Int32Ty,
3563 Int32Ty,
3564 getPointerType(VoidPtrTy),
3565 getPointerType(VoidPtrTy),
3566 Ty
3567 };
3568
Daniel Dunbar56df9772010-08-17 22:39:59 +00003569 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003570 "__isa",
3571 "__forwarding",
3572 "__flags",
3573 "__size",
3574 "__copy_helper",
3575 "__destroy_helper",
3576 DeclName,
3577 };
3578
3579 for (size_t i = 0; i < 7; ++i) {
3580 if (!HasCopyAndDispose && i >=4 && i <= 5)
3581 continue;
3582 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3583 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003584 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003585 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003586 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003587 T->addDecl(Field);
3588 }
3589
Douglas Gregord5058122010-02-11 01:19:42 +00003590 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003591
3592 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003593}
3594
3595
3596QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003597 bool BlockHasCopyDispose,
Jay Foad39c79802011-01-12 09:06:06 +00003598 llvm::SmallVectorImpl<const Expr *> &Layout) const {
John McCall87fe5d52010-05-20 01:18:31 +00003599
Mike Stumpd0153282009-10-20 02:12:22 +00003600 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003601 llvm::SmallString<36> Name;
3602 llvm::raw_svector_ostream(Name) << "__block_literal_"
3603 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003604 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003605 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003606 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003607 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003608 QualType FieldTypes[] = {
3609 getPointerType(VoidPtrTy),
3610 IntTy,
3611 IntTy,
3612 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003613 (BlockHasCopyDispose ?
3614 getPointerType(getBlockDescriptorExtendedType()) :
3615 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003616 };
3617
3618 const char *FieldNames[] = {
3619 "__isa",
3620 "__flags",
3621 "__reserved",
3622 "__FuncPtr",
3623 "__descriptor"
3624 };
3625
3626 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003627 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003628 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003629 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003630 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003631 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003632 T->addDecl(Field);
3633 }
3634
John McCall87fe5d52010-05-20 01:18:31 +00003635 for (unsigned i = 0; i < Layout.size(); ++i) {
3636 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003637
John McCall87fe5d52010-05-20 01:18:31 +00003638 QualType FieldType = E->getType();
3639 IdentifierInfo *FieldName = 0;
3640 if (isa<CXXThisExpr>(E)) {
3641 FieldName = &Idents.get("this");
3642 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3643 const ValueDecl *D = BDRE->getDecl();
3644 FieldName = D->getIdentifier();
3645 if (BDRE->isByRef())
Daniel Dunbar56df9772010-08-17 22:39:59 +00003646 FieldType = BuildByRefType(D->getName(), FieldType);
John McCall87fe5d52010-05-20 01:18:31 +00003647 } else {
3648 // Padding.
3649 assert(isa<ConstantArrayType>(FieldType) &&
3650 isa<DeclRefExpr>(E) &&
3651 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3652 "doesn't match characteristics of padding decl");
3653 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003654
3655 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003656 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003657 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003658 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003659 T->addDecl(Field);
3660 }
3661
Douglas Gregord5058122010-02-11 01:19:42 +00003662 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003663
3664 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003665}
3666
Douglas Gregor512b0772009-04-23 22:29:11 +00003667void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003668 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003669 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3670 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3671}
3672
Anders Carlsson18acd442007-10-29 06:33:42 +00003673// This returns true if a type has been typedefed to BOOL:
3674// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003675static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003676 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003677 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3678 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003679
Anders Carlssond8499822007-10-29 05:01:08 +00003680 return false;
3681}
3682
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003683/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003684/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003685CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003686 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003687
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003688 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003689 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003690 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003691 // Treat arrays as pointers, since that's how they're passed in.
3692 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003693 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003694 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003695}
3696
3697static inline
3698std::string charUnitsToString(const CharUnits &CU) {
3699 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003700}
3701
John McCall351762c2011-02-07 10:33:21 +00003702/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003703/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003704std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3705 std::string S;
3706
David Chisnall950a9512009-11-17 19:33:30 +00003707 const BlockDecl *Decl = Expr->getBlockDecl();
3708 QualType BlockTy =
3709 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3710 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003711 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003712 // Compute size of all parameters.
3713 // Start with computing size of a pointer in number of bytes.
3714 // FIXME: There might(should) be a better way of doing this computation!
3715 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003716 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3717 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003718 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003719 E = Decl->param_end(); PI != E; ++PI) {
3720 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003721 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003722 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003723 ParmOffset += sz;
3724 }
3725 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003726 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003727 // Block pointer and offset.
3728 S += "@?0";
3729 ParmOffset = PtrSize;
3730
3731 // Argument types.
3732 ParmOffset = PtrSize;
3733 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3734 Decl->param_end(); PI != E; ++PI) {
3735 ParmVarDecl *PVDecl = *PI;
3736 QualType PType = PVDecl->getOriginalType();
3737 if (const ArrayType *AT =
3738 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3739 // Use array's original type only if it has known number of
3740 // elements.
3741 if (!isa<ConstantArrayType>(AT))
3742 PType = PVDecl->getType();
3743 } else if (PType->isFunctionType())
3744 PType = PVDecl->getType();
3745 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003746 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003747 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003748 }
John McCall351762c2011-02-07 10:33:21 +00003749
3750 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003751}
3752
David Chisnall50e4eba2010-12-30 14:05:53 +00003753void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3754 std::string& S) {
3755 // Encode result type.
3756 getObjCEncodingForType(Decl->getResultType(), S);
3757 CharUnits ParmOffset;
3758 // Compute size of all parameters.
3759 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3760 E = Decl->param_end(); PI != E; ++PI) {
3761 QualType PType = (*PI)->getType();
3762 CharUnits sz = getObjCEncodingTypeSize(PType);
3763 assert (sz.isPositive() &&
3764 "getObjCEncodingForMethodDecl - Incomplete param type");
3765 ParmOffset += sz;
3766 }
3767 S += charUnitsToString(ParmOffset);
3768 ParmOffset = CharUnits::Zero();
3769
3770 // Argument types.
3771 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3772 E = Decl->param_end(); PI != E; ++PI) {
3773 ParmVarDecl *PVDecl = *PI;
3774 QualType PType = PVDecl->getOriginalType();
3775 if (const ArrayType *AT =
3776 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3777 // Use array's original type only if it has known number of
3778 // elements.
3779 if (!isa<ConstantArrayType>(AT))
3780 PType = PVDecl->getType();
3781 } else if (PType->isFunctionType())
3782 PType = PVDecl->getType();
3783 getObjCEncodingForType(PType, S);
3784 S += charUnitsToString(ParmOffset);
3785 ParmOffset += getObjCEncodingTypeSize(PType);
3786 }
3787}
3788
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003789/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003790/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003791void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003792 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003793 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003794 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003795 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003796 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003797 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003798 // Compute size of all parameters.
3799 // Start with computing size of a pointer in number of bytes.
3800 // FIXME: There might(should) be a better way of doing this computation!
3801 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003802 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003803 // The first two arguments (self and _cmd) are pointers; account for
3804 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003805 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003806 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003807 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003808 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003809 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003810 assert (sz.isPositive() &&
3811 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003812 ParmOffset += sz;
3813 }
Ken Dyck40775002010-01-11 17:06:35 +00003814 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003815 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003816 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003817
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003818 // Argument types.
3819 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003820 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003821 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003822 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003823 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003824 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003825 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3826 // Use array's original type only if it has known number of
3827 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003828 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003829 PType = PVDecl->getType();
3830 } else if (PType->isFunctionType())
3831 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003832 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003833 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003834 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003835 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003836 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003837 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003838 }
3839}
3840
Daniel Dunbar4932b362008-08-28 04:38:10 +00003841/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003842/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003843/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3844/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003845/// Property attributes are stored as a comma-delimited C string. The simple
3846/// attributes readonly and bycopy are encoded as single characters. The
3847/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3848/// encoded as single characters, followed by an identifier. Property types
3849/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003850/// these attributes are defined by the following enumeration:
3851/// @code
3852/// enum PropertyAttributes {
3853/// kPropertyReadOnly = 'R', // property is read-only.
3854/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3855/// kPropertyByref = '&', // property is a reference to the value last assigned
3856/// kPropertyDynamic = 'D', // property is dynamic
3857/// kPropertyGetter = 'G', // followed by getter selector name
3858/// kPropertySetter = 'S', // followed by setter selector name
3859/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3860/// kPropertyType = 't' // followed by old-style type encoding.
3861/// kPropertyWeak = 'W' // 'weak' property
3862/// kPropertyStrong = 'P' // property GC'able
3863/// kPropertyNonAtomic = 'N' // property non-atomic
3864/// };
3865/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003866void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003867 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003868 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003869 // Collect information from the property implementation decl(s).
3870 bool Dynamic = false;
3871 ObjCPropertyImplDecl *SynthesizePID = 0;
3872
3873 // FIXME: Duplicated code due to poor abstraction.
3874 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003875 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003876 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3877 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003878 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003879 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003880 ObjCPropertyImplDecl *PID = *i;
3881 if (PID->getPropertyDecl() == PD) {
3882 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3883 Dynamic = true;
3884 } else {
3885 SynthesizePID = PID;
3886 }
3887 }
3888 }
3889 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003890 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003891 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003892 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003893 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003894 ObjCPropertyImplDecl *PID = *i;
3895 if (PID->getPropertyDecl() == PD) {
3896 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3897 Dynamic = true;
3898 } else {
3899 SynthesizePID = PID;
3900 }
3901 }
Mike Stump11289f42009-09-09 15:08:12 +00003902 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003903 }
3904 }
3905
3906 // FIXME: This is not very efficient.
3907 S = "T";
3908
3909 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003910 // GCC has some special rules regarding encoding of properties which
3911 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003912 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003913 true /* outermost type */,
3914 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003915
3916 if (PD->isReadOnly()) {
3917 S += ",R";
3918 } else {
3919 switch (PD->getSetterKind()) {
3920 case ObjCPropertyDecl::Assign: break;
3921 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003922 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003923 }
3924 }
3925
3926 // It really isn't clear at all what this means, since properties
3927 // are "dynamic by default".
3928 if (Dynamic)
3929 S += ",D";
3930
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003931 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3932 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003933
Daniel Dunbar4932b362008-08-28 04:38:10 +00003934 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3935 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003936 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003937 }
3938
3939 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3940 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003941 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003942 }
3943
3944 if (SynthesizePID) {
3945 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3946 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003947 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003948 }
3949
3950 // FIXME: OBJCGC: weak & strong
3951}
3952
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003953/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003954/// Another legacy compatibility encoding: 32-bit longs are encoded as
3955/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003956/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3957///
3958void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003959 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003960 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00003961 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003962 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003963 else
Jay Foad39c79802011-01-12 09:06:06 +00003964 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003965 PointeeTy = IntTy;
3966 }
3967 }
3968}
3969
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003970void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00003971 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003972 // We follow the behavior of gcc, expanding structures which are
3973 // directly pointed to, and expanding embedded structures. Note that
3974 // these rules are sufficient to prevent recursive encoding of the
3975 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003976 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003977 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003978}
3979
David Chisnallb190a2c2010-06-04 01:10:52 +00003980static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3981 switch (T->getAs<BuiltinType>()->getKind()) {
3982 default: assert(0 && "Unhandled builtin type kind");
3983 case BuiltinType::Void: return 'v';
3984 case BuiltinType::Bool: return 'B';
3985 case BuiltinType::Char_U:
3986 case BuiltinType::UChar: return 'C';
3987 case BuiltinType::UShort: return 'S';
3988 case BuiltinType::UInt: return 'I';
3989 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00003990 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003991 case BuiltinType::UInt128: return 'T';
3992 case BuiltinType::ULongLong: return 'Q';
3993 case BuiltinType::Char_S:
3994 case BuiltinType::SChar: return 'c';
3995 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00003996 case BuiltinType::WChar_S:
3997 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00003998 case BuiltinType::Int: return 'i';
3999 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004000 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004001 case BuiltinType::LongLong: return 'q';
4002 case BuiltinType::Int128: return 't';
4003 case BuiltinType::Float: return 'f';
4004 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004005 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004006 }
4007}
4008
Jay Foad39c79802011-01-12 09:06:06 +00004009static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004010 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004011 const Expr *E = FD->getBitWidth();
4012 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004013 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004014 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4015 // The GNU runtime requires more information; bitfields are encoded as b,
4016 // then the offset (in bits) of the first element, then the type of the
4017 // bitfield, then the size in bits. For example, in this structure:
4018 //
4019 // struct
4020 // {
4021 // int integer;
4022 // int flags:2;
4023 // };
4024 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4025 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4026 // information is not especially sensible, but we're stuck with it for
4027 // compatibility with GCC, although providing it breaks anything that
4028 // actually uses runtime introspection and wants to work on both runtimes...
4029 if (!Ctx->getLangOptions().NeXTRuntime) {
4030 const RecordDecl *RD = FD->getParent();
4031 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4032 // FIXME: This same linear search is also used in ExprConstant - it might
4033 // be better if the FieldDecl stored its offset. We'd be increasing the
4034 // size of the object slightly, but saving some time every time it is used.
4035 unsigned i = 0;
4036 for (RecordDecl::field_iterator Field = RD->field_begin(),
4037 FieldEnd = RD->field_end();
4038 Field != FieldEnd; (void)++Field, ++i) {
4039 if (*Field == FD)
4040 break;
4041 }
4042 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004043 if (T->isEnumeralType())
4044 S += 'i';
4045 else
Jay Foad39c79802011-01-12 09:06:06 +00004046 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004047 }
4048 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004049 S += llvm::utostr(N);
4050}
4051
Daniel Dunbar07d07852009-10-18 21:17:35 +00004052// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004053void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4054 bool ExpandPointedToStructures,
4055 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004056 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004057 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00004058 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004059 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004060 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004061 return EncodeBitField(this, S, T, FD);
4062 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004063 return;
4064 }
Mike Stump11289f42009-09-09 15:08:12 +00004065
John McCall9dd450b2009-09-21 23:43:11 +00004066 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004067 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004068 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004069 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004070 return;
4071 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004072
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004073 // encoding for pointer or r3eference types.
4074 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004075 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004076 if (PT->isObjCSelType()) {
4077 S += ':';
4078 return;
4079 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004080 PointeeTy = PT->getPointeeType();
4081 }
4082 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4083 PointeeTy = RT->getPointeeType();
4084 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004085 bool isReadOnly = false;
4086 // For historical/compatibility reasons, the read-only qualifier of the
4087 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4088 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004089 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004090 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004091 if (OutermostType && T.isConstQualified()) {
4092 isReadOnly = true;
4093 S += 'r';
4094 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004095 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004096 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004097 while (P->getAs<PointerType>())
4098 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004099 if (P.isConstQualified()) {
4100 isReadOnly = true;
4101 S += 'r';
4102 }
4103 }
4104 if (isReadOnly) {
4105 // Another legacy compatibility encoding. Some ObjC qualifier and type
4106 // combinations need to be rearranged.
4107 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004108 if (llvm::StringRef(S).endswith("nr"))
4109 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004110 }
Mike Stump11289f42009-09-09 15:08:12 +00004111
Anders Carlssond8499822007-10-29 05:01:08 +00004112 if (PointeeTy->isCharType()) {
4113 // char pointer types should be encoded as '*' unless it is a
4114 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004115 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004116 S += '*';
4117 return;
4118 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004119 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004120 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4121 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4122 S += '#';
4123 return;
4124 }
4125 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4126 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4127 S += '@';
4128 return;
4129 }
4130 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004131 }
Anders Carlssond8499822007-10-29 05:01:08 +00004132 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004133 getLegacyIntegralTypeEncoding(PointeeTy);
4134
Mike Stump11289f42009-09-09 15:08:12 +00004135 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004136 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004137 return;
4138 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004139
Chris Lattnere7cabb92009-07-13 00:10:46 +00004140 if (const ArrayType *AT =
4141 // Ignore type qualifiers etc.
4142 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004143 if (isa<IncompleteArrayType>(AT)) {
4144 // Incomplete arrays are encoded as a pointer to the array element.
4145 S += '^';
4146
Mike Stump11289f42009-09-09 15:08:12 +00004147 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004148 false, ExpandStructures, FD);
4149 } else {
4150 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004151
Anders Carlssond05f44b2009-02-22 01:38:57 +00004152 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4153 S += llvm::utostr(CAT->getSize().getZExtValue());
4154 else {
4155 //Variable length arrays are encoded as a regular array with 0 elements.
4156 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4157 S += '0';
4158 }
Mike Stump11289f42009-09-09 15:08:12 +00004159
4160 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004161 false, ExpandStructures, FD);
4162 S += ']';
4163 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004164 return;
4165 }
Mike Stump11289f42009-09-09 15:08:12 +00004166
John McCall9dd450b2009-09-21 23:43:11 +00004167 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004168 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004169 return;
4170 }
Mike Stump11289f42009-09-09 15:08:12 +00004171
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004172 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004173 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004174 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004175 // Anonymous structures print as '?'
4176 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4177 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004178 if (ClassTemplateSpecializationDecl *Spec
4179 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4180 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4181 std::string TemplateArgsStr
4182 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004183 TemplateArgs.data(),
4184 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004185 (*this).PrintingPolicy);
4186
4187 S += TemplateArgsStr;
4188 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004189 } else {
4190 S += '?';
4191 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004192 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004193 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004194 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4195 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004196 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004197 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004198 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004199 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004200 S += '"';
4201 }
Mike Stump11289f42009-09-09 15:08:12 +00004202
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004203 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004204 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004205 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004206 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004207 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004208 QualType qt = Field->getType();
4209 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004210 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004211 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004212 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004213 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004214 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004215 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004216 return;
4217 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004218
Chris Lattnere7cabb92009-07-13 00:10:46 +00004219 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004220 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004221 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004222 else
4223 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004224 return;
4225 }
Mike Stump11289f42009-09-09 15:08:12 +00004226
Chris Lattnere7cabb92009-07-13 00:10:46 +00004227 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004228 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004229 return;
4230 }
Mike Stump11289f42009-09-09 15:08:12 +00004231
John McCall8b07ec22010-05-15 11:32:37 +00004232 // Ignore protocol qualifiers when mangling at this level.
4233 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4234 T = OT->getBaseType();
4235
John McCall8ccfcb52009-09-24 19:53:00 +00004236 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004237 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004238 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004239 S += '{';
4240 const IdentifierInfo *II = OI->getIdentifier();
4241 S += II->getName();
4242 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004243 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4244 DeepCollectObjCIvars(OI, true, Ivars);
4245 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4246 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4247 if (Field->isBitField())
4248 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004249 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004250 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004251 }
4252 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004253 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004254 }
Mike Stump11289f42009-09-09 15:08:12 +00004255
John McCall9dd450b2009-09-21 23:43:11 +00004256 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004257 if (OPT->isObjCIdType()) {
4258 S += '@';
4259 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004260 }
Mike Stump11289f42009-09-09 15:08:12 +00004261
Steve Narofff0c86112009-10-28 22:03:49 +00004262 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4263 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4264 // Since this is a binary compatibility issue, need to consult with runtime
4265 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004266 S += '#';
4267 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004268 }
Mike Stump11289f42009-09-09 15:08:12 +00004269
Chris Lattnere7cabb92009-07-13 00:10:46 +00004270 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004271 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004272 ExpandPointedToStructures,
4273 ExpandStructures, FD);
4274 if (FD || EncodingProperty) {
4275 // Note that we do extended encoding of protocol qualifer list
4276 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004277 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004278 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4279 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004280 S += '<';
4281 S += (*I)->getNameAsString();
4282 S += '>';
4283 }
4284 S += '"';
4285 }
4286 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004287 }
Mike Stump11289f42009-09-09 15:08:12 +00004288
Chris Lattnere7cabb92009-07-13 00:10:46 +00004289 QualType PointeeTy = OPT->getPointeeType();
4290 if (!EncodingProperty &&
4291 isa<TypedefType>(PointeeTy.getTypePtr())) {
4292 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004293 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004294 // {...};
4295 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004296 getObjCEncodingForTypeImpl(PointeeTy, S,
4297 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004298 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004299 return;
4300 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004301
4302 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004303 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004304 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004305 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004306 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4307 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004308 S += '<';
4309 S += (*I)->getNameAsString();
4310 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004311 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004312 S += '"';
4313 }
4314 return;
4315 }
Mike Stump11289f42009-09-09 15:08:12 +00004316
John McCalla9e6e8d2010-05-17 23:56:34 +00004317 // gcc just blithely ignores member pointers.
4318 // TODO: maybe there should be a mangling for these
4319 if (T->getAs<MemberPointerType>())
4320 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004321
4322 if (T->isVectorType()) {
4323 // This matches gcc's encoding, even though technically it is
4324 // insufficient.
4325 // FIXME. We should do a better job than gcc.
4326 return;
4327 }
4328
Chris Lattnere7cabb92009-07-13 00:10:46 +00004329 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004330}
4331
Mike Stump11289f42009-09-09 15:08:12 +00004332void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004333 std::string& S) const {
4334 if (QT & Decl::OBJC_TQ_In)
4335 S += 'n';
4336 if (QT & Decl::OBJC_TQ_Inout)
4337 S += 'N';
4338 if (QT & Decl::OBJC_TQ_Out)
4339 S += 'o';
4340 if (QT & Decl::OBJC_TQ_Bycopy)
4341 S += 'O';
4342 if (QT & Decl::OBJC_TQ_Byref)
4343 S += 'R';
4344 if (QT & Decl::OBJC_TQ_Oneway)
4345 S += 'V';
4346}
4347
Chris Lattnere7cabb92009-07-13 00:10:46 +00004348void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004349 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004350
Anders Carlsson87c149b2007-10-11 01:00:40 +00004351 BuiltinVaListType = T;
4352}
4353
Chris Lattnere7cabb92009-07-13 00:10:46 +00004354void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004355 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004356}
4357
Chris Lattnere7cabb92009-07-13 00:10:46 +00004358void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004359 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004360}
4361
Chris Lattnere7cabb92009-07-13 00:10:46 +00004362void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004363 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004364}
4365
Chris Lattnere7cabb92009-07-13 00:10:46 +00004366void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004367 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004368}
4369
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004370void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004371 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004372 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004373
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004374 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004375}
4376
John McCalld28ae272009-12-02 08:04:21 +00004377/// \brief Retrieve the template name that corresponds to a non-empty
4378/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004379TemplateName
4380ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4381 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004382 unsigned size = End - Begin;
4383 assert(size > 1 && "set is not overloaded!");
4384
4385 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4386 size * sizeof(FunctionTemplateDecl*));
4387 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4388
4389 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004390 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004391 NamedDecl *D = *I;
4392 assert(isa<FunctionTemplateDecl>(D) ||
4393 (isa<UsingShadowDecl>(D) &&
4394 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4395 *Storage++ = D;
4396 }
4397
4398 return TemplateName(OT);
4399}
4400
Douglas Gregordc572a32009-03-30 22:58:21 +00004401/// \brief Retrieve the template name that represents a qualified
4402/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004403TemplateName
4404ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4405 bool TemplateKeyword,
4406 TemplateDecl *Template) const {
Douglas Gregorc42075a2010-02-04 18:10:26 +00004407 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004408 llvm::FoldingSetNodeID ID;
4409 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4410
4411 void *InsertPos = 0;
4412 QualifiedTemplateName *QTN =
4413 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4414 if (!QTN) {
4415 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4416 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4417 }
4418
4419 return TemplateName(QTN);
4420}
4421
4422/// \brief Retrieve the template name that represents a dependent
4423/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004424TemplateName
4425ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4426 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004427 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004428 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004429
4430 llvm::FoldingSetNodeID ID;
4431 DependentTemplateName::Profile(ID, NNS, Name);
4432
4433 void *InsertPos = 0;
4434 DependentTemplateName *QTN =
4435 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4436
4437 if (QTN)
4438 return TemplateName(QTN);
4439
4440 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4441 if (CanonNNS == NNS) {
4442 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4443 } else {
4444 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4445 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004446 DependentTemplateName *CheckQTN =
4447 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4448 assert(!CheckQTN && "Dependent type name canonicalization broken");
4449 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004450 }
4451
4452 DependentTemplateNames.InsertNode(QTN, InsertPos);
4453 return TemplateName(QTN);
4454}
4455
Douglas Gregor71395fa2009-11-04 00:56:37 +00004456/// \brief Retrieve the template name that represents a dependent
4457/// template name such as \c MetaFun::template operator+.
4458TemplateName
4459ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004460 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004461 assert((!NNS || NNS->isDependent()) &&
4462 "Nested name specifier must be dependent");
4463
4464 llvm::FoldingSetNodeID ID;
4465 DependentTemplateName::Profile(ID, NNS, Operator);
4466
4467 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004468 DependentTemplateName *QTN
4469 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004470
4471 if (QTN)
4472 return TemplateName(QTN);
4473
4474 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4475 if (CanonNNS == NNS) {
4476 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4477 } else {
4478 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4479 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004480
4481 DependentTemplateName *CheckQTN
4482 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4483 assert(!CheckQTN && "Dependent template name canonicalization broken");
4484 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004485 }
4486
4487 DependentTemplateNames.InsertNode(QTN, InsertPos);
4488 return TemplateName(QTN);
4489}
4490
Douglas Gregor5590be02011-01-15 06:45:20 +00004491TemplateName
4492ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4493 const TemplateArgument &ArgPack) const {
4494 ASTContext &Self = const_cast<ASTContext &>(*this);
4495 llvm::FoldingSetNodeID ID;
4496 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4497
4498 void *InsertPos = 0;
4499 SubstTemplateTemplateParmPackStorage *Subst
4500 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4501
4502 if (!Subst) {
4503 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4504 ArgPack.pack_size(),
4505 ArgPack.pack_begin());
4506 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4507 }
4508
4509 return TemplateName(Subst);
4510}
4511
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004512/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004513/// TargetInfo, produce the corresponding type. The unsigned @p Type
4514/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004515CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004516 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004517 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004518 case TargetInfo::SignedShort: return ShortTy;
4519 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4520 case TargetInfo::SignedInt: return IntTy;
4521 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4522 case TargetInfo::SignedLong: return LongTy;
4523 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4524 case TargetInfo::SignedLongLong: return LongLongTy;
4525 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4526 }
4527
4528 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004529 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004530}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004531
4532//===----------------------------------------------------------------------===//
4533// Type Predicates.
4534//===----------------------------------------------------------------------===//
4535
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004536/// isObjCNSObjectType - Return true if this is an NSObject object using
4537/// NSObject attribute on a c-style pointer type.
4538/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004539/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004540///
4541bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCall424cec92011-01-19 06:33:43 +00004542 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004543 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004544 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004545 return true;
4546 }
Mike Stump11289f42009-09-09 15:08:12 +00004547 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004548}
4549
Fariborz Jahanian96207692009-02-18 21:49:28 +00004550/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4551/// garbage collection attribute.
4552///
John McCall553d45a2011-01-12 00:34:59 +00004553Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4554 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4555 return Qualifiers::GCNone;
4556
4557 assert(getLangOptions().ObjC1);
4558 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4559
4560 // Default behaviour under objective-C's gc is for ObjC pointers
4561 // (or pointers to them) be treated as though they were declared
4562 // as __strong.
4563 if (GCAttrs == Qualifiers::GCNone) {
4564 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4565 return Qualifiers::Strong;
4566 else if (Ty->isPointerType())
4567 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4568 } else {
4569 // It's not valid to set GC attributes on anything that isn't a
4570 // pointer.
4571#ifndef NDEBUG
4572 QualType CT = Ty->getCanonicalTypeInternal();
4573 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4574 CT = AT->getElementType();
4575 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4576#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004577 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004578 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004579}
4580
Chris Lattner49af6a42008-04-07 06:51:04 +00004581//===----------------------------------------------------------------------===//
4582// Type Compatibility Testing
4583//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004584
Mike Stump11289f42009-09-09 15:08:12 +00004585/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004586/// compatible.
4587static bool areCompatVectorTypes(const VectorType *LHS,
4588 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004589 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004590 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004591 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004592}
4593
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004594bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4595 QualType SecondVec) {
4596 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4597 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4598
4599 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4600 return true;
4601
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004602 // Treat Neon vector types and most AltiVec vector types as if they are the
4603 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004604 const VectorType *First = FirstVec->getAs<VectorType>();
4605 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004606 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004607 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004608 First->getVectorKind() != VectorType::AltiVecPixel &&
4609 First->getVectorKind() != VectorType::AltiVecBool &&
4610 Second->getVectorKind() != VectorType::AltiVecPixel &&
4611 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004612 return true;
4613
4614 return false;
4615}
4616
Steve Naroff8e6aee52009-07-23 01:01:38 +00004617//===----------------------------------------------------------------------===//
4618// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4619//===----------------------------------------------------------------------===//
4620
4621/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4622/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004623bool
4624ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4625 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004626 if (lProto == rProto)
4627 return true;
4628 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4629 E = rProto->protocol_end(); PI != E; ++PI)
4630 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4631 return true;
4632 return false;
4633}
4634
Steve Naroff8e6aee52009-07-23 01:01:38 +00004635/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4636/// return true if lhs's protocols conform to rhs's protocol; false
4637/// otherwise.
4638bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4639 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4640 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4641 return false;
4642}
4643
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004644/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4645/// Class<p1, ...>.
4646bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4647 QualType rhs) {
4648 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4649 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4650 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4651
4652 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4653 E = lhsQID->qual_end(); I != E; ++I) {
4654 bool match = false;
4655 ObjCProtocolDecl *lhsProto = *I;
4656 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4657 E = rhsOPT->qual_end(); J != E; ++J) {
4658 ObjCProtocolDecl *rhsProto = *J;
4659 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4660 match = true;
4661 break;
4662 }
4663 }
4664 if (!match)
4665 return false;
4666 }
4667 return true;
4668}
4669
Steve Naroff8e6aee52009-07-23 01:01:38 +00004670/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4671/// ObjCQualifiedIDType.
4672bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4673 bool compare) {
4674 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004675 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004676 lhs->isObjCIdType() || lhs->isObjCClassType())
4677 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004678 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004679 rhs->isObjCIdType() || rhs->isObjCClassType())
4680 return true;
4681
4682 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004683 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004684
Steve Naroff8e6aee52009-07-23 01:01:38 +00004685 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004686
Steve Naroff8e6aee52009-07-23 01:01:38 +00004687 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004688 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004689 // make sure we check the class hierarchy.
4690 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4691 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4692 E = lhsQID->qual_end(); I != E; ++I) {
4693 // when comparing an id<P> on lhs with a static type on rhs,
4694 // see if static class implements all of id's protocols, directly or
4695 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004696 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004697 return false;
4698 }
4699 }
4700 // If there are no qualifiers and no interface, we have an 'id'.
4701 return true;
4702 }
Mike Stump11289f42009-09-09 15:08:12 +00004703 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004704 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4705 E = lhsQID->qual_end(); I != E; ++I) {
4706 ObjCProtocolDecl *lhsProto = *I;
4707 bool match = false;
4708
4709 // when comparing an id<P> on lhs with a static type on rhs,
4710 // see if static class implements all of id's protocols, directly or
4711 // through its super class and categories.
4712 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4713 E = rhsOPT->qual_end(); J != E; ++J) {
4714 ObjCProtocolDecl *rhsProto = *J;
4715 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4716 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4717 match = true;
4718 break;
4719 }
4720 }
Mike Stump11289f42009-09-09 15:08:12 +00004721 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004722 // make sure we check the class hierarchy.
4723 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4724 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4725 E = lhsQID->qual_end(); I != E; ++I) {
4726 // when comparing an id<P> on lhs with a static type on rhs,
4727 // see if static class implements all of id's protocols, directly or
4728 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004729 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004730 match = true;
4731 break;
4732 }
4733 }
4734 }
4735 if (!match)
4736 return false;
4737 }
Mike Stump11289f42009-09-09 15:08:12 +00004738
Steve Naroff8e6aee52009-07-23 01:01:38 +00004739 return true;
4740 }
Mike Stump11289f42009-09-09 15:08:12 +00004741
Steve Naroff8e6aee52009-07-23 01:01:38 +00004742 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4743 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4744
Mike Stump11289f42009-09-09 15:08:12 +00004745 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004746 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004747 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004748 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4749 E = lhsOPT->qual_end(); I != E; ++I) {
4750 ObjCProtocolDecl *lhsProto = *I;
4751 bool match = false;
4752
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004753 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004754 // see if static class implements all of id's protocols, directly or
4755 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004756 // First, lhs protocols in the qualifier list must be found, direct
4757 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004758 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4759 E = rhsQID->qual_end(); J != E; ++J) {
4760 ObjCProtocolDecl *rhsProto = *J;
4761 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4762 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4763 match = true;
4764 break;
4765 }
4766 }
4767 if (!match)
4768 return false;
4769 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004770
4771 // Static class's protocols, or its super class or category protocols
4772 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4773 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4774 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4775 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4776 // This is rather dubious but matches gcc's behavior. If lhs has
4777 // no type qualifier and its class has no static protocol(s)
4778 // assume that it is mismatch.
4779 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4780 return false;
4781 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4782 LHSInheritedProtocols.begin(),
4783 E = LHSInheritedProtocols.end(); I != E; ++I) {
4784 bool match = false;
4785 ObjCProtocolDecl *lhsProto = (*I);
4786 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4787 E = rhsQID->qual_end(); J != E; ++J) {
4788 ObjCProtocolDecl *rhsProto = *J;
4789 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4790 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4791 match = true;
4792 break;
4793 }
4794 }
4795 if (!match)
4796 return false;
4797 }
4798 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004799 return true;
4800 }
4801 return false;
4802}
4803
Eli Friedman47f77112008-08-22 00:56:42 +00004804/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004805/// compatible for assignment from RHS to LHS. This handles validation of any
4806/// protocol qualifiers on the LHS or RHS.
4807///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004808bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4809 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004810 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4811 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4812
Steve Naroff1329fa02009-07-15 18:40:39 +00004813 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004814 if (LHS->isObjCUnqualifiedIdOrClass() ||
4815 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004816 return true;
4817
John McCall8b07ec22010-05-15 11:32:37 +00004818 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004819 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4820 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004821 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004822
4823 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4824 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4825 QualType(RHSOPT,0));
4826
John McCall8b07ec22010-05-15 11:32:37 +00004827 // If we have 2 user-defined types, fall into that path.
4828 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004829 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004830
Steve Naroff8e6aee52009-07-23 01:01:38 +00004831 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004832}
4833
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004834/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4835/// for providing type-safty for objective-c pointers used to pass/return
4836/// arguments in block literals. When passed as arguments, passing 'A*' where
4837/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4838/// not OK. For the return type, the opposite is not OK.
4839bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4840 const ObjCObjectPointerType *LHSOPT,
4841 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004842 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004843 return true;
4844
4845 if (LHSOPT->isObjCBuiltinType()) {
4846 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4847 }
4848
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004849 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004850 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4851 QualType(RHSOPT,0),
4852 false);
4853
4854 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4855 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4856 if (LHS && RHS) { // We have 2 user-defined types.
4857 if (LHS != RHS) {
4858 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4859 return false;
4860 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4861 return true;
4862 }
4863 else
4864 return true;
4865 }
4866 return false;
4867}
4868
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004869/// getIntersectionOfProtocols - This routine finds the intersection of set
4870/// of protocols inherited from two distinct objective-c pointer objects.
4871/// It is used to build composite qualifier list of the composite type of
4872/// the conditional expression involving two objective-c pointer objects.
4873static
4874void getIntersectionOfProtocols(ASTContext &Context,
4875 const ObjCObjectPointerType *LHSOPT,
4876 const ObjCObjectPointerType *RHSOPT,
4877 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4878
John McCall8b07ec22010-05-15 11:32:37 +00004879 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4880 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4881 assert(LHS->getInterface() && "LHS must have an interface base");
4882 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004883
4884 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4885 unsigned LHSNumProtocols = LHS->getNumProtocols();
4886 if (LHSNumProtocols > 0)
4887 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4888 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004889 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004890 Context.CollectInheritedProtocols(LHS->getInterface(),
4891 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004892 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4893 LHSInheritedProtocols.end());
4894 }
4895
4896 unsigned RHSNumProtocols = RHS->getNumProtocols();
4897 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004898 ObjCProtocolDecl **RHSProtocols =
4899 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004900 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4901 if (InheritedProtocolSet.count(RHSProtocols[i]))
4902 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4903 }
4904 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004905 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004906 Context.CollectInheritedProtocols(RHS->getInterface(),
4907 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004908 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4909 RHSInheritedProtocols.begin(),
4910 E = RHSInheritedProtocols.end(); I != E; ++I)
4911 if (InheritedProtocolSet.count((*I)))
4912 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004913 }
4914}
4915
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004916/// areCommonBaseCompatible - Returns common base class of the two classes if
4917/// one found. Note that this is O'2 algorithm. But it will be called as the
4918/// last type comparison in a ?-exp of ObjC pointer types before a
4919/// warning is issued. So, its invokation is extremely rare.
4920QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004921 const ObjCObjectPointerType *Lptr,
4922 const ObjCObjectPointerType *Rptr) {
4923 const ObjCObjectType *LHS = Lptr->getObjectType();
4924 const ObjCObjectType *RHS = Rptr->getObjectType();
4925 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4926 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4927 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004928 return QualType();
4929
John McCall8b07ec22010-05-15 11:32:37 +00004930 while ((LDecl = LDecl->getSuperClass())) {
4931 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004932 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004933 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4934 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4935
4936 QualType Result = QualType(LHS, 0);
4937 if (!Protocols.empty())
4938 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4939 Result = getObjCObjectPointerType(Result);
4940 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004941 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004942 }
4943
4944 return QualType();
4945}
4946
John McCall8b07ec22010-05-15 11:32:37 +00004947bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4948 const ObjCObjectType *RHS) {
4949 assert(LHS->getInterface() && "LHS is not an interface type");
4950 assert(RHS->getInterface() && "RHS is not an interface type");
4951
Chris Lattner49af6a42008-04-07 06:51:04 +00004952 // Verify that the base decls are compatible: the RHS must be a subclass of
4953 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004954 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004955 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004956
Chris Lattner49af6a42008-04-07 06:51:04 +00004957 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4958 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004959 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004960 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004961
Chris Lattner49af6a42008-04-07 06:51:04 +00004962 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4963 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004964 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004965 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004966
John McCall8b07ec22010-05-15 11:32:37 +00004967 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4968 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004969 LHSPI != LHSPE; LHSPI++) {
4970 bool RHSImplementsProtocol = false;
4971
4972 // If the RHS doesn't implement the protocol on the left, the types
4973 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004974 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4975 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004976 RHSPI != RHSPE; RHSPI++) {
4977 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004978 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004979 break;
4980 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004981 }
4982 // FIXME: For better diagnostics, consider passing back the protocol name.
4983 if (!RHSImplementsProtocol)
4984 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004985 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004986 // The RHS implements all protocols listed on the LHS.
4987 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004988}
4989
Steve Naroffb7605152009-02-12 17:52:19 +00004990bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4991 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004992 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4993 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004994
Steve Naroff7cae42b2009-07-10 23:34:53 +00004995 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004996 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004997
4998 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4999 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005000}
5001
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005002bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5003 return canAssignObjCInterfaces(
5004 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5005 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5006}
5007
Mike Stump11289f42009-09-09 15:08:12 +00005008/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005009/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005010/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005011/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005012bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5013 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005014 if (getLangOptions().CPlusPlus)
5015 return hasSameType(LHS, RHS);
5016
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005017 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005018}
5019
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005020bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5021 return !mergeTypes(LHS, RHS, true).isNull();
5022}
5023
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005024/// mergeTransparentUnionType - if T is a transparent union type and a member
5025/// of T is compatible with SubType, return the merged type, else return
5026/// QualType()
5027QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5028 bool OfBlockPointer,
5029 bool Unqualified) {
5030 if (const RecordType *UT = T->getAsUnionType()) {
5031 RecordDecl *UD = UT->getDecl();
5032 if (UD->hasAttr<TransparentUnionAttr>()) {
5033 for (RecordDecl::field_iterator it = UD->field_begin(),
5034 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005035 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005036 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5037 if (!MT.isNull())
5038 return MT;
5039 }
5040 }
5041 }
5042
5043 return QualType();
5044}
5045
5046/// mergeFunctionArgumentTypes - merge two types which appear as function
5047/// argument types
5048QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5049 bool OfBlockPointer,
5050 bool Unqualified) {
5051 // GNU extension: two types are compatible if they appear as a function
5052 // argument, one of the types is a transparent union type and the other
5053 // type is compatible with a union member
5054 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5055 Unqualified);
5056 if (!lmerge.isNull())
5057 return lmerge;
5058
5059 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5060 Unqualified);
5061 if (!rmerge.isNull())
5062 return rmerge;
5063
5064 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5065}
5066
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005067QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005068 bool OfBlockPointer,
5069 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005070 const FunctionType *lbase = lhs->getAs<FunctionType>();
5071 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005072 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5073 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005074 bool allLTypes = true;
5075 bool allRTypes = true;
5076
5077 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005078 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005079 if (OfBlockPointer) {
5080 QualType RHS = rbase->getResultType();
5081 QualType LHS = lbase->getResultType();
5082 bool UnqualifiedResult = Unqualified;
5083 if (!UnqualifiedResult)
5084 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
5085 retType = mergeTypes(RHS, LHS, true, UnqualifiedResult);
5086 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005087 else
John McCall8c6b56f2010-12-15 01:06:38 +00005088 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5089 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005090 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005091
5092 if (Unqualified)
5093 retType = retType.getUnqualifiedType();
5094
5095 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5096 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5097 if (Unqualified) {
5098 LRetType = LRetType.getUnqualifiedType();
5099 RRetType = RRetType.getUnqualifiedType();
5100 }
5101
5102 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005103 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005104 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005105 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005106
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005107 // FIXME: double check this
5108 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5109 // rbase->getRegParmAttr() != 0 &&
5110 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005111 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5112 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005113
Douglas Gregor8c940862010-01-18 17:14:39 +00005114 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005115 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005116 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005117
John McCall8c6b56f2010-12-15 01:06:38 +00005118 // Regparm is part of the calling convention.
5119 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5120 return QualType();
5121
5122 // It's noreturn if either type is.
5123 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5124 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5125 if (NoReturn != lbaseInfo.getNoReturn())
5126 allLTypes = false;
5127 if (NoReturn != rbaseInfo.getNoReturn())
5128 allRTypes = false;
5129
5130 FunctionType::ExtInfo einfo(NoReturn,
5131 lbaseInfo.getRegParm(),
5132 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00005133
Eli Friedman47f77112008-08-22 00:56:42 +00005134 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005135 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5136 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005137 unsigned lproto_nargs = lproto->getNumArgs();
5138 unsigned rproto_nargs = rproto->getNumArgs();
5139
5140 // Compatible functions must have the same number of arguments
5141 if (lproto_nargs != rproto_nargs)
5142 return QualType();
5143
5144 // Variadic and non-variadic functions aren't compatible
5145 if (lproto->isVariadic() != rproto->isVariadic())
5146 return QualType();
5147
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005148 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5149 return QualType();
5150
Eli Friedman47f77112008-08-22 00:56:42 +00005151 // Check argument compatibility
5152 llvm::SmallVector<QualType, 10> types;
5153 for (unsigned i = 0; i < lproto_nargs; i++) {
5154 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5155 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005156 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5157 OfBlockPointer,
5158 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005159 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005160
5161 if (Unqualified)
5162 argtype = argtype.getUnqualifiedType();
5163
Eli Friedman47f77112008-08-22 00:56:42 +00005164 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005165 if (Unqualified) {
5166 largtype = largtype.getUnqualifiedType();
5167 rargtype = rargtype.getUnqualifiedType();
5168 }
5169
Chris Lattner465fa322008-10-05 17:34:18 +00005170 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5171 allLTypes = false;
5172 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5173 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005174 }
5175 if (allLTypes) return lhs;
5176 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005177
5178 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5179 EPI.ExtInfo = einfo;
5180 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005181 }
5182
5183 if (lproto) allRTypes = false;
5184 if (rproto) allLTypes = false;
5185
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005186 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005187 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005188 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005189 if (proto->isVariadic()) return QualType();
5190 // Check that the types are compatible with the types that
5191 // would result from default argument promotions (C99 6.7.5.3p15).
5192 // The only types actually affected are promotable integer
5193 // types and floats, which would be passed as a different
5194 // type depending on whether the prototype is visible.
5195 unsigned proto_nargs = proto->getNumArgs();
5196 for (unsigned i = 0; i < proto_nargs; ++i) {
5197 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005198
5199 // Look at the promotion type of enum types, since that is the type used
5200 // to pass enum values.
5201 if (const EnumType *Enum = argTy->getAs<EnumType>())
5202 argTy = Enum->getDecl()->getPromotionType();
5203
Eli Friedman47f77112008-08-22 00:56:42 +00005204 if (argTy->isPromotableIntegerType() ||
5205 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5206 return QualType();
5207 }
5208
5209 if (allLTypes) return lhs;
5210 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005211
5212 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5213 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005214 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005215 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005216 }
5217
5218 if (allLTypes) return lhs;
5219 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005220 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005221}
5222
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005223QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005224 bool OfBlockPointer,
5225 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005226 // C++ [expr]: If an expression initially has the type "reference to T", the
5227 // type is adjusted to "T" prior to any further analysis, the expression
5228 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005229 // expression is an lvalue unless the reference is an rvalue reference and
5230 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005231 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5232 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005233
5234 if (Unqualified) {
5235 LHS = LHS.getUnqualifiedType();
5236 RHS = RHS.getUnqualifiedType();
5237 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005238
Eli Friedman47f77112008-08-22 00:56:42 +00005239 QualType LHSCan = getCanonicalType(LHS),
5240 RHSCan = getCanonicalType(RHS);
5241
5242 // If two types are identical, they are compatible.
5243 if (LHSCan == RHSCan)
5244 return LHS;
5245
John McCall8ccfcb52009-09-24 19:53:00 +00005246 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005247 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5248 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005249 if (LQuals != RQuals) {
5250 // If any of these qualifiers are different, we have a type
5251 // mismatch.
5252 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5253 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5254 return QualType();
5255
5256 // Exactly one GC qualifier difference is allowed: __strong is
5257 // okay if the other type has no GC qualifier but is an Objective
5258 // C object pointer (i.e. implicitly strong by default). We fix
5259 // this by pretending that the unqualified type was actually
5260 // qualified __strong.
5261 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5262 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5263 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5264
5265 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5266 return QualType();
5267
5268 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5269 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5270 }
5271 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5272 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5273 }
Eli Friedman47f77112008-08-22 00:56:42 +00005274 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005275 }
5276
5277 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005278
Eli Friedmandcca6332009-06-01 01:22:52 +00005279 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5280 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005281
Chris Lattnerfd652912008-01-14 05:45:46 +00005282 // We want to consider the two function types to be the same for these
5283 // comparisons, just force one to the other.
5284 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5285 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005286
5287 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005288 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5289 LHSClass = Type::ConstantArray;
5290 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5291 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005292
John McCall8b07ec22010-05-15 11:32:37 +00005293 // ObjCInterfaces are just specialized ObjCObjects.
5294 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5295 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5296
Nate Begemance4d7fc2008-04-18 23:10:10 +00005297 // Canonicalize ExtVector -> Vector.
5298 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5299 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005300
Chris Lattner95554662008-04-07 05:43:21 +00005301 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005302 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005303 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005304 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005305 // Compatibility is based on the underlying type, not the promotion
5306 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005307 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005308 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5309 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005310 }
John McCall9dd450b2009-09-21 23:43:11 +00005311 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005312 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5313 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005314 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005315
Eli Friedman47f77112008-08-22 00:56:42 +00005316 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005317 }
Eli Friedman47f77112008-08-22 00:56:42 +00005318
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005319 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005320 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005321#define TYPE(Class, Base)
5322#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005323#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005324#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5325#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5326#include "clang/AST/TypeNodes.def"
5327 assert(false && "Non-canonical and dependent types shouldn't get here");
5328 return QualType();
5329
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005330 case Type::LValueReference:
5331 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005332 case Type::MemberPointer:
5333 assert(false && "C++ should never be in mergeTypes");
5334 return QualType();
5335
John McCall8b07ec22010-05-15 11:32:37 +00005336 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005337 case Type::IncompleteArray:
5338 case Type::VariableArray:
5339 case Type::FunctionProto:
5340 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005341 assert(false && "Types are eliminated above");
5342 return QualType();
5343
Chris Lattnerfd652912008-01-14 05:45:46 +00005344 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005345 {
5346 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005347 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5348 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005349 if (Unqualified) {
5350 LHSPointee = LHSPointee.getUnqualifiedType();
5351 RHSPointee = RHSPointee.getUnqualifiedType();
5352 }
5353 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5354 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005355 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005356 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005357 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005358 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005359 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005360 return getPointerType(ResultType);
5361 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005362 case Type::BlockPointer:
5363 {
5364 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005365 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5366 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005367 if (Unqualified) {
5368 LHSPointee = LHSPointee.getUnqualifiedType();
5369 RHSPointee = RHSPointee.getUnqualifiedType();
5370 }
5371 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5372 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005373 if (ResultType.isNull()) return QualType();
5374 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5375 return LHS;
5376 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5377 return RHS;
5378 return getBlockPointerType(ResultType);
5379 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005380 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005381 {
5382 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5383 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5384 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5385 return QualType();
5386
5387 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5388 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005389 if (Unqualified) {
5390 LHSElem = LHSElem.getUnqualifiedType();
5391 RHSElem = RHSElem.getUnqualifiedType();
5392 }
5393
5394 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005395 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005396 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5397 return LHS;
5398 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5399 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005400 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5401 ArrayType::ArraySizeModifier(), 0);
5402 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5403 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005404 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5405 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005406 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5407 return LHS;
5408 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5409 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005410 if (LVAT) {
5411 // FIXME: This isn't correct! But tricky to implement because
5412 // the array's size has to be the size of LHS, but the type
5413 // has to be different.
5414 return LHS;
5415 }
5416 if (RVAT) {
5417 // FIXME: This isn't correct! But tricky to implement because
5418 // the array's size has to be the size of RHS, but the type
5419 // has to be different.
5420 return RHS;
5421 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005422 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5423 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005424 return getIncompleteArrayType(ResultType,
5425 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005426 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005427 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005428 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005429 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005430 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005431 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005432 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005433 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005434 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005435 case Type::Complex:
5436 // Distinct complex types are incompatible.
5437 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005438 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005439 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005440 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5441 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005442 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005443 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005444 case Type::ObjCObject: {
5445 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005446 // FIXME: This should be type compatibility, e.g. whether
5447 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005448 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5449 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5450 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005451 return LHS;
5452
Eli Friedman47f77112008-08-22 00:56:42 +00005453 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005454 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005455 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005456 if (OfBlockPointer) {
5457 if (canAssignObjCInterfacesInBlockPointer(
5458 LHS->getAs<ObjCObjectPointerType>(),
5459 RHS->getAs<ObjCObjectPointerType>()))
5460 return LHS;
5461 return QualType();
5462 }
John McCall9dd450b2009-09-21 23:43:11 +00005463 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5464 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005465 return LHS;
5466
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005467 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005468 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005469 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005470
5471 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005472}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005473
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005474/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5475/// 'RHS' attributes and returns the merged version; including for function
5476/// return types.
5477QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5478 QualType LHSCan = getCanonicalType(LHS),
5479 RHSCan = getCanonicalType(RHS);
5480 // If two types are identical, they are compatible.
5481 if (LHSCan == RHSCan)
5482 return LHS;
5483 if (RHSCan->isFunctionType()) {
5484 if (!LHSCan->isFunctionType())
5485 return QualType();
5486 QualType OldReturnType =
5487 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5488 QualType NewReturnType =
5489 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5490 QualType ResReturnType =
5491 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5492 if (ResReturnType.isNull())
5493 return QualType();
5494 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5495 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5496 // In either case, use OldReturnType to build the new function type.
5497 const FunctionType *F = LHS->getAs<FunctionType>();
5498 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005499 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5500 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005501 QualType ResultType
5502 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005503 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005504 return ResultType;
5505 }
5506 }
5507 return QualType();
5508 }
5509
5510 // If the qualifiers are different, the types can still be merged.
5511 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5512 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5513 if (LQuals != RQuals) {
5514 // If any of these qualifiers are different, we have a type mismatch.
5515 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5516 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5517 return QualType();
5518
5519 // Exactly one GC qualifier difference is allowed: __strong is
5520 // okay if the other type has no GC qualifier but is an Objective
5521 // C object pointer (i.e. implicitly strong by default). We fix
5522 // this by pretending that the unqualified type was actually
5523 // qualified __strong.
5524 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5525 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5526 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5527
5528 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5529 return QualType();
5530
5531 if (GC_L == Qualifiers::Strong)
5532 return LHS;
5533 if (GC_R == Qualifiers::Strong)
5534 return RHS;
5535 return QualType();
5536 }
5537
5538 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5539 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5540 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5541 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5542 if (ResQT == LHSBaseQT)
5543 return LHS;
5544 if (ResQT == RHSBaseQT)
5545 return RHS;
5546 }
5547 return QualType();
5548}
5549
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005550//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005551// Integer Predicates
5552//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005553
Jay Foad39c79802011-01-12 09:06:06 +00005554unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005555 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005556 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005557 if (T->isBooleanType())
5558 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005559 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005560 return (unsigned)getTypeSize(T);
5561}
5562
5563QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005564 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005565
5566 // Turn <4 x signed int> -> <4 x unsigned int>
5567 if (const VectorType *VTy = T->getAs<VectorType>())
5568 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005569 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005570
5571 // For enums, we return the unsigned version of the base type.
5572 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005573 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005574
5575 const BuiltinType *BTy = T->getAs<BuiltinType>();
5576 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005577 switch (BTy->getKind()) {
5578 case BuiltinType::Char_S:
5579 case BuiltinType::SChar:
5580 return UnsignedCharTy;
5581 case BuiltinType::Short:
5582 return UnsignedShortTy;
5583 case BuiltinType::Int:
5584 return UnsignedIntTy;
5585 case BuiltinType::Long:
5586 return UnsignedLongTy;
5587 case BuiltinType::LongLong:
5588 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005589 case BuiltinType::Int128:
5590 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005591 default:
5592 assert(0 && "Unexpected signed integer type");
5593 return QualType();
5594 }
5595}
5596
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005597ExternalASTSource::~ExternalASTSource() { }
5598
5599void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00005600
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005601ASTMutationListener::~ASTMutationListener() { }
5602
Chris Lattnerecd79c62009-06-14 00:45:47 +00005603
5604//===----------------------------------------------------------------------===//
5605// Builtin Type Computation
5606//===----------------------------------------------------------------------===//
5607
5608/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005609/// pointer over the consumed characters. This returns the resultant type. If
5610/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5611/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5612/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005613///
5614/// RequiresICE is filled in on return to indicate whether the value is required
5615/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005616static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005617 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005618 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005619 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005620 // Modifiers.
5621 int HowLong = 0;
5622 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005623 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005624
Chris Lattnerdc226c22010-10-01 22:42:38 +00005625 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005626 bool Done = false;
5627 while (!Done) {
5628 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005629 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005630 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005631 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005632 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005633 case 'S':
5634 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5635 assert(!Signed && "Can't use 'S' modifier multiple times!");
5636 Signed = true;
5637 break;
5638 case 'U':
5639 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5640 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5641 Unsigned = true;
5642 break;
5643 case 'L':
5644 assert(HowLong <= 2 && "Can't have LLLL modifier");
5645 ++HowLong;
5646 break;
5647 }
5648 }
5649
5650 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005651
Chris Lattnerecd79c62009-06-14 00:45:47 +00005652 // Read the base type.
5653 switch (*Str++) {
5654 default: assert(0 && "Unknown builtin type letter!");
5655 case 'v':
5656 assert(HowLong == 0 && !Signed && !Unsigned &&
5657 "Bad modifiers used with 'v'!");
5658 Type = Context.VoidTy;
5659 break;
5660 case 'f':
5661 assert(HowLong == 0 && !Signed && !Unsigned &&
5662 "Bad modifiers used with 'f'!");
5663 Type = Context.FloatTy;
5664 break;
5665 case 'd':
5666 assert(HowLong < 2 && !Signed && !Unsigned &&
5667 "Bad modifiers used with 'd'!");
5668 if (HowLong)
5669 Type = Context.LongDoubleTy;
5670 else
5671 Type = Context.DoubleTy;
5672 break;
5673 case 's':
5674 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5675 if (Unsigned)
5676 Type = Context.UnsignedShortTy;
5677 else
5678 Type = Context.ShortTy;
5679 break;
5680 case 'i':
5681 if (HowLong == 3)
5682 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5683 else if (HowLong == 2)
5684 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5685 else if (HowLong == 1)
5686 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5687 else
5688 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5689 break;
5690 case 'c':
5691 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5692 if (Signed)
5693 Type = Context.SignedCharTy;
5694 else if (Unsigned)
5695 Type = Context.UnsignedCharTy;
5696 else
5697 Type = Context.CharTy;
5698 break;
5699 case 'b': // boolean
5700 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5701 Type = Context.BoolTy;
5702 break;
5703 case 'z': // size_t.
5704 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5705 Type = Context.getSizeType();
5706 break;
5707 case 'F':
5708 Type = Context.getCFConstantStringType();
5709 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005710 case 'G':
5711 Type = Context.getObjCIdType();
5712 break;
5713 case 'H':
5714 Type = Context.getObjCSelType();
5715 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005716 case 'a':
5717 Type = Context.getBuiltinVaListType();
5718 assert(!Type.isNull() && "builtin va list type not initialized!");
5719 break;
5720 case 'A':
5721 // This is a "reference" to a va_list; however, what exactly
5722 // this means depends on how va_list is defined. There are two
5723 // different kinds of va_list: ones passed by value, and ones
5724 // passed by reference. An example of a by-value va_list is
5725 // x86, where va_list is a char*. An example of by-ref va_list
5726 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5727 // we want this argument to be a char*&; for x86-64, we want
5728 // it to be a __va_list_tag*.
5729 Type = Context.getBuiltinVaListType();
5730 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005731 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005732 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005733 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005734 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005735 break;
5736 case 'V': {
5737 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005738 unsigned NumElements = strtoul(Str, &End, 10);
5739 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005740 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005741
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005742 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5743 RequiresICE, false);
5744 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005745
5746 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005747 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005748 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005749 break;
5750 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005751 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005752 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5753 false);
5754 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005755 Type = Context.getComplexType(ElementType);
5756 break;
5757 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005758 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005759 Type = Context.getFILEType();
5760 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005761 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005762 return QualType();
5763 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005764 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005765 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005766 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005767 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005768 else
5769 Type = Context.getjmp_bufType();
5770
Mike Stump2adb4da2009-07-28 23:47:15 +00005771 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005772 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005773 return QualType();
5774 }
5775 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005776 }
Mike Stump11289f42009-09-09 15:08:12 +00005777
Chris Lattnerdc226c22010-10-01 22:42:38 +00005778 // If there are modifiers and if we're allowed to parse them, go for it.
5779 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005780 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005781 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005782 default: Done = true; --Str; break;
5783 case '*':
5784 case '&': {
5785 // Both pointers and references can have their pointee types
5786 // qualified with an address space.
5787 char *End;
5788 unsigned AddrSpace = strtoul(Str, &End, 10);
5789 if (End != Str && AddrSpace != 0) {
5790 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5791 Str = End;
5792 }
5793 if (c == '*')
5794 Type = Context.getPointerType(Type);
5795 else
5796 Type = Context.getLValueReferenceType(Type);
5797 break;
5798 }
5799 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5800 case 'C':
5801 Type = Type.withConst();
5802 break;
5803 case 'D':
5804 Type = Context.getVolatileType(Type);
5805 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005806 }
5807 }
Chris Lattner84733392010-10-01 07:13:18 +00005808
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005809 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005810 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005811
Chris Lattnerecd79c62009-06-14 00:45:47 +00005812 return Type;
5813}
5814
5815/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005816QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005817 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005818 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005819 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005820
Chris Lattnerecd79c62009-06-14 00:45:47 +00005821 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005822
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005823 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005824 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005825 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5826 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005827 if (Error != GE_None)
5828 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005829
5830 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5831
Chris Lattnerecd79c62009-06-14 00:45:47 +00005832 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005833 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005834 if (Error != GE_None)
5835 return QualType();
5836
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005837 // If this argument is required to be an IntegerConstantExpression and the
5838 // caller cares, fill in the bitmask we return.
5839 if (RequiresICE && IntegerConstantArgs)
5840 *IntegerConstantArgs |= 1 << ArgTypes.size();
5841
Chris Lattnerecd79c62009-06-14 00:45:47 +00005842 // Do array -> pointer decay. The builtin should use the decayed type.
5843 if (Ty->isArrayType())
5844 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005845
Chris Lattnerecd79c62009-06-14 00:45:47 +00005846 ArgTypes.push_back(Ty);
5847 }
5848
5849 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5850 "'.' should only occur at end of builtin type list!");
5851
John McCall991eb4b2010-12-21 00:44:39 +00005852 FunctionType::ExtInfo EI;
5853 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5854
5855 bool Variadic = (TypeStr[0] == '.');
5856
5857 // We really shouldn't be making a no-proto type here, especially in C++.
5858 if (ArgTypes.empty() && Variadic)
5859 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005860
John McCalldb40c7f2010-12-14 08:05:40 +00005861 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005862 EPI.ExtInfo = EI;
5863 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00005864
5865 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005866}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005867
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005868GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5869 GVALinkage External = GVA_StrongExternal;
5870
5871 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005872 switch (L) {
5873 case NoLinkage:
5874 case InternalLinkage:
5875 case UniqueExternalLinkage:
5876 return GVA_Internal;
5877
5878 case ExternalLinkage:
5879 switch (FD->getTemplateSpecializationKind()) {
5880 case TSK_Undeclared:
5881 case TSK_ExplicitSpecialization:
5882 External = GVA_StrongExternal;
5883 break;
5884
5885 case TSK_ExplicitInstantiationDefinition:
5886 return GVA_ExplicitTemplateInstantiation;
5887
5888 case TSK_ExplicitInstantiationDeclaration:
5889 case TSK_ImplicitInstantiation:
5890 External = GVA_TemplateInstantiation;
5891 break;
5892 }
5893 }
5894
5895 if (!FD->isInlined())
5896 return External;
5897
5898 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5899 // GNU or C99 inline semantics. Determine whether this symbol should be
5900 // externally visible.
5901 if (FD->isInlineDefinitionExternallyVisible())
5902 return External;
5903
5904 // C99 inline semantics, where the symbol is not externally visible.
5905 return GVA_C99Inline;
5906 }
5907
5908 // C++0x [temp.explicit]p9:
5909 // [ Note: The intent is that an inline function that is the subject of
5910 // an explicit instantiation declaration will still be implicitly
5911 // instantiated when used so that the body can be considered for
5912 // inlining, but that no out-of-line copy of the inline function would be
5913 // generated in the translation unit. -- end note ]
5914 if (FD->getTemplateSpecializationKind()
5915 == TSK_ExplicitInstantiationDeclaration)
5916 return GVA_C99Inline;
5917
5918 return GVA_CXXInline;
5919}
5920
5921GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5922 // If this is a static data member, compute the kind of template
5923 // specialization. Otherwise, this variable is not part of a
5924 // template.
5925 TemplateSpecializationKind TSK = TSK_Undeclared;
5926 if (VD->isStaticDataMember())
5927 TSK = VD->getTemplateSpecializationKind();
5928
5929 Linkage L = VD->getLinkage();
5930 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5931 VD->getType()->getLinkage() == UniqueExternalLinkage)
5932 L = UniqueExternalLinkage;
5933
5934 switch (L) {
5935 case NoLinkage:
5936 case InternalLinkage:
5937 case UniqueExternalLinkage:
5938 return GVA_Internal;
5939
5940 case ExternalLinkage:
5941 switch (TSK) {
5942 case TSK_Undeclared:
5943 case TSK_ExplicitSpecialization:
5944 return GVA_StrongExternal;
5945
5946 case TSK_ExplicitInstantiationDeclaration:
5947 llvm_unreachable("Variable should not be instantiated");
5948 // Fall through to treat this like any other instantiation.
5949
5950 case TSK_ExplicitInstantiationDefinition:
5951 return GVA_ExplicitTemplateInstantiation;
5952
5953 case TSK_ImplicitInstantiation:
5954 return GVA_TemplateInstantiation;
5955 }
5956 }
5957
5958 return GVA_StrongExternal;
5959}
5960
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005961bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005962 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5963 if (!VD->isFileVarDecl())
5964 return false;
5965 } else if (!isa<FunctionDecl>(D))
5966 return false;
5967
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005968 // Weak references don't produce any output by themselves.
5969 if (D->hasAttr<WeakRefAttr>())
5970 return false;
5971
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005972 // Aliases and used decls are required.
5973 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5974 return true;
5975
5976 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5977 // Forward declarations aren't required.
5978 if (!FD->isThisDeclarationADefinition())
5979 return false;
5980
5981 // Constructors and destructors are required.
5982 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5983 return true;
5984
5985 // The key function for a class is required.
5986 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5987 const CXXRecordDecl *RD = MD->getParent();
5988 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5989 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5990 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5991 return true;
5992 }
5993 }
5994
5995 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5996
5997 // static, static inline, always_inline, and extern inline functions can
5998 // always be deferred. Normal inline functions can be deferred in C99/C++.
5999 // Implicit template instantiations can also be deferred in C++.
6000 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6001 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6002 return false;
6003 return true;
6004 }
6005
6006 const VarDecl *VD = cast<VarDecl>(D);
6007 assert(VD->isFileVarDecl() && "Expected file scoped var");
6008
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006009 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6010 return false;
6011
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006012 // Structs that have non-trivial constructors or destructors are required.
6013
6014 // FIXME: Handle references.
6015 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6016 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006017 if (RD->hasDefinition() &&
6018 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006019 return true;
6020 }
6021 }
6022
6023 GVALinkage L = GetGVALinkageForVariable(VD);
6024 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6025 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6026 return false;
6027 }
6028
6029 return true;
6030}
Charles Davis53c59df2010-08-16 03:33:14 +00006031
Charles Davis99202b32010-11-09 18:04:24 +00006032CallingConv ASTContext::getDefaultMethodCallConv() {
6033 // Pass through to the C++ ABI object
6034 return ABI->getDefaultMethodCallConv();
6035}
6036
Jay Foad39c79802011-01-12 09:06:06 +00006037bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006038 // Pass through to the C++ ABI object
6039 return ABI->isNearlyEmpty(RD);
6040}
6041
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006042MangleContext *ASTContext::createMangleContext() {
6043 switch (Target.getCXXABI()) {
6044 case CXXABI_ARM:
6045 case CXXABI_Itanium:
6046 return createItaniumMangleContext(*this, getDiagnostics());
6047 case CXXABI_Microsoft:
6048 return createMicrosoftMangleContext(*this, getDiagnostics());
6049 }
6050 assert(0 && "Unsupported ABI");
6051 return 0;
6052}
6053
Charles Davis53c59df2010-08-16 03:33:14 +00006054CXXABI::~CXXABI() {}