blob: 0b3febd0bdb28d8f964af50f1fb7dd5ea92567e8 [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),
John McCall147d0212011-02-22 22:38:33 +0000208 UniqueBlockByRefTypeID(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
Chris Lattner970e54e2006-11-12 00:37:36 +0000383 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000384 FloatComplexTy = getComplexType(FloatTy);
385 DoubleComplexTy = getComplexType(DoubleTy);
386 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000387
Steve Naroff66e9f332007-10-15 14:41:52 +0000388 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000389
Steve Naroff1329fa02009-07-15 18:40:39 +0000390 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
391 ObjCIdTypedefType = QualType();
392 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000393 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000394
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000395 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000396 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
397 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000398 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000399
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000400 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000401
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000402 // void * type
403 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000404
405 // nullptr type (C++0x 2.14.7)
406 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000407}
408
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000409Diagnostic &ASTContext::getDiagnostics() const {
410 return SourceMgr.getDiagnostics();
411}
412
Douglas Gregor561eceb2010-08-30 16:49:28 +0000413AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
414 AttrVec *&Result = DeclAttrs[D];
415 if (!Result) {
416 void *Mem = Allocate(sizeof(AttrVec));
417 Result = new (Mem) AttrVec;
418 }
419
420 return *Result;
421}
422
423/// \brief Erase the attributes corresponding to the given declaration.
424void ASTContext::eraseDeclAttrs(const Decl *D) {
425 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
426 if (Pos != DeclAttrs.end()) {
427 Pos->second->~AttrVec();
428 DeclAttrs.erase(Pos);
429 }
430}
431
432
Douglas Gregor86d142a2009-10-08 07:24:58 +0000433MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000434ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000435 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000436 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000437 = InstantiatedFromStaticDataMember.find(Var);
438 if (Pos == InstantiatedFromStaticDataMember.end())
439 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000440
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000441 return Pos->second;
442}
443
Mike Stump11289f42009-09-09 15:08:12 +0000444void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000445ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000446 TemplateSpecializationKind TSK,
447 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000448 assert(Inst->isStaticDataMember() && "Not a static data member");
449 assert(Tmpl->isStaticDataMember() && "Not a static data member");
450 assert(!InstantiatedFromStaticDataMember[Inst] &&
451 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000452 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000453 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000454}
455
John McCalle61f2ba2009-11-18 02:36:19 +0000456NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000457ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000458 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000459 = InstantiatedFromUsingDecl.find(UUD);
460 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000461 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000462
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000463 return Pos->second;
464}
465
466void
John McCallb96ec562009-12-04 22:46:56 +0000467ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
468 assert((isa<UsingDecl>(Pattern) ||
469 isa<UnresolvedUsingValueDecl>(Pattern) ||
470 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
471 "pattern decl is not a using decl");
472 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
473 InstantiatedFromUsingDecl[Inst] = Pattern;
474}
475
476UsingShadowDecl *
477ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
478 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
479 = InstantiatedFromUsingShadowDecl.find(Inst);
480 if (Pos == InstantiatedFromUsingShadowDecl.end())
481 return 0;
482
483 return Pos->second;
484}
485
486void
487ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
488 UsingShadowDecl *Pattern) {
489 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
490 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000491}
492
Anders Carlsson5da84842009-09-01 04:26:58 +0000493FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
494 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
495 = InstantiatedFromUnnamedFieldDecl.find(Field);
496 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
497 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000498
Anders Carlsson5da84842009-09-01 04:26:58 +0000499 return Pos->second;
500}
501
502void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
503 FieldDecl *Tmpl) {
504 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
505 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
506 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
507 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000508
Anders Carlsson5da84842009-09-01 04:26:58 +0000509 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
510}
511
Douglas Gregor832940b2010-03-02 23:58:15 +0000512ASTContext::overridden_cxx_method_iterator
513ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
514 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
515 = OverriddenMethods.find(Method);
516 if (Pos == OverriddenMethods.end())
517 return 0;
518
519 return Pos->second.begin();
520}
521
522ASTContext::overridden_cxx_method_iterator
523ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
524 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
525 = OverriddenMethods.find(Method);
526 if (Pos == OverriddenMethods.end())
527 return 0;
528
529 return Pos->second.end();
530}
531
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000532unsigned
533ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
534 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
535 = OverriddenMethods.find(Method);
536 if (Pos == OverriddenMethods.end())
537 return 0;
538
539 return Pos->second.size();
540}
541
Douglas Gregor832940b2010-03-02 23:58:15 +0000542void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
543 const CXXMethodDecl *Overridden) {
544 OverriddenMethods[Method].push_back(Overridden);
545}
546
Chris Lattner53cfe802007-07-18 17:52:12 +0000547//===----------------------------------------------------------------------===//
548// Type Sizing and Analysis
549//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000550
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000551/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
552/// scalar floating point type.
553const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000554 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000555 assert(BT && "Not a floating point type!");
556 switch (BT->getKind()) {
557 default: assert(0 && "Not a floating point type!");
558 case BuiltinType::Float: return Target.getFloatFormat();
559 case BuiltinType::Double: return Target.getDoubleFormat();
560 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
561 }
562}
563
Ken Dyck160146e2010-01-27 17:10:57 +0000564/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000565/// specified decl. Note that bitfields do not have a valid alignment, so
566/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000567/// If @p RefAsPointee, references are treated like their underlying type
568/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000569CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000570 unsigned Align = Target.getCharWidth();
571
John McCall94268702010-10-08 18:24:19 +0000572 bool UseAlignAttrOnly = false;
573 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
574 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000575
John McCall94268702010-10-08 18:24:19 +0000576 // __attribute__((aligned)) can increase or decrease alignment
577 // *except* on a struct or struct member, where it only increases
578 // alignment unless 'packed' is also specified.
579 //
580 // It is an error for [[align]] to decrease alignment, so we can
581 // ignore that possibility; Sema should diagnose it.
582 if (isa<FieldDecl>(D)) {
583 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
584 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
585 } else {
586 UseAlignAttrOnly = true;
587 }
588 }
589
John McCall4e819612011-01-20 07:57:12 +0000590 // If we're using the align attribute only, just ignore everything
591 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000592 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000593 // do nothing
594
John McCall94268702010-10-08 18:24:19 +0000595 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000596 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000597 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000598 if (RefAsPointee)
599 T = RT->getPointeeType();
600 else
601 T = getPointerType(RT->getPointeeType());
602 }
603 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000604 // Adjust alignments of declarations with array type by the
605 // large-array alignment on the target.
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000606 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000607 const ArrayType *arrayType;
608 if (MinWidth && (arrayType = getAsArrayType(T))) {
609 if (isa<VariableArrayType>(arrayType))
610 Align = std::max(Align, Target.getLargeArrayAlign());
611 else if (isa<ConstantArrayType>(arrayType) &&
612 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
613 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000614
John McCall33ddac02011-01-19 10:06:00 +0000615 // Walk through any array types while we're at it.
616 T = getBaseElementType(arrayType);
617 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000618 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
619 }
John McCall4e819612011-01-20 07:57:12 +0000620
621 // Fields can be subject to extra alignment constraints, like if
622 // the field is packed, the struct is packed, or the struct has a
623 // a max-field-alignment constraint (#pragma pack). So calculate
624 // the actual alignment of the field within the struct, and then
625 // (as we're expected to) constrain that by the alignment of the type.
626 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
627 // So calculate the alignment of the field.
628 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
629
630 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000631 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000632
633 // Use the GCD of that and the offset within the record.
634 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
635 if (offset > 0) {
636 // Alignment is always a power of 2, so the GCD will be a power of 2,
637 // which means we get to do this crazy thing instead of Euclid's.
638 uint64_t lowBitOfOffset = offset & (~offset + 1);
639 if (lowBitOfOffset < fieldAlign)
640 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
641 }
642
643 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000644 }
Chris Lattner68061312009-01-24 21:53:27 +0000645 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000646
Ken Dyckcc56c542011-01-15 18:38:59 +0000647 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000648}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000649
John McCall87fe5d52010-05-20 01:18:31 +0000650std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000651ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000652 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000653 return std::make_pair(toCharUnitsFromBits(Info.first),
654 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000655}
656
657std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000658ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000659 return getTypeInfoInChars(T.getTypePtr());
660}
661
Chris Lattner983a8bb2007-07-13 22:13:22 +0000662/// getTypeSize - Return the size of the specified type, in bits. This method
663/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000664///
665/// FIXME: Pointers into different addr spaces could have different sizes and
666/// alignment requirements: getPointerInfo should take an AddrSpace, this
667/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000668std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000669ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000670 uint64_t Width=0;
671 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000672 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000673#define TYPE(Class, Base)
674#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000675#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000676#define DEPENDENT_TYPE(Class, Base) case Type::Class:
677#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000678 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000679 break;
680
Chris Lattner355332d2007-07-13 22:27:08 +0000681 case Type::FunctionNoProto:
682 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000683 // GCC extension: alignof(function) = 32 bits
684 Width = 0;
685 Align = 32;
686 break;
687
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000688 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000689 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000690 Width = 0;
691 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
692 break;
693
Steve Naroff5c131802007-08-30 01:06:46 +0000694 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000695 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000696
Chris Lattner37e05872008-03-05 18:54:05 +0000697 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000698 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000699 Align = EltInfo.second;
700 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000701 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000702 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000703 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000704 const VectorType *VT = cast<VectorType>(T);
705 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
706 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000707 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000708 // If the alignment is not a power of 2, round up to the next power of 2.
709 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000710 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000711 Align = llvm::NextPowerOf2(Align);
712 Width = llvm::RoundUpToAlignment(Width, Align);
713 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000714 break;
715 }
Chris Lattner647fb222007-07-18 18:26:58 +0000716
Chris Lattner7570e9c2008-03-08 08:52:55 +0000717 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000718 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000719 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000720 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000721 // GCC extension: alignof(void) = 8 bits.
722 Width = 0;
723 Align = 8;
724 break;
725
Chris Lattner6a4f7452007-12-19 19:23:28 +0000726 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000727 Width = Target.getBoolWidth();
728 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000729 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000730 case BuiltinType::Char_S:
731 case BuiltinType::Char_U:
732 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000733 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000734 Width = Target.getCharWidth();
735 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000736 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000737 case BuiltinType::WChar_S:
738 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000739 Width = Target.getWCharWidth();
740 Align = Target.getWCharAlign();
741 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000742 case BuiltinType::Char16:
743 Width = Target.getChar16Width();
744 Align = Target.getChar16Align();
745 break;
746 case BuiltinType::Char32:
747 Width = Target.getChar32Width();
748 Align = Target.getChar32Align();
749 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000750 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000751 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000752 Width = Target.getShortWidth();
753 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000754 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000755 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000756 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000757 Width = Target.getIntWidth();
758 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000759 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000760 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000761 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000762 Width = Target.getLongWidth();
763 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000764 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000765 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000766 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000767 Width = Target.getLongLongWidth();
768 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000769 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000770 case BuiltinType::Int128:
771 case BuiltinType::UInt128:
772 Width = 128;
773 Align = 128; // int128_t is 128-bit aligned on all targets.
774 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000775 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000776 Width = Target.getFloatWidth();
777 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000778 break;
779 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000780 Width = Target.getDoubleWidth();
781 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000782 break;
783 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000784 Width = Target.getLongDoubleWidth();
785 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000786 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000787 case BuiltinType::NullPtr:
788 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
789 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000790 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000791 case BuiltinType::ObjCId:
792 case BuiltinType::ObjCClass:
793 case BuiltinType::ObjCSel:
794 Width = Target.getPointerWidth(0);
795 Align = Target.getPointerAlign(0);
796 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000797 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000798 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000799 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000800 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000801 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000802 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000803 case Type::BlockPointer: {
804 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
805 Width = Target.getPointerWidth(AS);
806 Align = Target.getPointerAlign(AS);
807 break;
808 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000809 case Type::LValueReference:
810 case Type::RValueReference: {
811 // alignof and sizeof should never enter this code path here, so we go
812 // the pointer route.
813 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
814 Width = Target.getPointerWidth(AS);
815 Align = Target.getPointerAlign(AS);
816 break;
817 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000818 case Type::Pointer: {
819 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000820 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000821 Align = Target.getPointerAlign(AS);
822 break;
823 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000824 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000825 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000826 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000827 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000828 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000829 Align = PtrDiffInfo.second;
830 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000831 }
Chris Lattner647fb222007-07-18 18:26:58 +0000832 case Type::Complex: {
833 // Complex types have the same alignment as their elements, but twice the
834 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000835 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000836 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000837 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000838 Align = EltInfo.second;
839 break;
840 }
John McCall8b07ec22010-05-15 11:32:37 +0000841 case Type::ObjCObject:
842 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000843 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000844 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000845 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000846 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000847 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000848 break;
849 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000850 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000851 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000852 const TagType *TT = cast<TagType>(T);
853
854 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000855 Width = 1;
856 Align = 1;
857 break;
858 }
Mike Stump11289f42009-09-09 15:08:12 +0000859
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000860 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000861 return getTypeInfo(ET->getDecl()->getIntegerType());
862
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000863 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000864 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000865 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000866 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +0000867 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000868 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000869
Chris Lattner63d2b362009-10-22 05:17:15 +0000870 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000871 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
872 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000873
Richard Smith30482bc2011-02-20 03:19:35 +0000874 case Type::Auto: {
875 const AutoType *A = cast<AutoType>(T);
876 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +0000877 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +0000878 }
879
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000880 case Type::Paren:
881 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
882
Douglas Gregoref462e62009-04-30 17:32:17 +0000883 case Type::Typedef: {
884 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000885 std::pair<uint64_t, unsigned> Info
886 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +0000887 // If the typedef has an aligned attribute on it, it overrides any computed
888 // alignment we have. This violates the GCC documentation (which says that
889 // attribute(aligned) can only round up) but matches its implementation.
890 if (unsigned AttrAlign = Typedef->getMaxAlignment())
891 Align = AttrAlign;
892 else
893 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +0000894 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000895 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000896 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000897
898 case Type::TypeOfExpr:
899 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
900 .getTypePtr());
901
902 case Type::TypeOf:
903 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
904
Anders Carlsson81df7b82009-06-24 19:06:50 +0000905 case Type::Decltype:
906 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
907 .getTypePtr());
908
Abramo Bagnara6150c882010-05-11 21:36:43 +0000909 case Type::Elaborated:
910 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000911
John McCall81904512011-01-06 01:58:22 +0000912 case Type::Attributed:
913 return getTypeInfo(
914 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
915
Douglas Gregoref462e62009-04-30 17:32:17 +0000916 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000917 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000918 "Cannot request the size of a dependent type");
919 // FIXME: this is likely to be wrong once we support template
920 // aliases, since a template alias could refer to a typedef that
921 // has an __aligned__ attribute on it.
922 return getTypeInfo(getCanonicalType(T));
923 }
Mike Stump11289f42009-09-09 15:08:12 +0000924
Chris Lattner53cfe802007-07-18 17:52:12 +0000925 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000926 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000927}
928
Ken Dyckcc56c542011-01-15 18:38:59 +0000929/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
930CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
931 return CharUnits::fromQuantity(BitSize / getCharWidth());
932}
933
Ken Dyckb0fcc592011-02-11 01:54:29 +0000934/// toBits - Convert a size in characters to a size in characters.
935int64_t ASTContext::toBits(CharUnits CharSize) const {
936 return CharSize.getQuantity() * getCharWidth();
937}
938
Ken Dyck8c89d592009-12-22 14:23:30 +0000939/// getTypeSizeInChars - Return the size of the specified type, in characters.
940/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000941CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000942 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000943}
Jay Foad39c79802011-01-12 09:06:06 +0000944CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000945 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000946}
947
Ken Dycka6046ab2010-01-26 17:25:18 +0000948/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000949/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000950CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000951 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000952}
Jay Foad39c79802011-01-12 09:06:06 +0000953CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000954 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000955}
956
Chris Lattnera3402cd2009-01-27 18:08:34 +0000957/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
958/// type for the current target in bits. This can be different than the ABI
959/// alignment in cases where it is beneficial for performance to overalign
960/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +0000961unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +0000962 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000963
964 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000965 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000966 T = CT->getElementType().getTypePtr();
967 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
968 T->isSpecificBuiltinType(BuiltinType::LongLong))
969 return std::max(ABIAlign, (unsigned)getTypeSize(T));
970
Chris Lattnera3402cd2009-01-27 18:08:34 +0000971 return ABIAlign;
972}
973
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000974/// ShallowCollectObjCIvars -
975/// Collect all ivars, including those synthesized, in the current class.
976///
977void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +0000978 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000979 // FIXME. This need be removed but there are two many places which
980 // assume const-ness of ObjCInterfaceDecl
981 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
982 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
983 Iv= Iv->getNextIvar())
984 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000985}
986
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000987/// DeepCollectObjCIvars -
988/// This routine first collects all declared, but not synthesized, ivars in
989/// super class and then collects all ivars, including those synthesized for
990/// current class. This routine is used for implementation of current class
991/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000992///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000993void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
994 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +0000995 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000996 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
997 DeepCollectObjCIvars(SuperClass, false, Ivars);
998 if (!leafClass) {
999 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1000 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001001 Ivars.push_back(*I);
1002 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001003 else
1004 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001005}
1006
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001007/// CollectInheritedProtocols - Collect all protocols in current class and
1008/// those inherited by it.
1009void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001010 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001011 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001012 // We can use protocol_iterator here instead of
1013 // all_referenced_protocol_iterator since we are walking all categories.
1014 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1015 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001016 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001017 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001018 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001019 PE = Proto->protocol_end(); P != PE; ++P) {
1020 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001021 CollectInheritedProtocols(*P, Protocols);
1022 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001023 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001024
1025 // Categories of this Interface.
1026 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1027 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1028 CollectInheritedProtocols(CDeclChain, Protocols);
1029 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1030 while (SD) {
1031 CollectInheritedProtocols(SD, Protocols);
1032 SD = SD->getSuperClass();
1033 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001034 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001035 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001036 PE = OC->protocol_end(); P != PE; ++P) {
1037 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001038 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001039 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1040 PE = Proto->protocol_end(); P != PE; ++P)
1041 CollectInheritedProtocols(*P, Protocols);
1042 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001043 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001044 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1045 PE = OP->protocol_end(); P != PE; ++P) {
1046 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001047 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001048 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1049 PE = Proto->protocol_end(); P != PE; ++P)
1050 CollectInheritedProtocols(*P, Protocols);
1051 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001052 }
1053}
1054
Jay Foad39c79802011-01-12 09:06:06 +00001055unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001056 unsigned count = 0;
1057 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001058 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1059 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001060 count += CDecl->ivar_size();
1061
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001062 // Count ivar defined in this class's implementation. This
1063 // includes synthesized ivars.
1064 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001065 count += ImplDecl->ivar_size();
1066
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001067 return count;
1068}
1069
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001070/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1071ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1072 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1073 I = ObjCImpls.find(D);
1074 if (I != ObjCImpls.end())
1075 return cast<ObjCImplementationDecl>(I->second);
1076 return 0;
1077}
1078/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1079ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1080 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1081 I = ObjCImpls.find(D);
1082 if (I != ObjCImpls.end())
1083 return cast<ObjCCategoryImplDecl>(I->second);
1084 return 0;
1085}
1086
1087/// \brief Set the implementation of ObjCInterfaceDecl.
1088void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1089 ObjCImplementationDecl *ImplD) {
1090 assert(IFaceD && ImplD && "Passed null params");
1091 ObjCImpls[IFaceD] = ImplD;
1092}
1093/// \brief Set the implementation of ObjCCategoryDecl.
1094void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1095 ObjCCategoryImplDecl *ImplD) {
1096 assert(CatD && ImplD && "Passed null params");
1097 ObjCImpls[CatD] = ImplD;
1098}
1099
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001100/// \brief Get the copy initialization expression of VarDecl,or NULL if
1101/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001102Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001103 assert(VD && "Passed null params");
1104 assert(VD->hasAttr<BlocksAttr>() &&
1105 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001106 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001107 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001108 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1109}
1110
1111/// \brief Set the copy inialization expression of a block var decl.
1112void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1113 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001114 assert(VD->hasAttr<BlocksAttr>() &&
1115 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001116 BlockVarCopyInits[VD] = Init;
1117}
1118
John McCallbcd03502009-12-07 02:54:59 +00001119/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001120///
John McCallbcd03502009-12-07 02:54:59 +00001121/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001122/// the TypeLoc wrappers.
1123///
1124/// \param T the type that will be the basis for type source info. This type
1125/// should refer to how the declarator was written in source code, not to
1126/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001127TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001128 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001129 if (!DataSize)
1130 DataSize = TypeLoc::getFullDataSizeForType(T);
1131 else
1132 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001133 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001134
John McCallbcd03502009-12-07 02:54:59 +00001135 TypeSourceInfo *TInfo =
1136 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1137 new (TInfo) TypeSourceInfo(T);
1138 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001139}
1140
John McCallbcd03502009-12-07 02:54:59 +00001141TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001142 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001143 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001144 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001145 return DI;
1146}
1147
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001148const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001149ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001150 return getObjCLayout(D, 0);
1151}
1152
1153const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001154ASTContext::getASTObjCImplementationLayout(
1155 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001156 return getObjCLayout(D->getClassInterface(), D);
1157}
1158
Chris Lattner983a8bb2007-07-13 22:13:22 +00001159//===----------------------------------------------------------------------===//
1160// Type creation/memoization methods
1161//===----------------------------------------------------------------------===//
1162
Jay Foad39c79802011-01-12 09:06:06 +00001163QualType
John McCall33ddac02011-01-19 10:06:00 +00001164ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1165 unsigned fastQuals = quals.getFastQualifiers();
1166 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001167
1168 // Check if we've already instantiated this type.
1169 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001170 ExtQuals::Profile(ID, baseType, quals);
1171 void *insertPos = 0;
1172 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1173 assert(eq->getQualifiers() == quals);
1174 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001175 }
1176
John McCall33ddac02011-01-19 10:06:00 +00001177 // If the base type is not canonical, make the appropriate canonical type.
1178 QualType canon;
1179 if (!baseType->isCanonicalUnqualified()) {
1180 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1181 canonSplit.second.addConsistentQualifiers(quals);
1182 canon = getExtQualType(canonSplit.first, canonSplit.second);
1183
1184 // Re-find the insert position.
1185 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1186 }
1187
1188 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1189 ExtQualNodes.InsertNode(eq, insertPos);
1190 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001191}
1192
Jay Foad39c79802011-01-12 09:06:06 +00001193QualType
1194ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001195 QualType CanT = getCanonicalType(T);
1196 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001197 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001198
John McCall8ccfcb52009-09-24 19:53:00 +00001199 // If we are composing extended qualifiers together, merge together
1200 // into one ExtQuals node.
1201 QualifierCollector Quals;
1202 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001203
John McCall8ccfcb52009-09-24 19:53:00 +00001204 // If this type already has an address space specified, it cannot get
1205 // another one.
1206 assert(!Quals.hasAddressSpace() &&
1207 "Type cannot be in multiple addr spaces!");
1208 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001209
John McCall8ccfcb52009-09-24 19:53:00 +00001210 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001211}
1212
Chris Lattnerd60183d2009-02-18 22:53:11 +00001213QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001214 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001215 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001216 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001217 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001218
John McCall53fa7142010-12-24 02:08:15 +00001219 if (const PointerType *ptr = T->getAs<PointerType>()) {
1220 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001221 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001222 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1223 return getPointerType(ResultType);
1224 }
1225 }
Mike Stump11289f42009-09-09 15:08:12 +00001226
John McCall8ccfcb52009-09-24 19:53:00 +00001227 // If we are composing extended qualifiers together, merge together
1228 // into one ExtQuals node.
1229 QualifierCollector Quals;
1230 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001231
John McCall8ccfcb52009-09-24 19:53:00 +00001232 // If this type already has an ObjCGC specified, it cannot get
1233 // another one.
1234 assert(!Quals.hasObjCGCAttr() &&
1235 "Type cannot have multiple ObjCGCs!");
1236 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001237
John McCall8ccfcb52009-09-24 19:53:00 +00001238 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001239}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001240
John McCall4f5019e2010-12-19 02:44:49 +00001241const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1242 FunctionType::ExtInfo Info) {
1243 if (T->getExtInfo() == Info)
1244 return T;
1245
1246 QualType Result;
1247 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1248 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1249 } else {
1250 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1251 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1252 EPI.ExtInfo = Info;
1253 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1254 FPT->getNumArgs(), EPI);
1255 }
1256
1257 return cast<FunctionType>(Result.getTypePtr());
1258}
1259
Chris Lattnerc6395932007-06-22 20:56:16 +00001260/// getComplexType - Return the uniqued reference to the type for a complex
1261/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001262QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001263 // Unique pointers, to guarantee there is only one pointer of a particular
1264 // structure.
1265 llvm::FoldingSetNodeID ID;
1266 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001267
Chris Lattnerc6395932007-06-22 20:56:16 +00001268 void *InsertPos = 0;
1269 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1270 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001271
Chris Lattnerc6395932007-06-22 20:56:16 +00001272 // If the pointee type isn't canonical, this won't be a canonical type either,
1273 // so fill in the canonical type field.
1274 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001275 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001276 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001277
Chris Lattnerc6395932007-06-22 20:56:16 +00001278 // Get the new insert position for the node we care about.
1279 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001280 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001281 }
John McCall90d1c2d2009-09-24 23:30:46 +00001282 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001283 Types.push_back(New);
1284 ComplexTypes.InsertNode(New, InsertPos);
1285 return QualType(New, 0);
1286}
1287
Chris Lattner970e54e2006-11-12 00:37:36 +00001288/// getPointerType - Return the uniqued reference to the type for a pointer to
1289/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001290QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001291 // Unique pointers, to guarantee there is only one pointer of a particular
1292 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001293 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001294 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001295
Chris Lattner67521df2007-01-27 01:29:36 +00001296 void *InsertPos = 0;
1297 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001298 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001299
Chris Lattner7ccecb92006-11-12 08:50:50 +00001300 // If the pointee type isn't canonical, this won't be a canonical type either,
1301 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001302 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001303 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001304 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001305
Chris Lattner67521df2007-01-27 01:29:36 +00001306 // Get the new insert position for the node we care about.
1307 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001308 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001309 }
John McCall90d1c2d2009-09-24 23:30:46 +00001310 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001311 Types.push_back(New);
1312 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001313 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001314}
1315
Mike Stump11289f42009-09-09 15:08:12 +00001316/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001317/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001318QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001319 assert(T->isFunctionType() && "block of function types only");
1320 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001321 // structure.
1322 llvm::FoldingSetNodeID ID;
1323 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001324
Steve Naroffec33ed92008-08-27 16:04:49 +00001325 void *InsertPos = 0;
1326 if (BlockPointerType *PT =
1327 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1328 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001329
1330 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001331 // type either so fill in the canonical type field.
1332 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001333 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001334 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001335
Steve Naroffec33ed92008-08-27 16:04:49 +00001336 // Get the new insert position for the node we care about.
1337 BlockPointerType *NewIP =
1338 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001339 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001340 }
John McCall90d1c2d2009-09-24 23:30:46 +00001341 BlockPointerType *New
1342 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001343 Types.push_back(New);
1344 BlockPointerTypes.InsertNode(New, InsertPos);
1345 return QualType(New, 0);
1346}
1347
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001348/// getLValueReferenceType - Return the uniqued reference to the type for an
1349/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001350QualType
1351ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001352 // Unique pointers, to guarantee there is only one pointer of a particular
1353 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001354 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001355 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001356
1357 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001358 if (LValueReferenceType *RT =
1359 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001360 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001361
John McCallfc93cf92009-10-22 22:37:11 +00001362 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1363
Bill Wendling3708c182007-05-27 10:15:43 +00001364 // If the referencee type isn't canonical, this won't be a canonical type
1365 // either, so fill in the canonical type field.
1366 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001367 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1368 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1369 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001370
Bill Wendling3708c182007-05-27 10:15:43 +00001371 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001372 LValueReferenceType *NewIP =
1373 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001374 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001375 }
1376
John McCall90d1c2d2009-09-24 23:30:46 +00001377 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001378 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1379 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001380 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001381 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001382
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001383 return QualType(New, 0);
1384}
1385
1386/// getRValueReferenceType - Return the uniqued reference to the type for an
1387/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001388QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001389 // Unique pointers, to guarantee there is only one pointer of a particular
1390 // structure.
1391 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001392 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001393
1394 void *InsertPos = 0;
1395 if (RValueReferenceType *RT =
1396 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1397 return QualType(RT, 0);
1398
John McCallfc93cf92009-10-22 22:37:11 +00001399 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1400
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001401 // If the referencee type isn't canonical, this won't be a canonical type
1402 // either, so fill in the canonical type field.
1403 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001404 if (InnerRef || !T.isCanonical()) {
1405 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1406 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001407
1408 // Get the new insert position for the node we care about.
1409 RValueReferenceType *NewIP =
1410 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001411 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001412 }
1413
John McCall90d1c2d2009-09-24 23:30:46 +00001414 RValueReferenceType *New
1415 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001416 Types.push_back(New);
1417 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001418 return QualType(New, 0);
1419}
1420
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001421/// getMemberPointerType - Return the uniqued reference to the type for a
1422/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001423QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001424 // Unique pointers, to guarantee there is only one pointer of a particular
1425 // structure.
1426 llvm::FoldingSetNodeID ID;
1427 MemberPointerType::Profile(ID, T, Cls);
1428
1429 void *InsertPos = 0;
1430 if (MemberPointerType *PT =
1431 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1432 return QualType(PT, 0);
1433
1434 // If the pointee or class type isn't canonical, this won't be a canonical
1435 // type either, so fill in the canonical type field.
1436 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001437 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001438 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1439
1440 // Get the new insert position for the node we care about.
1441 MemberPointerType *NewIP =
1442 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001443 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001444 }
John McCall90d1c2d2009-09-24 23:30:46 +00001445 MemberPointerType *New
1446 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001447 Types.push_back(New);
1448 MemberPointerTypes.InsertNode(New, InsertPos);
1449 return QualType(New, 0);
1450}
1451
Mike Stump11289f42009-09-09 15:08:12 +00001452/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001453/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001454QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001455 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001456 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001457 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001458 assert((EltTy->isDependentType() ||
1459 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001460 "Constant array of VLAs is illegal!");
1461
Chris Lattnere2df3f92009-05-13 04:12:56 +00001462 // Convert the array size into a canonical width matching the pointer size for
1463 // the target.
1464 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001465 ArySize =
1466 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001467
Chris Lattner23b7eb62007-06-15 23:05:46 +00001468 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001469 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001470
Chris Lattner36f8e652007-01-27 08:31:04 +00001471 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001472 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001473 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001474 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001475
John McCall33ddac02011-01-19 10:06:00 +00001476 // If the element type isn't canonical or has qualifiers, this won't
1477 // be a canonical type either, so fill in the canonical type field.
1478 QualType Canon;
1479 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1480 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1481 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001482 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001483 Canon = getQualifiedType(Canon, canonSplit.second);
1484
Chris Lattner36f8e652007-01-27 08:31:04 +00001485 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001486 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001487 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001488 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001489 }
Mike Stump11289f42009-09-09 15:08:12 +00001490
John McCall90d1c2d2009-09-24 23:30:46 +00001491 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001492 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001493 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001494 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001495 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001496}
1497
John McCall06549462011-01-18 08:40:38 +00001498/// getVariableArrayDecayedType - Turns the given type, which may be
1499/// variably-modified, into the corresponding type with all the known
1500/// sizes replaced with [*].
1501QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1502 // Vastly most common case.
1503 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001504
John McCall06549462011-01-18 08:40:38 +00001505 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001506
John McCall06549462011-01-18 08:40:38 +00001507 SplitQualType split = type.getSplitDesugaredType();
1508 const Type *ty = split.first;
1509 switch (ty->getTypeClass()) {
1510#define TYPE(Class, Base)
1511#define ABSTRACT_TYPE(Class, Base)
1512#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1513#include "clang/AST/TypeNodes.def"
1514 llvm_unreachable("didn't desugar past all non-canonical types?");
1515
1516 // These types should never be variably-modified.
1517 case Type::Builtin:
1518 case Type::Complex:
1519 case Type::Vector:
1520 case Type::ExtVector:
1521 case Type::DependentSizedExtVector:
1522 case Type::ObjCObject:
1523 case Type::ObjCInterface:
1524 case Type::ObjCObjectPointer:
1525 case Type::Record:
1526 case Type::Enum:
1527 case Type::UnresolvedUsing:
1528 case Type::TypeOfExpr:
1529 case Type::TypeOf:
1530 case Type::Decltype:
1531 case Type::DependentName:
1532 case Type::InjectedClassName:
1533 case Type::TemplateSpecialization:
1534 case Type::DependentTemplateSpecialization:
1535 case Type::TemplateTypeParm:
1536 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001537 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001538 case Type::PackExpansion:
1539 llvm_unreachable("type should never be variably-modified");
1540
1541 // These types can be variably-modified but should never need to
1542 // further decay.
1543 case Type::FunctionNoProto:
1544 case Type::FunctionProto:
1545 case Type::BlockPointer:
1546 case Type::MemberPointer:
1547 return type;
1548
1549 // These types can be variably-modified. All these modifications
1550 // preserve structure except as noted by comments.
1551 // TODO: if we ever care about optimizing VLAs, there are no-op
1552 // optimizations available here.
1553 case Type::Pointer:
1554 result = getPointerType(getVariableArrayDecayedType(
1555 cast<PointerType>(ty)->getPointeeType()));
1556 break;
1557
1558 case Type::LValueReference: {
1559 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1560 result = getLValueReferenceType(
1561 getVariableArrayDecayedType(lv->getPointeeType()),
1562 lv->isSpelledAsLValue());
1563 break;
1564 }
1565
1566 case Type::RValueReference: {
1567 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1568 result = getRValueReferenceType(
1569 getVariableArrayDecayedType(lv->getPointeeType()));
1570 break;
1571 }
1572
1573 case Type::ConstantArray: {
1574 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1575 result = getConstantArrayType(
1576 getVariableArrayDecayedType(cat->getElementType()),
1577 cat->getSize(),
1578 cat->getSizeModifier(),
1579 cat->getIndexTypeCVRQualifiers());
1580 break;
1581 }
1582
1583 case Type::DependentSizedArray: {
1584 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1585 result = getDependentSizedArrayType(
1586 getVariableArrayDecayedType(dat->getElementType()),
1587 dat->getSizeExpr(),
1588 dat->getSizeModifier(),
1589 dat->getIndexTypeCVRQualifiers(),
1590 dat->getBracketsRange());
1591 break;
1592 }
1593
1594 // Turn incomplete types into [*] types.
1595 case Type::IncompleteArray: {
1596 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1597 result = getVariableArrayType(
1598 getVariableArrayDecayedType(iat->getElementType()),
1599 /*size*/ 0,
1600 ArrayType::Normal,
1601 iat->getIndexTypeCVRQualifiers(),
1602 SourceRange());
1603 break;
1604 }
1605
1606 // Turn VLA types into [*] types.
1607 case Type::VariableArray: {
1608 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1609 result = getVariableArrayType(
1610 getVariableArrayDecayedType(vat->getElementType()),
1611 /*size*/ 0,
1612 ArrayType::Star,
1613 vat->getIndexTypeCVRQualifiers(),
1614 vat->getBracketsRange());
1615 break;
1616 }
1617 }
1618
1619 // Apply the top-level qualifiers from the original.
1620 return getQualifiedType(result, split.second);
1621}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001622
Steve Naroffcadebd02007-08-30 18:14:25 +00001623/// getVariableArrayType - Returns a non-unique reference to the type for a
1624/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001625QualType ASTContext::getVariableArrayType(QualType EltTy,
1626 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001627 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001628 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001629 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001630 // Since we don't unique expressions, it isn't possible to unique VLA's
1631 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001632 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001633
John McCall33ddac02011-01-19 10:06:00 +00001634 // Be sure to pull qualifiers off the element type.
1635 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1636 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1637 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001638 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001639 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001640 }
1641
John McCall90d1c2d2009-09-24 23:30:46 +00001642 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001643 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001644
1645 VariableArrayTypes.push_back(New);
1646 Types.push_back(New);
1647 return QualType(New, 0);
1648}
1649
Douglas Gregor4619e432008-12-05 23:32:09 +00001650/// getDependentSizedArrayType - Returns a non-unique reference to
1651/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001652/// type.
John McCall33ddac02011-01-19 10:06:00 +00001653QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1654 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001655 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001656 unsigned elementTypeQuals,
1657 SourceRange brackets) const {
1658 assert((!numElements || numElements->isTypeDependent() ||
1659 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001660 "Size must be type- or value-dependent!");
1661
John McCall33ddac02011-01-19 10:06:00 +00001662 // Dependently-sized array types that do not have a specified number
1663 // of elements will have their sizes deduced from a dependent
1664 // initializer. We do no canonicalization here at all, which is okay
1665 // because they can't be used in most locations.
1666 if (!numElements) {
1667 DependentSizedArrayType *newType
1668 = new (*this, TypeAlignment)
1669 DependentSizedArrayType(*this, elementType, QualType(),
1670 numElements, ASM, elementTypeQuals,
1671 brackets);
1672 Types.push_back(newType);
1673 return QualType(newType, 0);
1674 }
1675
1676 // Otherwise, we actually build a new type every time, but we
1677 // also build a canonical type.
1678
1679 SplitQualType canonElementType = getCanonicalType(elementType).split();
1680
1681 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001682 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001683 DependentSizedArrayType::Profile(ID, *this,
1684 QualType(canonElementType.first, 0),
1685 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001686
John McCall33ddac02011-01-19 10:06:00 +00001687 // Look for an existing type with these properties.
1688 DependentSizedArrayType *canonTy =
1689 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001690
John McCall33ddac02011-01-19 10:06:00 +00001691 // If we don't have one, build one.
1692 if (!canonTy) {
1693 canonTy = new (*this, TypeAlignment)
1694 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1695 QualType(), numElements, ASM, elementTypeQuals,
1696 brackets);
1697 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1698 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001699 }
1700
John McCall33ddac02011-01-19 10:06:00 +00001701 // Apply qualifiers from the element type to the array.
1702 QualType canon = getQualifiedType(QualType(canonTy,0),
1703 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001704
John McCall33ddac02011-01-19 10:06:00 +00001705 // If we didn't need extra canonicalization for the element type,
1706 // then just use that as our result.
1707 if (QualType(canonElementType.first, 0) == elementType)
1708 return canon;
1709
1710 // Otherwise, we need to build a type which follows the spelling
1711 // of the element type.
1712 DependentSizedArrayType *sugaredType
1713 = new (*this, TypeAlignment)
1714 DependentSizedArrayType(*this, elementType, canon, numElements,
1715 ASM, elementTypeQuals, brackets);
1716 Types.push_back(sugaredType);
1717 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001718}
1719
John McCall33ddac02011-01-19 10:06:00 +00001720QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001721 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001722 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001723 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001724 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001725
John McCall33ddac02011-01-19 10:06:00 +00001726 void *insertPos = 0;
1727 if (IncompleteArrayType *iat =
1728 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1729 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001730
1731 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001732 // either, so fill in the canonical type field. We also have to pull
1733 // qualifiers off the element type.
1734 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001735
John McCall33ddac02011-01-19 10:06:00 +00001736 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1737 SplitQualType canonSplit = getCanonicalType(elementType).split();
1738 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1739 ASM, elementTypeQuals);
1740 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001741
1742 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001743 IncompleteArrayType *existing =
1744 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1745 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001746 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001747
John McCall33ddac02011-01-19 10:06:00 +00001748 IncompleteArrayType *newType = new (*this, TypeAlignment)
1749 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001750
John McCall33ddac02011-01-19 10:06:00 +00001751 IncompleteArrayTypes.InsertNode(newType, insertPos);
1752 Types.push_back(newType);
1753 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001754}
1755
Steve Naroff91fcddb2007-07-18 18:00:27 +00001756/// getVectorType - Return the unique reference to a vector type of
1757/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001758QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001759 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001760 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001761
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001762 // Check if we've already instantiated a vector of this type.
1763 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001764 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001765
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001766 void *InsertPos = 0;
1767 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1768 return QualType(VTP, 0);
1769
1770 // If the element type isn't canonical, this won't be a canonical type either,
1771 // so fill in the canonical type field.
1772 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001773 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001774 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001775
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001776 // Get the new insert position for the node we care about.
1777 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001778 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001779 }
John McCall90d1c2d2009-09-24 23:30:46 +00001780 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001781 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001782 VectorTypes.InsertNode(New, InsertPos);
1783 Types.push_back(New);
1784 return QualType(New, 0);
1785}
1786
Nate Begemance4d7fc2008-04-18 23:10:10 +00001787/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001788/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001789QualType
1790ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall33ddac02011-01-19 10:06:00 +00001791 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001792
Steve Naroff91fcddb2007-07-18 18:00:27 +00001793 // Check if we've already instantiated a vector of this type.
1794 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001795 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001796 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001797 void *InsertPos = 0;
1798 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1799 return QualType(VTP, 0);
1800
1801 // If the element type isn't canonical, this won't be a canonical type either,
1802 // so fill in the canonical type field.
1803 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001804 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001805 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001806
Steve Naroff91fcddb2007-07-18 18:00:27 +00001807 // Get the new insert position for the node we care about.
1808 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001809 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001810 }
John McCall90d1c2d2009-09-24 23:30:46 +00001811 ExtVectorType *New = new (*this, TypeAlignment)
1812 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001813 VectorTypes.InsertNode(New, InsertPos);
1814 Types.push_back(New);
1815 return QualType(New, 0);
1816}
1817
Jay Foad39c79802011-01-12 09:06:06 +00001818QualType
1819ASTContext::getDependentSizedExtVectorType(QualType vecType,
1820 Expr *SizeExpr,
1821 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001822 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001823 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001824 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001825
Douglas Gregor352169a2009-07-31 03:54:25 +00001826 void *InsertPos = 0;
1827 DependentSizedExtVectorType *Canon
1828 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1829 DependentSizedExtVectorType *New;
1830 if (Canon) {
1831 // We already have a canonical version of this array type; use it as
1832 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001833 New = new (*this, TypeAlignment)
1834 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1835 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001836 } else {
1837 QualType CanonVecTy = getCanonicalType(vecType);
1838 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001839 New = new (*this, TypeAlignment)
1840 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1841 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001842
1843 DependentSizedExtVectorType *CanonCheck
1844 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1845 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1846 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001847 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1848 } else {
1849 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1850 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001851 New = new (*this, TypeAlignment)
1852 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001853 }
1854 }
Mike Stump11289f42009-09-09 15:08:12 +00001855
Douglas Gregor758a8692009-06-17 21:51:59 +00001856 Types.push_back(New);
1857 return QualType(New, 0);
1858}
1859
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001860/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001861///
Jay Foad39c79802011-01-12 09:06:06 +00001862QualType
1863ASTContext::getFunctionNoProtoType(QualType ResultTy,
1864 const FunctionType::ExtInfo &Info) const {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001865 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001866 // Unique functions, to guarantee there is only one function of a particular
1867 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001868 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001869 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001870
Chris Lattner47955de2007-01-27 08:37:20 +00001871 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001872 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001873 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001874 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001875
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001876 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001877 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001878 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001879 Canonical =
1880 getFunctionNoProtoType(getCanonicalType(ResultTy),
1881 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001882
Chris Lattner47955de2007-01-27 08:37:20 +00001883 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001884 FunctionNoProtoType *NewIP =
1885 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001886 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001887 }
Mike Stump11289f42009-09-09 15:08:12 +00001888
John McCall90d1c2d2009-09-24 23:30:46 +00001889 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001890 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001891 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001892 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001893 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001894}
1895
1896/// getFunctionType - Return a normal function type with a typed argument
1897/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001898QualType
1899ASTContext::getFunctionType(QualType ResultTy,
1900 const QualType *ArgArray, unsigned NumArgs,
1901 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001902 // Unique functions, to guarantee there is only one function of a particular
1903 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001904 llvm::FoldingSetNodeID ID;
John McCalldb40c7f2010-12-14 08:05:40 +00001905 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001906
1907 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001908 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001909 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001910 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001911
1912 // Determine whether the type being created is already canonical or not.
John McCalldb40c7f2010-12-14 08:05:40 +00001913 bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001914 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001915 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001916 isCanonical = false;
1917
John McCalldb40c7f2010-12-14 08:05:40 +00001918 const CallingConv CallConv = EPI.ExtInfo.getCC();
1919
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001920 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001921 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001922 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001923 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001924 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001925 CanonicalArgs.reserve(NumArgs);
1926 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001927 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001928
John McCalldb40c7f2010-12-14 08:05:40 +00001929 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1930 if (CanonicalEPI.HasExceptionSpec) {
1931 CanonicalEPI.HasExceptionSpec = false;
1932 CanonicalEPI.HasAnyExceptionSpec = false;
1933 CanonicalEPI.NumExceptions = 0;
1934 }
1935 CanonicalEPI.ExtInfo
1936 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1937
Chris Lattner76a00cf2008-04-06 22:59:24 +00001938 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001939 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00001940 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001941
Chris Lattnerfd4de792007-01-27 01:15:32 +00001942 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001943 FunctionProtoType *NewIP =
1944 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001945 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001946 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001947
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001948 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001949 // for two variable size arrays (for parameter and exception types) at the
1950 // end of them.
John McCalldb40c7f2010-12-14 08:05:40 +00001951 size_t Size = sizeof(FunctionProtoType) +
1952 NumArgs * sizeof(QualType) +
1953 EPI.NumExceptions * sizeof(QualType);
1954 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
1955 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, EPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001956 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001957 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001958 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001959}
Chris Lattneref51c202006-11-10 07:17:23 +00001960
John McCalle78aac42010-03-10 03:28:59 +00001961#ifndef NDEBUG
1962static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1963 if (!isa<CXXRecordDecl>(D)) return false;
1964 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1965 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1966 return true;
1967 if (RD->getDescribedClassTemplate() &&
1968 !isa<ClassTemplateSpecializationDecl>(RD))
1969 return true;
1970 return false;
1971}
1972#endif
1973
1974/// getInjectedClassNameType - Return the unique reference to the
1975/// injected class name type for the specified templated declaration.
1976QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00001977 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00001978 assert(NeedsInjectedClassNameType(Decl));
1979 if (Decl->TypeForDecl) {
1980 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001981 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001982 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1983 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1984 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1985 } else {
John McCall424cec92011-01-19 06:33:43 +00001986 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00001987 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00001988 Decl->TypeForDecl = newType;
1989 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00001990 }
1991 return QualType(Decl->TypeForDecl, 0);
1992}
1993
Douglas Gregor83a586e2008-04-13 21:07:44 +00001994/// getTypeDeclType - Return the unique reference to the type for the
1995/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00001996QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001997 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001998 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001999
John McCall81e38502010-02-16 03:57:14 +00002000 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002001 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002002
John McCall96f0b5f2010-03-10 06:48:02 +00002003 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2004 "Template type parameter types are always available.");
2005
John McCall81e38502010-02-16 03:57:14 +00002006 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002007 assert(!Record->getPreviousDeclaration() &&
2008 "struct/union has previous declaration");
2009 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002010 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002011 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002012 assert(!Enum->getPreviousDeclaration() &&
2013 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002014 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002015 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002016 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002017 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2018 Decl->TypeForDecl = newType;
2019 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002020 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002021 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002022
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002023 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002024}
2025
Chris Lattner32d920b2007-01-26 02:01:53 +00002026/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00002027/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002028QualType
Jay Foad39c79802011-01-12 09:06:06 +00002029ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002030 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002031
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002032 if (Canonical.isNull())
2033 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002034 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002035 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002036 Decl->TypeForDecl = newType;
2037 Types.push_back(newType);
2038 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002039}
2040
Jay Foad39c79802011-01-12 09:06:06 +00002041QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002042 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2043
2044 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2045 if (PrevDecl->TypeForDecl)
2046 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2047
John McCall424cec92011-01-19 06:33:43 +00002048 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2049 Decl->TypeForDecl = newType;
2050 Types.push_back(newType);
2051 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002052}
2053
Jay Foad39c79802011-01-12 09:06:06 +00002054QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002055 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2056
2057 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2058 if (PrevDecl->TypeForDecl)
2059 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2060
John McCall424cec92011-01-19 06:33:43 +00002061 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2062 Decl->TypeForDecl = newType;
2063 Types.push_back(newType);
2064 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002065}
2066
John McCall81904512011-01-06 01:58:22 +00002067QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2068 QualType modifiedType,
2069 QualType equivalentType) {
2070 llvm::FoldingSetNodeID id;
2071 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2072
2073 void *insertPos = 0;
2074 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2075 if (type) return QualType(type, 0);
2076
2077 QualType canon = getCanonicalType(equivalentType);
2078 type = new (*this, TypeAlignment)
2079 AttributedType(canon, attrKind, modifiedType, equivalentType);
2080
2081 Types.push_back(type);
2082 AttributedTypes.InsertNode(type, insertPos);
2083
2084 return QualType(type, 0);
2085}
2086
2087
John McCallcebee162009-10-18 09:09:24 +00002088/// \brief Retrieve a substitution-result type.
2089QualType
2090ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002091 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002092 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002093 && "replacement types must always be canonical");
2094
2095 llvm::FoldingSetNodeID ID;
2096 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2097 void *InsertPos = 0;
2098 SubstTemplateTypeParmType *SubstParm
2099 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2100
2101 if (!SubstParm) {
2102 SubstParm = new (*this, TypeAlignment)
2103 SubstTemplateTypeParmType(Parm, Replacement);
2104 Types.push_back(SubstParm);
2105 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2106 }
2107
2108 return QualType(SubstParm, 0);
2109}
2110
Douglas Gregorada4b792011-01-14 02:55:32 +00002111/// \brief Retrieve a
2112QualType ASTContext::getSubstTemplateTypeParmPackType(
2113 const TemplateTypeParmType *Parm,
2114 const TemplateArgument &ArgPack) {
2115#ifndef NDEBUG
2116 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2117 PEnd = ArgPack.pack_end();
2118 P != PEnd; ++P) {
2119 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2120 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2121 }
2122#endif
2123
2124 llvm::FoldingSetNodeID ID;
2125 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2126 void *InsertPos = 0;
2127 if (SubstTemplateTypeParmPackType *SubstParm
2128 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2129 return QualType(SubstParm, 0);
2130
2131 QualType Canon;
2132 if (!Parm->isCanonicalUnqualified()) {
2133 Canon = getCanonicalType(QualType(Parm, 0));
2134 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2135 ArgPack);
2136 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2137 }
2138
2139 SubstTemplateTypeParmPackType *SubstParm
2140 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2141 ArgPack);
2142 Types.push_back(SubstParm);
2143 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2144 return QualType(SubstParm, 0);
2145}
2146
Douglas Gregoreff93e02009-02-05 23:33:38 +00002147/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002148/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002149/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002150QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002151 bool ParameterPack,
Jay Foad39c79802011-01-12 09:06:06 +00002152 IdentifierInfo *Name) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002153 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002154 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002155 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002156 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002157 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2158
2159 if (TypeParm)
2160 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002161
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002162 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002163 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002164 TypeParm = new (*this, TypeAlignment)
2165 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002166
2167 TemplateTypeParmType *TypeCheck
2168 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2169 assert(!TypeCheck && "Template type parameter canonical type broken");
2170 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002171 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002172 TypeParm = new (*this, TypeAlignment)
2173 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002174
2175 Types.push_back(TypeParm);
2176 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2177
2178 return QualType(TypeParm, 0);
2179}
2180
John McCalle78aac42010-03-10 03:28:59 +00002181TypeSourceInfo *
2182ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2183 SourceLocation NameLoc,
2184 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002185 QualType CanonType) const {
John McCalle78aac42010-03-10 03:28:59 +00002186 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2187
2188 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2189 TemplateSpecializationTypeLoc TL
2190 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2191 TL.setTemplateNameLoc(NameLoc);
2192 TL.setLAngleLoc(Args.getLAngleLoc());
2193 TL.setRAngleLoc(Args.getRAngleLoc());
2194 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2195 TL.setArgLocInfo(i, Args[i].getLocInfo());
2196 return DI;
2197}
2198
Mike Stump11289f42009-09-09 15:08:12 +00002199QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002200ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002201 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002202 QualType Canon) const {
John McCall6b51f282009-11-23 01:53:49 +00002203 unsigned NumArgs = Args.size();
2204
John McCall0ad16662009-10-29 08:12:44 +00002205 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2206 ArgVec.reserve(NumArgs);
2207 for (unsigned i = 0; i != NumArgs; ++i)
2208 ArgVec.push_back(Args[i].getArgument());
2209
John McCall2408e322010-04-27 00:57:59 +00002210 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00002211 Canon);
John McCall0ad16662009-10-29 08:12:44 +00002212}
2213
2214QualType
2215ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002216 const TemplateArgument *Args,
2217 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002218 QualType Canon) const {
Douglas Gregor15301382009-07-30 17:40:51 +00002219 if (!Canon.isNull())
2220 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002221 else
2222 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00002223
Douglas Gregora8e02e72009-07-28 23:00:59 +00002224 // Allocate the (non-canonical) template specialization type, but don't
2225 // try to unique it: these types typically have location information that
2226 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002227 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002228 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002229 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002230 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002231 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002232 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002233 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002234
Douglas Gregor8bf42052009-02-09 18:46:07 +00002235 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002236 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002237}
2238
Mike Stump11289f42009-09-09 15:08:12 +00002239QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002240ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2241 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002242 unsigned NumArgs) const {
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002243 // Build the canonical template specialization type.
2244 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2245 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2246 CanonArgs.reserve(NumArgs);
2247 for (unsigned I = 0; I != NumArgs; ++I)
2248 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2249
2250 // Determine whether this canonical template specialization type already
2251 // exists.
2252 llvm::FoldingSetNodeID ID;
2253 TemplateSpecializationType::Profile(ID, CanonTemplate,
2254 CanonArgs.data(), NumArgs, *this);
2255
2256 void *InsertPos = 0;
2257 TemplateSpecializationType *Spec
2258 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2259
2260 if (!Spec) {
2261 // Allocate a new canonical template specialization type.
2262 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2263 sizeof(TemplateArgument) * NumArgs),
2264 TypeAlignment);
2265 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2266 CanonArgs.data(), NumArgs,
2267 QualType());
2268 Types.push_back(Spec);
2269 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2270 }
2271
2272 assert(Spec->isDependentType() &&
2273 "Non-dependent template-id type must have a canonical type");
2274 return QualType(Spec, 0);
2275}
2276
2277QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002278ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2279 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002280 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002281 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002282 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002283
2284 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002285 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002286 if (T)
2287 return QualType(T, 0);
2288
Douglas Gregorc42075a2010-02-04 18:10:26 +00002289 QualType Canon = NamedType;
2290 if (!Canon.isCanonical()) {
2291 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002292 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2293 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002294 (void)CheckT;
2295 }
2296
Abramo Bagnara6150c882010-05-11 21:36:43 +00002297 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002298 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002299 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002300 return QualType(T, 0);
2301}
2302
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002303QualType
Jay Foad39c79802011-01-12 09:06:06 +00002304ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002305 llvm::FoldingSetNodeID ID;
2306 ParenType::Profile(ID, InnerType);
2307
2308 void *InsertPos = 0;
2309 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2310 if (T)
2311 return QualType(T, 0);
2312
2313 QualType Canon = InnerType;
2314 if (!Canon.isCanonical()) {
2315 Canon = getCanonicalType(InnerType);
2316 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2317 assert(!CheckT && "Paren canonical type broken");
2318 (void)CheckT;
2319 }
2320
2321 T = new (*this) ParenType(InnerType, Canon);
2322 Types.push_back(T);
2323 ParenTypes.InsertNode(T, InsertPos);
2324 return QualType(T, 0);
2325}
2326
Douglas Gregor02085352010-03-31 20:19:30 +00002327QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2328 NestedNameSpecifier *NNS,
2329 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002330 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002331 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2332
2333 if (Canon.isNull()) {
2334 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002335 ElaboratedTypeKeyword CanonKeyword = Keyword;
2336 if (Keyword == ETK_None)
2337 CanonKeyword = ETK_Typename;
2338
2339 if (CanonNNS != NNS || CanonKeyword != Keyword)
2340 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002341 }
2342
2343 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002344 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002345
2346 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002347 DependentNameType *T
2348 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002349 if (T)
2350 return QualType(T, 0);
2351
Douglas Gregor02085352010-03-31 20:19:30 +00002352 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002353 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002354 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002355 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002356}
2357
Mike Stump11289f42009-09-09 15:08:12 +00002358QualType
John McCallc392f372010-06-11 00:33:02 +00002359ASTContext::getDependentTemplateSpecializationType(
2360 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002361 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002362 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002363 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002364 // TODO: avoid this copy
2365 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2366 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2367 ArgCopy.push_back(Args[I].getArgument());
2368 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2369 ArgCopy.size(),
2370 ArgCopy.data());
2371}
2372
2373QualType
2374ASTContext::getDependentTemplateSpecializationType(
2375 ElaboratedTypeKeyword Keyword,
2376 NestedNameSpecifier *NNS,
2377 const IdentifierInfo *Name,
2378 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002379 const TemplateArgument *Args) const {
Douglas Gregordce2b622009-04-01 00:28:59 +00002380 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2381
Douglas Gregorc42075a2010-02-04 18:10:26 +00002382 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002383 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2384 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002385
2386 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002387 DependentTemplateSpecializationType *T
2388 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002389 if (T)
2390 return QualType(T, 0);
2391
John McCallc392f372010-06-11 00:33:02 +00002392 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002393
John McCallc392f372010-06-11 00:33:02 +00002394 ElaboratedTypeKeyword CanonKeyword = Keyword;
2395 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2396
2397 bool AnyNonCanonArgs = false;
2398 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2399 for (unsigned I = 0; I != NumArgs; ++I) {
2400 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2401 if (!CanonArgs[I].structurallyEquals(Args[I]))
2402 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002403 }
2404
John McCallc392f372010-06-11 00:33:02 +00002405 QualType Canon;
2406 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2407 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2408 Name, NumArgs,
2409 CanonArgs.data());
2410
2411 // Find the insert position again.
2412 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2413 }
2414
2415 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2416 sizeof(TemplateArgument) * NumArgs),
2417 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002418 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002419 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002420 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002421 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002422 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002423}
2424
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002425QualType ASTContext::getPackExpansionType(QualType Pattern,
2426 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002427 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002428 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002429
2430 assert(Pattern->containsUnexpandedParameterPack() &&
2431 "Pack expansions must expand one or more parameter packs");
2432 void *InsertPos = 0;
2433 PackExpansionType *T
2434 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2435 if (T)
2436 return QualType(T, 0);
2437
2438 QualType Canon;
2439 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002440 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002441
2442 // Find the insert position again.
2443 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2444 }
2445
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002446 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002447 Types.push_back(T);
2448 PackExpansionTypes.InsertNode(T, InsertPos);
2449 return QualType(T, 0);
2450}
2451
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002452/// CmpProtocolNames - Comparison predicate for sorting protocols
2453/// alphabetically.
2454static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2455 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002456 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002457}
2458
John McCall8b07ec22010-05-15 11:32:37 +00002459static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002460 unsigned NumProtocols) {
2461 if (NumProtocols == 0) return true;
2462
2463 for (unsigned i = 1; i != NumProtocols; ++i)
2464 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2465 return false;
2466 return true;
2467}
2468
2469static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002470 unsigned &NumProtocols) {
2471 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002472
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002473 // Sort protocols, keyed by name.
2474 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2475
2476 // Remove duplicates.
2477 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2478 NumProtocols = ProtocolsEnd-Protocols;
2479}
2480
John McCall8b07ec22010-05-15 11:32:37 +00002481QualType ASTContext::getObjCObjectType(QualType BaseType,
2482 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002483 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002484 // If the base type is an interface and there aren't any protocols
2485 // to add, then the interface type will do just fine.
2486 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2487 return BaseType;
2488
2489 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002490 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002491 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002492 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002493 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2494 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002495
John McCall8b07ec22010-05-15 11:32:37 +00002496 // Build the canonical type, which has the canonical base type and
2497 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002498 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002499 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2500 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2501 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002502 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2503 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002504 unsigned UniqueCount = NumProtocols;
2505
John McCallfc93cf92009-10-22 22:37:11 +00002506 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002507 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2508 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002509 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002510 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2511 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002512 }
2513
2514 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002515 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2516 }
2517
2518 unsigned Size = sizeof(ObjCObjectTypeImpl);
2519 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2520 void *Mem = Allocate(Size, TypeAlignment);
2521 ObjCObjectTypeImpl *T =
2522 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2523
2524 Types.push_back(T);
2525 ObjCObjectTypes.InsertNode(T, InsertPos);
2526 return QualType(T, 0);
2527}
2528
2529/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2530/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002531QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002532 llvm::FoldingSetNodeID ID;
2533 ObjCObjectPointerType::Profile(ID, ObjectT);
2534
2535 void *InsertPos = 0;
2536 if (ObjCObjectPointerType *QT =
2537 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2538 return QualType(QT, 0);
2539
2540 // Find the canonical object type.
2541 QualType Canonical;
2542 if (!ObjectT.isCanonical()) {
2543 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2544
2545 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002546 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2547 }
2548
Douglas Gregorf85bee62010-02-08 22:59:26 +00002549 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002550 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2551 ObjCObjectPointerType *QType =
2552 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002553
Steve Narofffb4330f2009-06-17 22:40:22 +00002554 Types.push_back(QType);
2555 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002556 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002557}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002558
Douglas Gregor1c283312010-08-11 12:19:30 +00002559/// getObjCInterfaceType - Return the unique reference to the type for the
2560/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002561QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002562 if (Decl->TypeForDecl)
2563 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002564
Douglas Gregor1c283312010-08-11 12:19:30 +00002565 // FIXME: redeclarations?
2566 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2567 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2568 Decl->TypeForDecl = T;
2569 Types.push_back(T);
2570 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002571}
2572
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002573/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2574/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002575/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002576/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002577/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002578QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002579 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002580 if (tofExpr->isTypeDependent()) {
2581 llvm::FoldingSetNodeID ID;
2582 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002583
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002584 void *InsertPos = 0;
2585 DependentTypeOfExprType *Canon
2586 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2587 if (Canon) {
2588 // We already have a "canonical" version of an identical, dependent
2589 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002590 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002591 QualType((TypeOfExprType*)Canon, 0));
2592 }
2593 else {
2594 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002595 Canon
2596 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002597 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2598 toe = Canon;
2599 }
2600 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002601 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002602 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002603 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002604 Types.push_back(toe);
2605 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002606}
2607
Steve Naroffa773cd52007-08-01 18:02:17 +00002608/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2609/// TypeOfType AST's. The only motivation to unique these nodes would be
2610/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002611/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002612/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002613QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002614 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002615 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002616 Types.push_back(tot);
2617 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002618}
2619
Anders Carlssonad6bd352009-06-24 21:24:56 +00002620/// getDecltypeForExpr - Given an expr, will return the decltype for that
2621/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002622static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002623 if (e->isTypeDependent())
2624 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002625
Anders Carlssonad6bd352009-06-24 21:24:56 +00002626 // If e is an id expression or a class member access, decltype(e) is defined
2627 // as the type of the entity named by e.
2628 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2629 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2630 return VD->getType();
2631 }
2632 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2633 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2634 return FD->getType();
2635 }
2636 // If e is a function call or an invocation of an overloaded operator,
2637 // (parentheses around e are ignored), decltype(e) is defined as the
2638 // return type of that function.
2639 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2640 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002641
Anders Carlssonad6bd352009-06-24 21:24:56 +00002642 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002643
2644 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002645 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002646 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002647 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002648
Anders Carlssonad6bd352009-06-24 21:24:56 +00002649 return T;
2650}
2651
Anders Carlsson81df7b82009-06-24 19:06:50 +00002652/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2653/// DecltypeType AST's. The only motivation to unique these nodes would be
2654/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002655/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002656/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002657QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002658 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002659 if (e->isTypeDependent()) {
2660 llvm::FoldingSetNodeID ID;
2661 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002662
Douglas Gregora21f6c32009-07-30 23:36:40 +00002663 void *InsertPos = 0;
2664 DependentDecltypeType *Canon
2665 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2666 if (Canon) {
2667 // We already have a "canonical" version of an equivalent, dependent
2668 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002669 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002670 QualType((DecltypeType*)Canon, 0));
2671 }
2672 else {
2673 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002674 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002675 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2676 dt = Canon;
2677 }
2678 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002679 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002680 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002681 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002682 Types.push_back(dt);
2683 return QualType(dt, 0);
2684}
2685
Richard Smithb2bc2e62011-02-21 20:05:19 +00002686/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002687QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002688 void *InsertPos = 0;
2689 if (!DeducedType.isNull()) {
2690 // Look in the folding set for an existing type.
2691 llvm::FoldingSetNodeID ID;
2692 AutoType::Profile(ID, DeducedType);
2693 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2694 return QualType(AT, 0);
2695 }
2696
2697 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2698 Types.push_back(AT);
2699 if (InsertPos)
2700 AutoTypes.InsertNode(AT, InsertPos);
2701 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002702}
2703
Chris Lattnerfb072462007-01-23 05:45:31 +00002704/// getTagDeclType - Return the unique reference to the type for the
2705/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002706QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002707 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002708 // FIXME: What is the design on getTagDeclType when it requires casting
2709 // away const? mutable?
2710 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002711}
2712
Mike Stump11289f42009-09-09 15:08:12 +00002713/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2714/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2715/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002716CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002717 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002718}
Chris Lattnerfb072462007-01-23 05:45:31 +00002719
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002720/// getSignedWCharType - Return the type of "signed wchar_t".
2721/// Used when in C++, as a GCC extension.
2722QualType ASTContext::getSignedWCharType() const {
2723 // FIXME: derive from "Target" ?
2724 return WCharTy;
2725}
2726
2727/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2728/// Used when in C++, as a GCC extension.
2729QualType ASTContext::getUnsignedWCharType() const {
2730 // FIXME: derive from "Target" ?
2731 return UnsignedIntTy;
2732}
2733
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002734/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2735/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2736QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002737 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002738}
2739
Chris Lattnera21ad802008-04-02 05:18:44 +00002740//===----------------------------------------------------------------------===//
2741// Type Operators
2742//===----------------------------------------------------------------------===//
2743
Jay Foad39c79802011-01-12 09:06:06 +00002744CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002745 // Push qualifiers into arrays, and then discard any remaining
2746 // qualifiers.
2747 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002748 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002749 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002750 QualType Result;
2751 if (isa<ArrayType>(Ty)) {
2752 Result = getArrayDecayedType(QualType(Ty,0));
2753 } else if (isa<FunctionType>(Ty)) {
2754 Result = getPointerType(QualType(Ty, 0));
2755 } else {
2756 Result = QualType(Ty, 0);
2757 }
2758
2759 return CanQualType::CreateUnsafe(Result);
2760}
2761
Chris Lattner7adf0762008-08-04 07:31:14 +00002762
John McCall6c9dd522011-01-18 07:41:22 +00002763QualType ASTContext::getUnqualifiedArrayType(QualType type,
2764 Qualifiers &quals) {
2765 SplitQualType splitType = type.getSplitUnqualifiedType();
2766
2767 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2768 // the unqualified desugared type and then drops it on the floor.
2769 // We then have to strip that sugar back off with
2770 // getUnqualifiedDesugaredType(), which is silly.
2771 const ArrayType *AT =
2772 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2773
2774 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002775 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002776 quals = splitType.second;
2777 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002778 }
2779
John McCall6c9dd522011-01-18 07:41:22 +00002780 // Otherwise, recurse on the array's element type.
2781 QualType elementType = AT->getElementType();
2782 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2783
2784 // If that didn't change the element type, AT has no qualifiers, so we
2785 // can just use the results in splitType.
2786 if (elementType == unqualElementType) {
2787 assert(quals.empty()); // from the recursive call
2788 quals = splitType.second;
2789 return QualType(splitType.first, 0);
2790 }
2791
2792 // Otherwise, add in the qualifiers from the outermost type, then
2793 // build the type back up.
2794 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002795
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002796 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002797 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002798 CAT->getSizeModifier(), 0);
2799 }
2800
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002801 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002802 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002803 }
2804
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002805 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002806 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002807 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002808 VAT->getSizeModifier(),
2809 VAT->getIndexTypeCVRQualifiers(),
2810 VAT->getBracketsRange());
2811 }
2812
2813 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002814 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002815 DSAT->getSizeModifier(), 0,
2816 SourceRange());
2817}
2818
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002819/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2820/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2821/// they point to and return true. If T1 and T2 aren't pointer types
2822/// or pointer-to-member types, or if they are not similar at this
2823/// level, returns false and leaves T1 and T2 unchanged. Top-level
2824/// qualifiers on T1 and T2 are ignored. This function will typically
2825/// be called in a loop that successively "unwraps" pointer and
2826/// pointer-to-member types to compare them at each level.
2827bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2828 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2829 *T2PtrType = T2->getAs<PointerType>();
2830 if (T1PtrType && T2PtrType) {
2831 T1 = T1PtrType->getPointeeType();
2832 T2 = T2PtrType->getPointeeType();
2833 return true;
2834 }
2835
2836 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2837 *T2MPType = T2->getAs<MemberPointerType>();
2838 if (T1MPType && T2MPType &&
2839 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2840 QualType(T2MPType->getClass(), 0))) {
2841 T1 = T1MPType->getPointeeType();
2842 T2 = T2MPType->getPointeeType();
2843 return true;
2844 }
2845
2846 if (getLangOptions().ObjC1) {
2847 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2848 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2849 if (T1OPType && T2OPType) {
2850 T1 = T1OPType->getPointeeType();
2851 T2 = T2OPType->getPointeeType();
2852 return true;
2853 }
2854 }
2855
2856 // FIXME: Block pointers, too?
2857
2858 return false;
2859}
2860
Jay Foad39c79802011-01-12 09:06:06 +00002861DeclarationNameInfo
2862ASTContext::getNameForTemplate(TemplateName Name,
2863 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002864 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002865 // DNInfo work in progress: CHECKME: what about DNLoc?
2866 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2867
John McCall847e2a12009-11-24 18:42:40 +00002868 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002869 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002870 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002871 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2872 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002873 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002874 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2875 // DNInfo work in progress: FIXME: source locations?
2876 DeclarationNameLoc DNLoc;
2877 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2878 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2879 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002880 }
2881 }
2882
John McCalld28ae272009-12-02 08:04:21 +00002883 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2884 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002885 // DNInfo work in progress: CHECKME: what about DNLoc?
2886 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002887}
2888
Jay Foad39c79802011-01-12 09:06:06 +00002889TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002890 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2891 if (TemplateTemplateParmDecl *TTP
2892 = dyn_cast<TemplateTemplateParmDecl>(Template))
2893 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2894
2895 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002896 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002897 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002898
Douglas Gregor5590be02011-01-15 06:45:20 +00002899 if (SubstTemplateTemplateParmPackStorage *SubstPack
2900 = Name.getAsSubstTemplateTemplateParmPack()) {
2901 TemplateTemplateParmDecl *CanonParam
2902 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2903 TemplateArgument CanonArgPack
2904 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2905 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2906 }
2907
John McCalld28ae272009-12-02 08:04:21 +00002908 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002909
Douglas Gregor6bc50582009-05-07 06:41:52 +00002910 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2911 assert(DTN && "Non-dependent template names must refer to template decls.");
2912 return DTN->CanonicalTemplateName;
2913}
2914
Douglas Gregoradee3e32009-11-11 23:06:43 +00002915bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2916 X = getCanonicalTemplateName(X);
2917 Y = getCanonicalTemplateName(Y);
2918 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2919}
2920
Mike Stump11289f42009-09-09 15:08:12 +00002921TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00002922ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00002923 switch (Arg.getKind()) {
2924 case TemplateArgument::Null:
2925 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002926
Douglas Gregora8e02e72009-07-28 23:00:59 +00002927 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002928 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002929
Douglas Gregora8e02e72009-07-28 23:00:59 +00002930 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002931 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002932
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002933 case TemplateArgument::Template:
2934 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002935
2936 case TemplateArgument::TemplateExpansion:
2937 return TemplateArgument(getCanonicalTemplateName(
2938 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00002939 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002940
Douglas Gregora8e02e72009-07-28 23:00:59 +00002941 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002942 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002943 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002944
Douglas Gregora8e02e72009-07-28 23:00:59 +00002945 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002946 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002947
Douglas Gregora8e02e72009-07-28 23:00:59 +00002948 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00002949 if (Arg.pack_size() == 0)
2950 return Arg;
2951
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002952 TemplateArgument *CanonArgs
2953 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00002954 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002955 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002956 AEnd = Arg.pack_end();
2957 A != AEnd; (void)++A, ++Idx)
2958 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002959
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002960 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00002961 }
2962 }
2963
2964 // Silence GCC warning
2965 assert(false && "Unhandled template argument kind");
2966 return TemplateArgument();
2967}
2968
Douglas Gregor333489b2009-03-27 23:10:48 +00002969NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00002970ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00002971 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002972 return 0;
2973
2974 switch (NNS->getKind()) {
2975 case NestedNameSpecifier::Identifier:
2976 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002977 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002978 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2979 NNS->getAsIdentifier());
2980
2981 case NestedNameSpecifier::Namespace:
2982 // A namespace is canonical; build a nested-name-specifier with
2983 // this namespace and no prefix.
2984 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2985
2986 case NestedNameSpecifier::TypeSpec:
2987 case NestedNameSpecifier::TypeSpecWithTemplate: {
2988 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00002989
2990 // If we have some kind of dependent-named type (e.g., "typename T::type"),
2991 // break it apart into its prefix and identifier, then reconsititute those
2992 // as the canonical nested-name-specifier. This is required to canonicalize
2993 // a dependent nested-name-specifier involving typedefs of dependent-name
2994 // types, e.g.,
2995 // typedef typename T::type T1;
2996 // typedef typename T1::type T2;
2997 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
2998 NestedNameSpecifier *Prefix
2999 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3000 return NestedNameSpecifier::Create(*this, Prefix,
3001 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3002 }
3003
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003004 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003005 if (const DependentTemplateSpecializationType *DTST
3006 = T->getAs<DependentTemplateSpecializationType>()) {
3007 NestedNameSpecifier *Prefix
3008 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
3009 TemplateName Name
3010 = getDependentTemplateName(Prefix, DTST->getIdentifier());
3011 T = getTemplateSpecializationType(Name,
3012 DTST->getArgs(), DTST->getNumArgs());
3013 T = getCanonicalType(T);
3014 }
3015
John McCall33ddac02011-01-19 10:06:00 +00003016 return NestedNameSpecifier::Create(*this, 0, false,
3017 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003018 }
3019
3020 case NestedNameSpecifier::Global:
3021 // The global specifier is canonical and unique.
3022 return NNS;
3023 }
3024
3025 // Required to silence a GCC warning
3026 return 0;
3027}
3028
Chris Lattner7adf0762008-08-04 07:31:14 +00003029
Jay Foad39c79802011-01-12 09:06:06 +00003030const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003031 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003032 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003033 // Handle the common positive case fast.
3034 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3035 return AT;
3036 }
Mike Stump11289f42009-09-09 15:08:12 +00003037
John McCall8ccfcb52009-09-24 19:53:00 +00003038 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003039 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003040 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003041
John McCall8ccfcb52009-09-24 19:53:00 +00003042 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003043 // implements C99 6.7.3p8: "If the specification of an array type includes
3044 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003045
Chris Lattner7adf0762008-08-04 07:31:14 +00003046 // If we get here, we either have type qualifiers on the type, or we have
3047 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003048 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003049
John McCall33ddac02011-01-19 10:06:00 +00003050 SplitQualType split = T.getSplitDesugaredType();
3051 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003052
Chris Lattner7adf0762008-08-04 07:31:14 +00003053 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003054 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3055 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003056 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003057
Chris Lattner7adf0762008-08-04 07:31:14 +00003058 // Otherwise, we have an array and we have qualifiers on it. Push the
3059 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003060 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003061
Chris Lattner7adf0762008-08-04 07:31:14 +00003062 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3063 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3064 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003065 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003066 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3067 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3068 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003069 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003070
Mike Stump11289f42009-09-09 15:08:12 +00003071 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003072 = dyn_cast<DependentSizedArrayType>(ATy))
3073 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003074 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003075 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003076 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003077 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003078 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003079
Chris Lattner7adf0762008-08-04 07:31:14 +00003080 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003081 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003082 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003083 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003084 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003085 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003086}
3087
Chris Lattnera21ad802008-04-02 05:18:44 +00003088/// getArrayDecayedType - Return the properly qualified result of decaying the
3089/// specified array type to a pointer. This operation is non-trivial when
3090/// handling typedefs etc. The canonical type of "T" must be an array type,
3091/// this returns a pointer to a properly qualified element of the array.
3092///
3093/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003094QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003095 // Get the element type with 'getAsArrayType' so that we don't lose any
3096 // typedefs in the element type of the array. This also handles propagation
3097 // of type qualifiers from the array type into the element type if present
3098 // (C99 6.7.3p8).
3099 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3100 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003101
Chris Lattner7adf0762008-08-04 07:31:14 +00003102 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003103
3104 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003105 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003106}
3107
John McCall33ddac02011-01-19 10:06:00 +00003108QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3109 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003110}
3111
John McCall33ddac02011-01-19 10:06:00 +00003112QualType ASTContext::getBaseElementType(QualType type) const {
3113 Qualifiers qs;
3114 while (true) {
3115 SplitQualType split = type.getSplitDesugaredType();
3116 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3117 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003118
John McCall33ddac02011-01-19 10:06:00 +00003119 type = array->getElementType();
3120 qs.addConsistentQualifiers(split.second);
3121 }
Mike Stump11289f42009-09-09 15:08:12 +00003122
John McCall33ddac02011-01-19 10:06:00 +00003123 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003124}
3125
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003126/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003127uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003128ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3129 uint64_t ElementCount = 1;
3130 do {
3131 ElementCount *= CA->getSize().getZExtValue();
3132 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3133 } while (CA);
3134 return ElementCount;
3135}
3136
Steve Naroff0af91202007-04-27 21:51:21 +00003137/// getFloatingRank - Return a relative rank for floating point types.
3138/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003139static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003140 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003141 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003142
John McCall9dd450b2009-09-21 23:43:11 +00003143 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3144 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003145 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003146 case BuiltinType::Float: return FloatRank;
3147 case BuiltinType::Double: return DoubleRank;
3148 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003149 }
3150}
3151
Mike Stump11289f42009-09-09 15:08:12 +00003152/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3153/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003154/// 'typeDomain' is a real floating point or complex type.
3155/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003156QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3157 QualType Domain) const {
3158 FloatingRank EltRank = getFloatingRank(Size);
3159 if (Domain->isComplexType()) {
3160 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003161 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003162 case FloatRank: return FloatComplexTy;
3163 case DoubleRank: return DoubleComplexTy;
3164 case LongDoubleRank: return LongDoubleComplexTy;
3165 }
Steve Naroff0af91202007-04-27 21:51:21 +00003166 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003167
3168 assert(Domain->isRealFloatingType() && "Unknown domain!");
3169 switch (EltRank) {
3170 default: assert(0 && "getFloatingRank(): illegal value for rank");
3171 case FloatRank: return FloatTy;
3172 case DoubleRank: return DoubleTy;
3173 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003174 }
Steve Naroffe4718892007-04-27 18:30:00 +00003175}
3176
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003177/// getFloatingTypeOrder - Compare the rank of the two specified floating
3178/// point types, ignoring the domain of the type (i.e. 'double' ==
3179/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003180/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003181int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003182 FloatingRank LHSR = getFloatingRank(LHS);
3183 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003184
Chris Lattnerb90739d2008-04-06 23:38:49 +00003185 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003186 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003187 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003188 return 1;
3189 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003190}
3191
Chris Lattner76a00cf2008-04-06 22:59:24 +00003192/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3193/// routine will assert if passed a built-in type that isn't an integer or enum,
3194/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003195unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003196 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003197 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003198 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003199
Chris Lattnerad3467e2010-12-25 23:25:43 +00003200 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3201 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003202 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3203
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003204 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3205 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3206
3207 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3208 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3209
Chris Lattner76a00cf2008-04-06 22:59:24 +00003210 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003211 default: assert(0 && "getIntegerRank(): not a built-in integer");
3212 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003213 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003214 case BuiltinType::Char_S:
3215 case BuiltinType::Char_U:
3216 case BuiltinType::SChar:
3217 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003218 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003219 case BuiltinType::Short:
3220 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003221 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003222 case BuiltinType::Int:
3223 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003224 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003225 case BuiltinType::Long:
3226 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003227 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003228 case BuiltinType::LongLong:
3229 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003230 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003231 case BuiltinType::Int128:
3232 case BuiltinType::UInt128:
3233 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003234 }
3235}
3236
Eli Friedman629ffb92009-08-20 04:21:42 +00003237/// \brief Whether this is a promotable bitfield reference according
3238/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3239///
3240/// \returns the type this bit-field will promote to, or NULL if no
3241/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003242QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003243 if (E->isTypeDependent() || E->isValueDependent())
3244 return QualType();
3245
Eli Friedman629ffb92009-08-20 04:21:42 +00003246 FieldDecl *Field = E->getBitField();
3247 if (!Field)
3248 return QualType();
3249
3250 QualType FT = Field->getType();
3251
3252 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3253 uint64_t BitWidth = BitWidthAP.getZExtValue();
3254 uint64_t IntSize = getTypeSize(IntTy);
3255 // GCC extension compatibility: if the bit-field size is less than or equal
3256 // to the size of int, it gets promoted no matter what its type is.
3257 // For instance, unsigned long bf : 4 gets promoted to signed int.
3258 if (BitWidth < IntSize)
3259 return IntTy;
3260
3261 if (BitWidth == IntSize)
3262 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3263
3264 // Types bigger than int are not subject to promotions, and therefore act
3265 // like the base type.
3266 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3267 // is ridiculous.
3268 return QualType();
3269}
3270
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003271/// getPromotedIntegerType - Returns the type that Promotable will
3272/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3273/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003274QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003275 assert(!Promotable.isNull());
3276 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003277 if (const EnumType *ET = Promotable->getAs<EnumType>())
3278 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003279 if (Promotable->isSignedIntegerType())
3280 return IntTy;
3281 uint64_t PromotableSize = getTypeSize(Promotable);
3282 uint64_t IntSize = getTypeSize(IntTy);
3283 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3284 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3285}
3286
Mike Stump11289f42009-09-09 15:08:12 +00003287/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003288/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003289/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003290int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003291 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3292 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003293 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003294
Chris Lattner76a00cf2008-04-06 22:59:24 +00003295 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3296 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003297
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003298 unsigned LHSRank = getIntegerRank(LHSC);
3299 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003300
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003301 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3302 if (LHSRank == RHSRank) return 0;
3303 return LHSRank > RHSRank ? 1 : -1;
3304 }
Mike Stump11289f42009-09-09 15:08:12 +00003305
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003306 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3307 if (LHSUnsigned) {
3308 // If the unsigned [LHS] type is larger, return it.
3309 if (LHSRank >= RHSRank)
3310 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003311
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003312 // If the signed type can represent all values of the unsigned type, it
3313 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003314 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003315 return -1;
3316 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003317
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003318 // If the unsigned [RHS] type is larger, return it.
3319 if (RHSRank >= LHSRank)
3320 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003321
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003322 // If the signed type can represent all values of the unsigned type, it
3323 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003324 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003325 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003326}
Anders Carlsson98f07902007-08-17 05:31:46 +00003327
Anders Carlsson6d417272009-11-14 21:45:58 +00003328static RecordDecl *
Jay Foad39c79802011-01-12 09:06:06 +00003329CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
Anders Carlsson6d417272009-11-14 21:45:58 +00003330 SourceLocation L, IdentifierInfo *Id) {
3331 if (Ctx.getLangOptions().CPlusPlus)
3332 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3333 else
3334 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3335}
3336
Mike Stump11289f42009-09-09 15:08:12 +00003337// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003338QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003339 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003340 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003341 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003342 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003343 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003344
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003345 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003346
Anders Carlsson98f07902007-08-17 05:31:46 +00003347 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003348 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003349 // int flags;
3350 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003351 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003352 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003353 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003354 FieldTypes[3] = LongTy;
3355
Anders Carlsson98f07902007-08-17 05:31:46 +00003356 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003357 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003358 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003359 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003360 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003361 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003362 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003363 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003364 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003365 }
3366
Douglas Gregord5058122010-02-11 01:19:42 +00003367 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003368 }
Mike Stump11289f42009-09-09 15:08:12 +00003369
Anders Carlsson98f07902007-08-17 05:31:46 +00003370 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003371}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003372
Douglas Gregor512b0772009-04-23 22:29:11 +00003373void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003374 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003375 assert(Rec && "Invalid CFConstantStringType");
3376 CFConstantStringTypeDecl = Rec->getDecl();
3377}
3378
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003379// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003380QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003381 if (!NSConstantStringTypeDecl) {
3382 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003383 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003384 &Idents.get("__builtin_NSString"));
3385 NSConstantStringTypeDecl->startDefinition();
3386
3387 QualType FieldTypes[3];
3388
3389 // const int *isa;
3390 FieldTypes[0] = getPointerType(IntTy.withConst());
3391 // const char *str;
3392 FieldTypes[1] = getPointerType(CharTy.withConst());
3393 // unsigned int length;
3394 FieldTypes[2] = UnsignedIntTy;
3395
3396 // Create fields
3397 for (unsigned i = 0; i < 3; ++i) {
3398 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3399 SourceLocation(), 0,
3400 FieldTypes[i], /*TInfo=*/0,
3401 /*BitWidth=*/0,
3402 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003403 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003404 NSConstantStringTypeDecl->addDecl(Field);
3405 }
3406
3407 NSConstantStringTypeDecl->completeDefinition();
3408 }
3409
3410 return getTagDeclType(NSConstantStringTypeDecl);
3411}
3412
3413void ASTContext::setNSConstantStringType(QualType T) {
3414 const RecordType *Rec = T->getAs<RecordType>();
3415 assert(Rec && "Invalid NSConstantStringType");
3416 NSConstantStringTypeDecl = Rec->getDecl();
3417}
3418
Jay Foad39c79802011-01-12 09:06:06 +00003419QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003420 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003421 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003422 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003423 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003424 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003425
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003426 QualType FieldTypes[] = {
3427 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003428 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003429 getPointerType(UnsignedLongTy),
3430 getConstantArrayType(UnsignedLongTy,
3431 llvm::APInt(32, 5), ArrayType::Normal, 0)
3432 };
Mike Stump11289f42009-09-09 15:08:12 +00003433
Douglas Gregor91f84212008-12-11 16:49:14 +00003434 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003435 FieldDecl *Field = FieldDecl::Create(*this,
3436 ObjCFastEnumerationStateTypeDecl,
3437 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003438 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003439 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003440 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003441 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003442 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003443 }
Mike Stump11289f42009-09-09 15:08:12 +00003444
Douglas Gregord5058122010-02-11 01:19:42 +00003445 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003446 }
Mike Stump11289f42009-09-09 15:08:12 +00003447
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003448 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3449}
3450
Jay Foad39c79802011-01-12 09:06:06 +00003451QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003452 if (BlockDescriptorType)
3453 return getTagDeclType(BlockDescriptorType);
3454
3455 RecordDecl *T;
3456 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003457 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003458 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003459 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003460
3461 QualType FieldTypes[] = {
3462 UnsignedLongTy,
3463 UnsignedLongTy,
3464 };
3465
3466 const char *FieldNames[] = {
3467 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003468 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003469 };
3470
3471 for (size_t i = 0; i < 2; ++i) {
3472 FieldDecl *Field = FieldDecl::Create(*this,
3473 T,
3474 SourceLocation(),
3475 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003476 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003477 /*BitWidth=*/0,
3478 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003479 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003480 T->addDecl(Field);
3481 }
3482
Douglas Gregord5058122010-02-11 01:19:42 +00003483 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003484
3485 BlockDescriptorType = T;
3486
3487 return getTagDeclType(BlockDescriptorType);
3488}
3489
3490void ASTContext::setBlockDescriptorType(QualType T) {
3491 const RecordType *Rec = T->getAs<RecordType>();
3492 assert(Rec && "Invalid BlockDescriptorType");
3493 BlockDescriptorType = Rec->getDecl();
3494}
3495
Jay Foad39c79802011-01-12 09:06:06 +00003496QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003497 if (BlockDescriptorExtendedType)
3498 return getTagDeclType(BlockDescriptorExtendedType);
3499
3500 RecordDecl *T;
3501 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003502 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003503 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003504 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003505
3506 QualType FieldTypes[] = {
3507 UnsignedLongTy,
3508 UnsignedLongTy,
3509 getPointerType(VoidPtrTy),
3510 getPointerType(VoidPtrTy)
3511 };
3512
3513 const char *FieldNames[] = {
3514 "reserved",
3515 "Size",
3516 "CopyFuncPtr",
3517 "DestroyFuncPtr"
3518 };
3519
3520 for (size_t i = 0; i < 4; ++i) {
3521 FieldDecl *Field = FieldDecl::Create(*this,
3522 T,
3523 SourceLocation(),
3524 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003525 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003526 /*BitWidth=*/0,
3527 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003528 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003529 T->addDecl(Field);
3530 }
3531
Douglas Gregord5058122010-02-11 01:19:42 +00003532 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003533
3534 BlockDescriptorExtendedType = T;
3535
3536 return getTagDeclType(BlockDescriptorExtendedType);
3537}
3538
3539void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3540 const RecordType *Rec = T->getAs<RecordType>();
3541 assert(Rec && "Invalid BlockDescriptorType");
3542 BlockDescriptorExtendedType = Rec->getDecl();
3543}
3544
Jay Foad39c79802011-01-12 09:06:06 +00003545bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003546 if (Ty->isBlockPointerType())
3547 return true;
3548 if (isObjCNSObjectType(Ty))
3549 return true;
3550 if (Ty->isObjCObjectPointerType())
3551 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003552 if (getLangOptions().CPlusPlus) {
3553 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3554 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3555 return RD->hasConstCopyConstructor(*this);
3556
3557 }
3558 }
Mike Stump94967902009-10-21 18:16:27 +00003559 return false;
3560}
3561
Jay Foad39c79802011-01-12 09:06:06 +00003562QualType
3563ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003564 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003565 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003566 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003567 // unsigned int __flags;
3568 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003569 // void *__copy_helper; // as needed
3570 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003571 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003572 // } *
3573
Mike Stump94967902009-10-21 18:16:27 +00003574 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3575
3576 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003577 llvm::SmallString<36> Name;
3578 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3579 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003580 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003581 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003582 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003583 T->startDefinition();
3584 QualType Int32Ty = IntTy;
3585 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3586 QualType FieldTypes[] = {
3587 getPointerType(VoidPtrTy),
3588 getPointerType(getTagDeclType(T)),
3589 Int32Ty,
3590 Int32Ty,
3591 getPointerType(VoidPtrTy),
3592 getPointerType(VoidPtrTy),
3593 Ty
3594 };
3595
Daniel Dunbar56df9772010-08-17 22:39:59 +00003596 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003597 "__isa",
3598 "__forwarding",
3599 "__flags",
3600 "__size",
3601 "__copy_helper",
3602 "__destroy_helper",
3603 DeclName,
3604 };
3605
3606 for (size_t i = 0; i < 7; ++i) {
3607 if (!HasCopyAndDispose && i >=4 && i <= 5)
3608 continue;
3609 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3610 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003611 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003612 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003613 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003614 T->addDecl(Field);
3615 }
3616
Douglas Gregord5058122010-02-11 01:19:42 +00003617 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003618
3619 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003620}
3621
Douglas Gregor512b0772009-04-23 22:29:11 +00003622void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003623 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003624 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3625 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3626}
3627
Anders Carlsson18acd442007-10-29 06:33:42 +00003628// This returns true if a type has been typedefed to BOOL:
3629// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003630static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003631 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003632 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3633 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003634
Anders Carlssond8499822007-10-29 05:01:08 +00003635 return false;
3636}
3637
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003638/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003639/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003640CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003641 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003642
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003643 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003644 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003645 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003646 // Treat arrays as pointers, since that's how they're passed in.
3647 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003648 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003649 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003650}
3651
3652static inline
3653std::string charUnitsToString(const CharUnits &CU) {
3654 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003655}
3656
John McCall351762c2011-02-07 10:33:21 +00003657/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003658/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003659std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3660 std::string S;
3661
David Chisnall950a9512009-11-17 19:33:30 +00003662 const BlockDecl *Decl = Expr->getBlockDecl();
3663 QualType BlockTy =
3664 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3665 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003666 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003667 // Compute size of all parameters.
3668 // Start with computing size of a pointer in number of bytes.
3669 // FIXME: There might(should) be a better way of doing this computation!
3670 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003671 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3672 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003673 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003674 E = Decl->param_end(); PI != E; ++PI) {
3675 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003676 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003677 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003678 ParmOffset += sz;
3679 }
3680 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003681 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003682 // Block pointer and offset.
3683 S += "@?0";
3684 ParmOffset = PtrSize;
3685
3686 // Argument types.
3687 ParmOffset = PtrSize;
3688 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3689 Decl->param_end(); PI != E; ++PI) {
3690 ParmVarDecl *PVDecl = *PI;
3691 QualType PType = PVDecl->getOriginalType();
3692 if (const ArrayType *AT =
3693 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3694 // Use array's original type only if it has known number of
3695 // elements.
3696 if (!isa<ConstantArrayType>(AT))
3697 PType = PVDecl->getType();
3698 } else if (PType->isFunctionType())
3699 PType = PVDecl->getType();
3700 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003701 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003702 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003703 }
John McCall351762c2011-02-07 10:33:21 +00003704
3705 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003706}
3707
David Chisnall50e4eba2010-12-30 14:05:53 +00003708void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3709 std::string& S) {
3710 // Encode result type.
3711 getObjCEncodingForType(Decl->getResultType(), S);
3712 CharUnits ParmOffset;
3713 // Compute size of all parameters.
3714 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3715 E = Decl->param_end(); PI != E; ++PI) {
3716 QualType PType = (*PI)->getType();
3717 CharUnits sz = getObjCEncodingTypeSize(PType);
3718 assert (sz.isPositive() &&
3719 "getObjCEncodingForMethodDecl - Incomplete param type");
3720 ParmOffset += sz;
3721 }
3722 S += charUnitsToString(ParmOffset);
3723 ParmOffset = CharUnits::Zero();
3724
3725 // Argument types.
3726 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3727 E = Decl->param_end(); PI != E; ++PI) {
3728 ParmVarDecl *PVDecl = *PI;
3729 QualType PType = PVDecl->getOriginalType();
3730 if (const ArrayType *AT =
3731 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3732 // Use array's original type only if it has known number of
3733 // elements.
3734 if (!isa<ConstantArrayType>(AT))
3735 PType = PVDecl->getType();
3736 } else if (PType->isFunctionType())
3737 PType = PVDecl->getType();
3738 getObjCEncodingForType(PType, S);
3739 S += charUnitsToString(ParmOffset);
3740 ParmOffset += getObjCEncodingTypeSize(PType);
3741 }
3742}
3743
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003744/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003745/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003746void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003747 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003748 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003749 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003750 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003751 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003752 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003753 // Compute size of all parameters.
3754 // Start with computing size of a pointer in number of bytes.
3755 // FIXME: There might(should) be a better way of doing this computation!
3756 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003757 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003758 // The first two arguments (self and _cmd) are pointers; account for
3759 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003760 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003761 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003762 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003763 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003764 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003765 assert (sz.isPositive() &&
3766 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003767 ParmOffset += sz;
3768 }
Ken Dyck40775002010-01-11 17:06:35 +00003769 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003770 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003771 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003772
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003773 // Argument types.
3774 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003775 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003776 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003777 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003778 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003779 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003780 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3781 // Use array's original type only if it has known number of
3782 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003783 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003784 PType = PVDecl->getType();
3785 } else if (PType->isFunctionType())
3786 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003787 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003788 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003789 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003790 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003791 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003792 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003793 }
3794}
3795
Daniel Dunbar4932b362008-08-28 04:38:10 +00003796/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003797/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003798/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3799/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003800/// Property attributes are stored as a comma-delimited C string. The simple
3801/// attributes readonly and bycopy are encoded as single characters. The
3802/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3803/// encoded as single characters, followed by an identifier. Property types
3804/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003805/// these attributes are defined by the following enumeration:
3806/// @code
3807/// enum PropertyAttributes {
3808/// kPropertyReadOnly = 'R', // property is read-only.
3809/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3810/// kPropertyByref = '&', // property is a reference to the value last assigned
3811/// kPropertyDynamic = 'D', // property is dynamic
3812/// kPropertyGetter = 'G', // followed by getter selector name
3813/// kPropertySetter = 'S', // followed by setter selector name
3814/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3815/// kPropertyType = 't' // followed by old-style type encoding.
3816/// kPropertyWeak = 'W' // 'weak' property
3817/// kPropertyStrong = 'P' // property GC'able
3818/// kPropertyNonAtomic = 'N' // property non-atomic
3819/// };
3820/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003821void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003822 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003823 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003824 // Collect information from the property implementation decl(s).
3825 bool Dynamic = false;
3826 ObjCPropertyImplDecl *SynthesizePID = 0;
3827
3828 // FIXME: Duplicated code due to poor abstraction.
3829 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003830 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003831 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3832 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003833 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003834 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003835 ObjCPropertyImplDecl *PID = *i;
3836 if (PID->getPropertyDecl() == PD) {
3837 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3838 Dynamic = true;
3839 } else {
3840 SynthesizePID = PID;
3841 }
3842 }
3843 }
3844 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003845 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003846 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003847 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003848 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003849 ObjCPropertyImplDecl *PID = *i;
3850 if (PID->getPropertyDecl() == PD) {
3851 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3852 Dynamic = true;
3853 } else {
3854 SynthesizePID = PID;
3855 }
3856 }
Mike Stump11289f42009-09-09 15:08:12 +00003857 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003858 }
3859 }
3860
3861 // FIXME: This is not very efficient.
3862 S = "T";
3863
3864 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003865 // GCC has some special rules regarding encoding of properties which
3866 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003867 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003868 true /* outermost type */,
3869 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003870
3871 if (PD->isReadOnly()) {
3872 S += ",R";
3873 } else {
3874 switch (PD->getSetterKind()) {
3875 case ObjCPropertyDecl::Assign: break;
3876 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003877 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003878 }
3879 }
3880
3881 // It really isn't clear at all what this means, since properties
3882 // are "dynamic by default".
3883 if (Dynamic)
3884 S += ",D";
3885
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003886 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3887 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003888
Daniel Dunbar4932b362008-08-28 04:38:10 +00003889 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3890 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003891 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003892 }
3893
3894 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3895 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003896 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003897 }
3898
3899 if (SynthesizePID) {
3900 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3901 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003902 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003903 }
3904
3905 // FIXME: OBJCGC: weak & strong
3906}
3907
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003908/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003909/// Another legacy compatibility encoding: 32-bit longs are encoded as
3910/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003911/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3912///
3913void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003914 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003915 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00003916 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003917 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003918 else
Jay Foad39c79802011-01-12 09:06:06 +00003919 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003920 PointeeTy = IntTy;
3921 }
3922 }
3923}
3924
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003925void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00003926 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003927 // We follow the behavior of gcc, expanding structures which are
3928 // directly pointed to, and expanding embedded structures. Note that
3929 // these rules are sufficient to prevent recursive encoding of the
3930 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003931 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003932 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003933}
3934
David Chisnallb190a2c2010-06-04 01:10:52 +00003935static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3936 switch (T->getAs<BuiltinType>()->getKind()) {
3937 default: assert(0 && "Unhandled builtin type kind");
3938 case BuiltinType::Void: return 'v';
3939 case BuiltinType::Bool: return 'B';
3940 case BuiltinType::Char_U:
3941 case BuiltinType::UChar: return 'C';
3942 case BuiltinType::UShort: return 'S';
3943 case BuiltinType::UInt: return 'I';
3944 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00003945 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003946 case BuiltinType::UInt128: return 'T';
3947 case BuiltinType::ULongLong: return 'Q';
3948 case BuiltinType::Char_S:
3949 case BuiltinType::SChar: return 'c';
3950 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00003951 case BuiltinType::WChar_S:
3952 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00003953 case BuiltinType::Int: return 'i';
3954 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00003955 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003956 case BuiltinType::LongLong: return 'q';
3957 case BuiltinType::Int128: return 't';
3958 case BuiltinType::Float: return 'f';
3959 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00003960 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00003961 }
3962}
3963
Jay Foad39c79802011-01-12 09:06:06 +00003964static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003965 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003966 const Expr *E = FD->getBitWidth();
3967 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003968 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003969 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3970 // The GNU runtime requires more information; bitfields are encoded as b,
3971 // then the offset (in bits) of the first element, then the type of the
3972 // bitfield, then the size in bits. For example, in this structure:
3973 //
3974 // struct
3975 // {
3976 // int integer;
3977 // int flags:2;
3978 // };
3979 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3980 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3981 // information is not especially sensible, but we're stuck with it for
3982 // compatibility with GCC, although providing it breaks anything that
3983 // actually uses runtime introspection and wants to work on both runtimes...
3984 if (!Ctx->getLangOptions().NeXTRuntime) {
3985 const RecordDecl *RD = FD->getParent();
3986 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3987 // FIXME: This same linear search is also used in ExprConstant - it might
3988 // be better if the FieldDecl stored its offset. We'd be increasing the
3989 // size of the object slightly, but saving some time every time it is used.
3990 unsigned i = 0;
3991 for (RecordDecl::field_iterator Field = RD->field_begin(),
3992 FieldEnd = RD->field_end();
3993 Field != FieldEnd; (void)++Field, ++i) {
3994 if (*Field == FD)
3995 break;
3996 }
3997 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00003998 if (T->isEnumeralType())
3999 S += 'i';
4000 else
Jay Foad39c79802011-01-12 09:06:06 +00004001 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004002 }
4003 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004004 S += llvm::utostr(N);
4005}
4006
Daniel Dunbar07d07852009-10-18 21:17:35 +00004007// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004008void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4009 bool ExpandPointedToStructures,
4010 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004011 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004012 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00004013 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004014 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004015 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004016 return EncodeBitField(this, S, T, FD);
4017 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004018 return;
4019 }
Mike Stump11289f42009-09-09 15:08:12 +00004020
John McCall9dd450b2009-09-21 23:43:11 +00004021 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004022 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004023 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004024 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004025 return;
4026 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004027
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004028 // encoding for pointer or r3eference types.
4029 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004030 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004031 if (PT->isObjCSelType()) {
4032 S += ':';
4033 return;
4034 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004035 PointeeTy = PT->getPointeeType();
4036 }
4037 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4038 PointeeTy = RT->getPointeeType();
4039 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004040 bool isReadOnly = false;
4041 // For historical/compatibility reasons, the read-only qualifier of the
4042 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4043 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004044 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004045 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004046 if (OutermostType && T.isConstQualified()) {
4047 isReadOnly = true;
4048 S += 'r';
4049 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004050 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004051 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004052 while (P->getAs<PointerType>())
4053 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004054 if (P.isConstQualified()) {
4055 isReadOnly = true;
4056 S += 'r';
4057 }
4058 }
4059 if (isReadOnly) {
4060 // Another legacy compatibility encoding. Some ObjC qualifier and type
4061 // combinations need to be rearranged.
4062 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004063 if (llvm::StringRef(S).endswith("nr"))
4064 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004065 }
Mike Stump11289f42009-09-09 15:08:12 +00004066
Anders Carlssond8499822007-10-29 05:01:08 +00004067 if (PointeeTy->isCharType()) {
4068 // char pointer types should be encoded as '*' unless it is a
4069 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004070 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004071 S += '*';
4072 return;
4073 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004074 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004075 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4076 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4077 S += '#';
4078 return;
4079 }
4080 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4081 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4082 S += '@';
4083 return;
4084 }
4085 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004086 }
Anders Carlssond8499822007-10-29 05:01:08 +00004087 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004088 getLegacyIntegralTypeEncoding(PointeeTy);
4089
Mike Stump11289f42009-09-09 15:08:12 +00004090 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004091 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004092 return;
4093 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004094
Chris Lattnere7cabb92009-07-13 00:10:46 +00004095 if (const ArrayType *AT =
4096 // Ignore type qualifiers etc.
4097 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004098 if (isa<IncompleteArrayType>(AT)) {
4099 // Incomplete arrays are encoded as a pointer to the array element.
4100 S += '^';
4101
Mike Stump11289f42009-09-09 15:08:12 +00004102 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004103 false, ExpandStructures, FD);
4104 } else {
4105 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004106
Anders Carlssond05f44b2009-02-22 01:38:57 +00004107 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4108 S += llvm::utostr(CAT->getSize().getZExtValue());
4109 else {
4110 //Variable length arrays are encoded as a regular array with 0 elements.
4111 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4112 S += '0';
4113 }
Mike Stump11289f42009-09-09 15:08:12 +00004114
4115 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004116 false, ExpandStructures, FD);
4117 S += ']';
4118 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004119 return;
4120 }
Mike Stump11289f42009-09-09 15:08:12 +00004121
John McCall9dd450b2009-09-21 23:43:11 +00004122 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004123 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004124 return;
4125 }
Mike Stump11289f42009-09-09 15:08:12 +00004126
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004127 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004128 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004129 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004130 // Anonymous structures print as '?'
4131 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4132 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004133 if (ClassTemplateSpecializationDecl *Spec
4134 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4135 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4136 std::string TemplateArgsStr
4137 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004138 TemplateArgs.data(),
4139 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004140 (*this).PrintingPolicy);
4141
4142 S += TemplateArgsStr;
4143 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004144 } else {
4145 S += '?';
4146 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004147 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004148 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004149 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4150 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004151 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004152 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004153 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004154 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004155 S += '"';
4156 }
Mike Stump11289f42009-09-09 15:08:12 +00004157
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004158 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004159 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004160 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004161 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004162 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004163 QualType qt = Field->getType();
4164 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004165 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004166 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004167 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004168 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004169 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004170 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004171 return;
4172 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004173
Chris Lattnere7cabb92009-07-13 00:10:46 +00004174 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004175 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004176 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004177 else
4178 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004179 return;
4180 }
Mike Stump11289f42009-09-09 15:08:12 +00004181
Chris Lattnere7cabb92009-07-13 00:10:46 +00004182 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004183 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004184 return;
4185 }
Mike Stump11289f42009-09-09 15:08:12 +00004186
John McCall8b07ec22010-05-15 11:32:37 +00004187 // Ignore protocol qualifiers when mangling at this level.
4188 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4189 T = OT->getBaseType();
4190
John McCall8ccfcb52009-09-24 19:53:00 +00004191 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004192 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004193 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004194 S += '{';
4195 const IdentifierInfo *II = OI->getIdentifier();
4196 S += II->getName();
4197 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004198 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4199 DeepCollectObjCIvars(OI, true, Ivars);
4200 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4201 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4202 if (Field->isBitField())
4203 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004204 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004205 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004206 }
4207 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004208 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004209 }
Mike Stump11289f42009-09-09 15:08:12 +00004210
John McCall9dd450b2009-09-21 23:43:11 +00004211 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004212 if (OPT->isObjCIdType()) {
4213 S += '@';
4214 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004215 }
Mike Stump11289f42009-09-09 15:08:12 +00004216
Steve Narofff0c86112009-10-28 22:03:49 +00004217 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4218 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4219 // Since this is a binary compatibility issue, need to consult with runtime
4220 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004221 S += '#';
4222 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004223 }
Mike Stump11289f42009-09-09 15:08:12 +00004224
Chris Lattnere7cabb92009-07-13 00:10:46 +00004225 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004226 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004227 ExpandPointedToStructures,
4228 ExpandStructures, FD);
4229 if (FD || EncodingProperty) {
4230 // Note that we do extended encoding of protocol qualifer list
4231 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004232 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004233 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4234 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004235 S += '<';
4236 S += (*I)->getNameAsString();
4237 S += '>';
4238 }
4239 S += '"';
4240 }
4241 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004242 }
Mike Stump11289f42009-09-09 15:08:12 +00004243
Chris Lattnere7cabb92009-07-13 00:10:46 +00004244 QualType PointeeTy = OPT->getPointeeType();
4245 if (!EncodingProperty &&
4246 isa<TypedefType>(PointeeTy.getTypePtr())) {
4247 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004248 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004249 // {...};
4250 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004251 getObjCEncodingForTypeImpl(PointeeTy, S,
4252 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004253 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004254 return;
4255 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004256
4257 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004258 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004259 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004260 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004261 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4262 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004263 S += '<';
4264 S += (*I)->getNameAsString();
4265 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004266 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004267 S += '"';
4268 }
4269 return;
4270 }
Mike Stump11289f42009-09-09 15:08:12 +00004271
John McCalla9e6e8d2010-05-17 23:56:34 +00004272 // gcc just blithely ignores member pointers.
4273 // TODO: maybe there should be a mangling for these
4274 if (T->getAs<MemberPointerType>())
4275 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004276
4277 if (T->isVectorType()) {
4278 // This matches gcc's encoding, even though technically it is
4279 // insufficient.
4280 // FIXME. We should do a better job than gcc.
4281 return;
4282 }
4283
Chris Lattnere7cabb92009-07-13 00:10:46 +00004284 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004285}
4286
Mike Stump11289f42009-09-09 15:08:12 +00004287void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004288 std::string& S) const {
4289 if (QT & Decl::OBJC_TQ_In)
4290 S += 'n';
4291 if (QT & Decl::OBJC_TQ_Inout)
4292 S += 'N';
4293 if (QT & Decl::OBJC_TQ_Out)
4294 S += 'o';
4295 if (QT & Decl::OBJC_TQ_Bycopy)
4296 S += 'O';
4297 if (QT & Decl::OBJC_TQ_Byref)
4298 S += 'R';
4299 if (QT & Decl::OBJC_TQ_Oneway)
4300 S += 'V';
4301}
4302
Chris Lattnere7cabb92009-07-13 00:10:46 +00004303void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004304 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004305
Anders Carlsson87c149b2007-10-11 01:00:40 +00004306 BuiltinVaListType = T;
4307}
4308
Chris Lattnere7cabb92009-07-13 00:10:46 +00004309void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004310 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004311}
4312
Chris Lattnere7cabb92009-07-13 00:10:46 +00004313void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004314 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004315}
4316
Chris Lattnere7cabb92009-07-13 00:10:46 +00004317void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004318 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004319}
4320
Chris Lattnere7cabb92009-07-13 00:10:46 +00004321void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004322 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004323}
4324
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004325void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004326 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004327 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004328
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004329 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004330}
4331
John McCalld28ae272009-12-02 08:04:21 +00004332/// \brief Retrieve the template name that corresponds to a non-empty
4333/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004334TemplateName
4335ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4336 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004337 unsigned size = End - Begin;
4338 assert(size > 1 && "set is not overloaded!");
4339
4340 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4341 size * sizeof(FunctionTemplateDecl*));
4342 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4343
4344 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004345 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004346 NamedDecl *D = *I;
4347 assert(isa<FunctionTemplateDecl>(D) ||
4348 (isa<UsingShadowDecl>(D) &&
4349 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4350 *Storage++ = D;
4351 }
4352
4353 return TemplateName(OT);
4354}
4355
Douglas Gregordc572a32009-03-30 22:58:21 +00004356/// \brief Retrieve the template name that represents a qualified
4357/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004358TemplateName
4359ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4360 bool TemplateKeyword,
4361 TemplateDecl *Template) const {
Douglas Gregorc42075a2010-02-04 18:10:26 +00004362 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004363 llvm::FoldingSetNodeID ID;
4364 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4365
4366 void *InsertPos = 0;
4367 QualifiedTemplateName *QTN =
4368 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4369 if (!QTN) {
4370 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4371 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4372 }
4373
4374 return TemplateName(QTN);
4375}
4376
4377/// \brief Retrieve the template name that represents a dependent
4378/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004379TemplateName
4380ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4381 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004382 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004383 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004384
4385 llvm::FoldingSetNodeID ID;
4386 DependentTemplateName::Profile(ID, NNS, Name);
4387
4388 void *InsertPos = 0;
4389 DependentTemplateName *QTN =
4390 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4391
4392 if (QTN)
4393 return TemplateName(QTN);
4394
4395 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4396 if (CanonNNS == NNS) {
4397 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4398 } else {
4399 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4400 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004401 DependentTemplateName *CheckQTN =
4402 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4403 assert(!CheckQTN && "Dependent type name canonicalization broken");
4404 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004405 }
4406
4407 DependentTemplateNames.InsertNode(QTN, InsertPos);
4408 return TemplateName(QTN);
4409}
4410
Douglas Gregor71395fa2009-11-04 00:56:37 +00004411/// \brief Retrieve the template name that represents a dependent
4412/// template name such as \c MetaFun::template operator+.
4413TemplateName
4414ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004415 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004416 assert((!NNS || NNS->isDependent()) &&
4417 "Nested name specifier must be dependent");
4418
4419 llvm::FoldingSetNodeID ID;
4420 DependentTemplateName::Profile(ID, NNS, Operator);
4421
4422 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004423 DependentTemplateName *QTN
4424 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004425
4426 if (QTN)
4427 return TemplateName(QTN);
4428
4429 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4430 if (CanonNNS == NNS) {
4431 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4432 } else {
4433 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4434 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004435
4436 DependentTemplateName *CheckQTN
4437 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4438 assert(!CheckQTN && "Dependent template name canonicalization broken");
4439 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004440 }
4441
4442 DependentTemplateNames.InsertNode(QTN, InsertPos);
4443 return TemplateName(QTN);
4444}
4445
Douglas Gregor5590be02011-01-15 06:45:20 +00004446TemplateName
4447ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4448 const TemplateArgument &ArgPack) const {
4449 ASTContext &Self = const_cast<ASTContext &>(*this);
4450 llvm::FoldingSetNodeID ID;
4451 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4452
4453 void *InsertPos = 0;
4454 SubstTemplateTemplateParmPackStorage *Subst
4455 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4456
4457 if (!Subst) {
4458 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4459 ArgPack.pack_size(),
4460 ArgPack.pack_begin());
4461 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4462 }
4463
4464 return TemplateName(Subst);
4465}
4466
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004467/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004468/// TargetInfo, produce the corresponding type. The unsigned @p Type
4469/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004470CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004471 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004472 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004473 case TargetInfo::SignedShort: return ShortTy;
4474 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4475 case TargetInfo::SignedInt: return IntTy;
4476 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4477 case TargetInfo::SignedLong: return LongTy;
4478 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4479 case TargetInfo::SignedLongLong: return LongLongTy;
4480 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4481 }
4482
4483 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004484 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004485}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004486
4487//===----------------------------------------------------------------------===//
4488// Type Predicates.
4489//===----------------------------------------------------------------------===//
4490
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004491/// isObjCNSObjectType - Return true if this is an NSObject object using
4492/// NSObject attribute on a c-style pointer type.
4493/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004494/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004495///
4496bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCall424cec92011-01-19 06:33:43 +00004497 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004498 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004499 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004500 return true;
4501 }
Mike Stump11289f42009-09-09 15:08:12 +00004502 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004503}
4504
Fariborz Jahanian96207692009-02-18 21:49:28 +00004505/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4506/// garbage collection attribute.
4507///
John McCall553d45a2011-01-12 00:34:59 +00004508Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4509 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4510 return Qualifiers::GCNone;
4511
4512 assert(getLangOptions().ObjC1);
4513 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4514
4515 // Default behaviour under objective-C's gc is for ObjC pointers
4516 // (or pointers to them) be treated as though they were declared
4517 // as __strong.
4518 if (GCAttrs == Qualifiers::GCNone) {
4519 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4520 return Qualifiers::Strong;
4521 else if (Ty->isPointerType())
4522 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4523 } else {
4524 // It's not valid to set GC attributes on anything that isn't a
4525 // pointer.
4526#ifndef NDEBUG
4527 QualType CT = Ty->getCanonicalTypeInternal();
4528 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4529 CT = AT->getElementType();
4530 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4531#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004532 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004533 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004534}
4535
Chris Lattner49af6a42008-04-07 06:51:04 +00004536//===----------------------------------------------------------------------===//
4537// Type Compatibility Testing
4538//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004539
Mike Stump11289f42009-09-09 15:08:12 +00004540/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004541/// compatible.
4542static bool areCompatVectorTypes(const VectorType *LHS,
4543 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004544 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004545 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004546 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004547}
4548
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004549bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4550 QualType SecondVec) {
4551 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4552 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4553
4554 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4555 return true;
4556
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004557 // Treat Neon vector types and most AltiVec vector types as if they are the
4558 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004559 const VectorType *First = FirstVec->getAs<VectorType>();
4560 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004561 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004562 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004563 First->getVectorKind() != VectorType::AltiVecPixel &&
4564 First->getVectorKind() != VectorType::AltiVecBool &&
4565 Second->getVectorKind() != VectorType::AltiVecPixel &&
4566 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004567 return true;
4568
4569 return false;
4570}
4571
Steve Naroff8e6aee52009-07-23 01:01:38 +00004572//===----------------------------------------------------------------------===//
4573// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4574//===----------------------------------------------------------------------===//
4575
4576/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4577/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004578bool
4579ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4580 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004581 if (lProto == rProto)
4582 return true;
4583 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4584 E = rProto->protocol_end(); PI != E; ++PI)
4585 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4586 return true;
4587 return false;
4588}
4589
Steve Naroff8e6aee52009-07-23 01:01:38 +00004590/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4591/// return true if lhs's protocols conform to rhs's protocol; false
4592/// otherwise.
4593bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4594 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4595 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4596 return false;
4597}
4598
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004599/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4600/// Class<p1, ...>.
4601bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4602 QualType rhs) {
4603 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4604 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4605 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4606
4607 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4608 E = lhsQID->qual_end(); I != E; ++I) {
4609 bool match = false;
4610 ObjCProtocolDecl *lhsProto = *I;
4611 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4612 E = rhsOPT->qual_end(); J != E; ++J) {
4613 ObjCProtocolDecl *rhsProto = *J;
4614 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4615 match = true;
4616 break;
4617 }
4618 }
4619 if (!match)
4620 return false;
4621 }
4622 return true;
4623}
4624
Steve Naroff8e6aee52009-07-23 01:01:38 +00004625/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4626/// ObjCQualifiedIDType.
4627bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4628 bool compare) {
4629 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004630 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004631 lhs->isObjCIdType() || lhs->isObjCClassType())
4632 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004633 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004634 rhs->isObjCIdType() || rhs->isObjCClassType())
4635 return true;
4636
4637 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004638 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004639
Steve Naroff8e6aee52009-07-23 01:01:38 +00004640 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004641
Steve Naroff8e6aee52009-07-23 01:01:38 +00004642 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004643 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004644 // make sure we check the class hierarchy.
4645 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4646 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4647 E = lhsQID->qual_end(); I != E; ++I) {
4648 // when comparing an id<P> on lhs with a static type on rhs,
4649 // see if static class implements all of id's protocols, directly or
4650 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004651 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004652 return false;
4653 }
4654 }
4655 // If there are no qualifiers and no interface, we have an 'id'.
4656 return true;
4657 }
Mike Stump11289f42009-09-09 15:08:12 +00004658 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004659 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4660 E = lhsQID->qual_end(); I != E; ++I) {
4661 ObjCProtocolDecl *lhsProto = *I;
4662 bool match = false;
4663
4664 // when comparing an id<P> on lhs with a static type on rhs,
4665 // see if static class implements all of id's protocols, directly or
4666 // through its super class and categories.
4667 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4668 E = rhsOPT->qual_end(); J != E; ++J) {
4669 ObjCProtocolDecl *rhsProto = *J;
4670 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4671 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4672 match = true;
4673 break;
4674 }
4675 }
Mike Stump11289f42009-09-09 15:08:12 +00004676 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004677 // make sure we check the class hierarchy.
4678 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4679 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4680 E = lhsQID->qual_end(); I != E; ++I) {
4681 // when comparing an id<P> on lhs with a static type on rhs,
4682 // see if static class implements all of id's protocols, directly or
4683 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004684 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004685 match = true;
4686 break;
4687 }
4688 }
4689 }
4690 if (!match)
4691 return false;
4692 }
Mike Stump11289f42009-09-09 15:08:12 +00004693
Steve Naroff8e6aee52009-07-23 01:01:38 +00004694 return true;
4695 }
Mike Stump11289f42009-09-09 15:08:12 +00004696
Steve Naroff8e6aee52009-07-23 01:01:38 +00004697 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4698 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4699
Mike Stump11289f42009-09-09 15:08:12 +00004700 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004701 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004702 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004703 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4704 E = lhsOPT->qual_end(); I != E; ++I) {
4705 ObjCProtocolDecl *lhsProto = *I;
4706 bool match = false;
4707
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004708 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004709 // see if static class implements all of id's protocols, directly or
4710 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004711 // First, lhs protocols in the qualifier list must be found, direct
4712 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004713 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4714 E = rhsQID->qual_end(); J != E; ++J) {
4715 ObjCProtocolDecl *rhsProto = *J;
4716 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4717 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4718 match = true;
4719 break;
4720 }
4721 }
4722 if (!match)
4723 return false;
4724 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004725
4726 // Static class's protocols, or its super class or category protocols
4727 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4728 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4729 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4730 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4731 // This is rather dubious but matches gcc's behavior. If lhs has
4732 // no type qualifier and its class has no static protocol(s)
4733 // assume that it is mismatch.
4734 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4735 return false;
4736 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4737 LHSInheritedProtocols.begin(),
4738 E = LHSInheritedProtocols.end(); I != E; ++I) {
4739 bool match = false;
4740 ObjCProtocolDecl *lhsProto = (*I);
4741 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4742 E = rhsQID->qual_end(); J != E; ++J) {
4743 ObjCProtocolDecl *rhsProto = *J;
4744 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4745 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4746 match = true;
4747 break;
4748 }
4749 }
4750 if (!match)
4751 return false;
4752 }
4753 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004754 return true;
4755 }
4756 return false;
4757}
4758
Eli Friedman47f77112008-08-22 00:56:42 +00004759/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004760/// compatible for assignment from RHS to LHS. This handles validation of any
4761/// protocol qualifiers on the LHS or RHS.
4762///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004763bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4764 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004765 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4766 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4767
Steve Naroff1329fa02009-07-15 18:40:39 +00004768 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004769 if (LHS->isObjCUnqualifiedIdOrClass() ||
4770 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004771 return true;
4772
John McCall8b07ec22010-05-15 11:32:37 +00004773 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004774 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4775 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004776 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004777
4778 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4779 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4780 QualType(RHSOPT,0));
4781
John McCall8b07ec22010-05-15 11:32:37 +00004782 // If we have 2 user-defined types, fall into that path.
4783 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004784 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004785
Steve Naroff8e6aee52009-07-23 01:01:38 +00004786 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004787}
4788
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004789/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4790/// for providing type-safty for objective-c pointers used to pass/return
4791/// arguments in block literals. When passed as arguments, passing 'A*' where
4792/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4793/// not OK. For the return type, the opposite is not OK.
4794bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4795 const ObjCObjectPointerType *LHSOPT,
4796 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004797 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004798 return true;
4799
4800 if (LHSOPT->isObjCBuiltinType()) {
4801 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4802 }
4803
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004804 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004805 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4806 QualType(RHSOPT,0),
4807 false);
4808
4809 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4810 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4811 if (LHS && RHS) { // We have 2 user-defined types.
4812 if (LHS != RHS) {
4813 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4814 return false;
4815 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4816 return true;
4817 }
4818 else
4819 return true;
4820 }
4821 return false;
4822}
4823
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004824/// getIntersectionOfProtocols - This routine finds the intersection of set
4825/// of protocols inherited from two distinct objective-c pointer objects.
4826/// It is used to build composite qualifier list of the composite type of
4827/// the conditional expression involving two objective-c pointer objects.
4828static
4829void getIntersectionOfProtocols(ASTContext &Context,
4830 const ObjCObjectPointerType *LHSOPT,
4831 const ObjCObjectPointerType *RHSOPT,
4832 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4833
John McCall8b07ec22010-05-15 11:32:37 +00004834 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4835 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4836 assert(LHS->getInterface() && "LHS must have an interface base");
4837 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004838
4839 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4840 unsigned LHSNumProtocols = LHS->getNumProtocols();
4841 if (LHSNumProtocols > 0)
4842 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4843 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004844 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004845 Context.CollectInheritedProtocols(LHS->getInterface(),
4846 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004847 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4848 LHSInheritedProtocols.end());
4849 }
4850
4851 unsigned RHSNumProtocols = RHS->getNumProtocols();
4852 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004853 ObjCProtocolDecl **RHSProtocols =
4854 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004855 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4856 if (InheritedProtocolSet.count(RHSProtocols[i]))
4857 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4858 }
4859 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004860 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004861 Context.CollectInheritedProtocols(RHS->getInterface(),
4862 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004863 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4864 RHSInheritedProtocols.begin(),
4865 E = RHSInheritedProtocols.end(); I != E; ++I)
4866 if (InheritedProtocolSet.count((*I)))
4867 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004868 }
4869}
4870
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004871/// areCommonBaseCompatible - Returns common base class of the two classes if
4872/// one found. Note that this is O'2 algorithm. But it will be called as the
4873/// last type comparison in a ?-exp of ObjC pointer types before a
4874/// warning is issued. So, its invokation is extremely rare.
4875QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004876 const ObjCObjectPointerType *Lptr,
4877 const ObjCObjectPointerType *Rptr) {
4878 const ObjCObjectType *LHS = Lptr->getObjectType();
4879 const ObjCObjectType *RHS = Rptr->getObjectType();
4880 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4881 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4882 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004883 return QualType();
4884
John McCall8b07ec22010-05-15 11:32:37 +00004885 while ((LDecl = LDecl->getSuperClass())) {
4886 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004887 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004888 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4889 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4890
4891 QualType Result = QualType(LHS, 0);
4892 if (!Protocols.empty())
4893 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4894 Result = getObjCObjectPointerType(Result);
4895 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004896 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004897 }
4898
4899 return QualType();
4900}
4901
John McCall8b07ec22010-05-15 11:32:37 +00004902bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4903 const ObjCObjectType *RHS) {
4904 assert(LHS->getInterface() && "LHS is not an interface type");
4905 assert(RHS->getInterface() && "RHS is not an interface type");
4906
Chris Lattner49af6a42008-04-07 06:51:04 +00004907 // Verify that the base decls are compatible: the RHS must be a subclass of
4908 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004909 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004910 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004911
Chris Lattner49af6a42008-04-07 06:51:04 +00004912 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4913 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004914 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004915 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004916
Chris Lattner49af6a42008-04-07 06:51:04 +00004917 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4918 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004919 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004920 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004921
John McCall8b07ec22010-05-15 11:32:37 +00004922 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4923 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004924 LHSPI != LHSPE; LHSPI++) {
4925 bool RHSImplementsProtocol = false;
4926
4927 // If the RHS doesn't implement the protocol on the left, the types
4928 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004929 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4930 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004931 RHSPI != RHSPE; RHSPI++) {
4932 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004933 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004934 break;
4935 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004936 }
4937 // FIXME: For better diagnostics, consider passing back the protocol name.
4938 if (!RHSImplementsProtocol)
4939 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004940 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004941 // The RHS implements all protocols listed on the LHS.
4942 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004943}
4944
Steve Naroffb7605152009-02-12 17:52:19 +00004945bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4946 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004947 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4948 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004949
Steve Naroff7cae42b2009-07-10 23:34:53 +00004950 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004951 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004952
4953 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4954 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004955}
4956
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004957bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4958 return canAssignObjCInterfaces(
4959 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4960 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4961}
4962
Mike Stump11289f42009-09-09 15:08:12 +00004963/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004964/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004965/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004966/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004967bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4968 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004969 if (getLangOptions().CPlusPlus)
4970 return hasSameType(LHS, RHS);
4971
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004972 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00004973}
4974
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004975bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4976 return !mergeTypes(LHS, RHS, true).isNull();
4977}
4978
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004979/// mergeTransparentUnionType - if T is a transparent union type and a member
4980/// of T is compatible with SubType, return the merged type, else return
4981/// QualType()
4982QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
4983 bool OfBlockPointer,
4984 bool Unqualified) {
4985 if (const RecordType *UT = T->getAsUnionType()) {
4986 RecordDecl *UD = UT->getDecl();
4987 if (UD->hasAttr<TransparentUnionAttr>()) {
4988 for (RecordDecl::field_iterator it = UD->field_begin(),
4989 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00004990 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004991 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
4992 if (!MT.isNull())
4993 return MT;
4994 }
4995 }
4996 }
4997
4998 return QualType();
4999}
5000
5001/// mergeFunctionArgumentTypes - merge two types which appear as function
5002/// argument types
5003QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5004 bool OfBlockPointer,
5005 bool Unqualified) {
5006 // GNU extension: two types are compatible if they appear as a function
5007 // argument, one of the types is a transparent union type and the other
5008 // type is compatible with a union member
5009 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5010 Unqualified);
5011 if (!lmerge.isNull())
5012 return lmerge;
5013
5014 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5015 Unqualified);
5016 if (!rmerge.isNull())
5017 return rmerge;
5018
5019 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5020}
5021
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005022QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005023 bool OfBlockPointer,
5024 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005025 const FunctionType *lbase = lhs->getAs<FunctionType>();
5026 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005027 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5028 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005029 bool allLTypes = true;
5030 bool allRTypes = true;
5031
5032 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005033 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005034 if (OfBlockPointer) {
5035 QualType RHS = rbase->getResultType();
5036 QualType LHS = lbase->getResultType();
5037 bool UnqualifiedResult = Unqualified;
5038 if (!UnqualifiedResult)
5039 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
5040 retType = mergeTypes(RHS, LHS, true, UnqualifiedResult);
5041 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005042 else
John McCall8c6b56f2010-12-15 01:06:38 +00005043 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5044 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005045 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005046
5047 if (Unqualified)
5048 retType = retType.getUnqualifiedType();
5049
5050 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5051 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5052 if (Unqualified) {
5053 LRetType = LRetType.getUnqualifiedType();
5054 RRetType = RRetType.getUnqualifiedType();
5055 }
5056
5057 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005058 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005059 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005060 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005061
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005062 // FIXME: double check this
5063 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5064 // rbase->getRegParmAttr() != 0 &&
5065 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005066 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5067 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005068
Douglas Gregor8c940862010-01-18 17:14:39 +00005069 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005070 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005071 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005072
John McCall8c6b56f2010-12-15 01:06:38 +00005073 // Regparm is part of the calling convention.
5074 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5075 return QualType();
5076
5077 // It's noreturn if either type is.
5078 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5079 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5080 if (NoReturn != lbaseInfo.getNoReturn())
5081 allLTypes = false;
5082 if (NoReturn != rbaseInfo.getNoReturn())
5083 allRTypes = false;
5084
5085 FunctionType::ExtInfo einfo(NoReturn,
5086 lbaseInfo.getRegParm(),
5087 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00005088
Eli Friedman47f77112008-08-22 00:56:42 +00005089 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005090 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5091 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005092 unsigned lproto_nargs = lproto->getNumArgs();
5093 unsigned rproto_nargs = rproto->getNumArgs();
5094
5095 // Compatible functions must have the same number of arguments
5096 if (lproto_nargs != rproto_nargs)
5097 return QualType();
5098
5099 // Variadic and non-variadic functions aren't compatible
5100 if (lproto->isVariadic() != rproto->isVariadic())
5101 return QualType();
5102
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005103 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5104 return QualType();
5105
Eli Friedman47f77112008-08-22 00:56:42 +00005106 // Check argument compatibility
5107 llvm::SmallVector<QualType, 10> types;
5108 for (unsigned i = 0; i < lproto_nargs; i++) {
5109 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5110 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005111 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5112 OfBlockPointer,
5113 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005114 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005115
5116 if (Unqualified)
5117 argtype = argtype.getUnqualifiedType();
5118
Eli Friedman47f77112008-08-22 00:56:42 +00005119 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005120 if (Unqualified) {
5121 largtype = largtype.getUnqualifiedType();
5122 rargtype = rargtype.getUnqualifiedType();
5123 }
5124
Chris Lattner465fa322008-10-05 17:34:18 +00005125 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5126 allLTypes = false;
5127 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5128 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005129 }
5130 if (allLTypes) return lhs;
5131 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005132
5133 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5134 EPI.ExtInfo = einfo;
5135 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005136 }
5137
5138 if (lproto) allRTypes = false;
5139 if (rproto) allLTypes = false;
5140
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005141 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005142 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005143 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005144 if (proto->isVariadic()) return QualType();
5145 // Check that the types are compatible with the types that
5146 // would result from default argument promotions (C99 6.7.5.3p15).
5147 // The only types actually affected are promotable integer
5148 // types and floats, which would be passed as a different
5149 // type depending on whether the prototype is visible.
5150 unsigned proto_nargs = proto->getNumArgs();
5151 for (unsigned i = 0; i < proto_nargs; ++i) {
5152 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005153
5154 // Look at the promotion type of enum types, since that is the type used
5155 // to pass enum values.
5156 if (const EnumType *Enum = argTy->getAs<EnumType>())
5157 argTy = Enum->getDecl()->getPromotionType();
5158
Eli Friedman47f77112008-08-22 00:56:42 +00005159 if (argTy->isPromotableIntegerType() ||
5160 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5161 return QualType();
5162 }
5163
5164 if (allLTypes) return lhs;
5165 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005166
5167 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5168 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005169 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005170 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005171 }
5172
5173 if (allLTypes) return lhs;
5174 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005175 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005176}
5177
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005178QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005179 bool OfBlockPointer,
5180 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005181 // C++ [expr]: If an expression initially has the type "reference to T", the
5182 // type is adjusted to "T" prior to any further analysis, the expression
5183 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005184 // expression is an lvalue unless the reference is an rvalue reference and
5185 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005186 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5187 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005188
5189 if (Unqualified) {
5190 LHS = LHS.getUnqualifiedType();
5191 RHS = RHS.getUnqualifiedType();
5192 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005193
Eli Friedman47f77112008-08-22 00:56:42 +00005194 QualType LHSCan = getCanonicalType(LHS),
5195 RHSCan = getCanonicalType(RHS);
5196
5197 // If two types are identical, they are compatible.
5198 if (LHSCan == RHSCan)
5199 return LHS;
5200
John McCall8ccfcb52009-09-24 19:53:00 +00005201 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005202 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5203 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005204 if (LQuals != RQuals) {
5205 // If any of these qualifiers are different, we have a type
5206 // mismatch.
5207 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5208 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5209 return QualType();
5210
5211 // Exactly one GC qualifier difference is allowed: __strong is
5212 // okay if the other type has no GC qualifier but is an Objective
5213 // C object pointer (i.e. implicitly strong by default). We fix
5214 // this by pretending that the unqualified type was actually
5215 // qualified __strong.
5216 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5217 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5218 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5219
5220 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5221 return QualType();
5222
5223 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5224 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5225 }
5226 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5227 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5228 }
Eli Friedman47f77112008-08-22 00:56:42 +00005229 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005230 }
5231
5232 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005233
Eli Friedmandcca6332009-06-01 01:22:52 +00005234 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5235 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005236
Chris Lattnerfd652912008-01-14 05:45:46 +00005237 // We want to consider the two function types to be the same for these
5238 // comparisons, just force one to the other.
5239 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5240 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005241
5242 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005243 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5244 LHSClass = Type::ConstantArray;
5245 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5246 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005247
John McCall8b07ec22010-05-15 11:32:37 +00005248 // ObjCInterfaces are just specialized ObjCObjects.
5249 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5250 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5251
Nate Begemance4d7fc2008-04-18 23:10:10 +00005252 // Canonicalize ExtVector -> Vector.
5253 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5254 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005255
Chris Lattner95554662008-04-07 05:43:21 +00005256 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005257 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005258 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005259 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005260 // Compatibility is based on the underlying type, not the promotion
5261 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005262 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005263 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5264 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005265 }
John McCall9dd450b2009-09-21 23:43:11 +00005266 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005267 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5268 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005269 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005270
Eli Friedman47f77112008-08-22 00:56:42 +00005271 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005272 }
Eli Friedman47f77112008-08-22 00:56:42 +00005273
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005274 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005275 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005276#define TYPE(Class, Base)
5277#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005278#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005279#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5280#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5281#include "clang/AST/TypeNodes.def"
5282 assert(false && "Non-canonical and dependent types shouldn't get here");
5283 return QualType();
5284
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005285 case Type::LValueReference:
5286 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005287 case Type::MemberPointer:
5288 assert(false && "C++ should never be in mergeTypes");
5289 return QualType();
5290
John McCall8b07ec22010-05-15 11:32:37 +00005291 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005292 case Type::IncompleteArray:
5293 case Type::VariableArray:
5294 case Type::FunctionProto:
5295 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005296 assert(false && "Types are eliminated above");
5297 return QualType();
5298
Chris Lattnerfd652912008-01-14 05:45:46 +00005299 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005300 {
5301 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005302 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5303 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005304 if (Unqualified) {
5305 LHSPointee = LHSPointee.getUnqualifiedType();
5306 RHSPointee = RHSPointee.getUnqualifiedType();
5307 }
5308 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5309 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005310 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005311 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005312 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005313 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005314 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005315 return getPointerType(ResultType);
5316 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005317 case Type::BlockPointer:
5318 {
5319 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005320 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5321 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005322 if (Unqualified) {
5323 LHSPointee = LHSPointee.getUnqualifiedType();
5324 RHSPointee = RHSPointee.getUnqualifiedType();
5325 }
5326 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5327 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005328 if (ResultType.isNull()) return QualType();
5329 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5330 return LHS;
5331 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5332 return RHS;
5333 return getBlockPointerType(ResultType);
5334 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005335 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005336 {
5337 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5338 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5339 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5340 return QualType();
5341
5342 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5343 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005344 if (Unqualified) {
5345 LHSElem = LHSElem.getUnqualifiedType();
5346 RHSElem = RHSElem.getUnqualifiedType();
5347 }
5348
5349 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005350 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005351 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5352 return LHS;
5353 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5354 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005355 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5356 ArrayType::ArraySizeModifier(), 0);
5357 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5358 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005359 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5360 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005361 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5362 return LHS;
5363 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5364 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005365 if (LVAT) {
5366 // FIXME: This isn't correct! But tricky to implement because
5367 // the array's size has to be the size of LHS, but the type
5368 // has to be different.
5369 return LHS;
5370 }
5371 if (RVAT) {
5372 // FIXME: This isn't correct! But tricky to implement because
5373 // the array's size has to be the size of RHS, but the type
5374 // has to be different.
5375 return RHS;
5376 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005377 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5378 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005379 return getIncompleteArrayType(ResultType,
5380 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005381 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005382 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005383 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005384 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005385 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005386 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005387 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005388 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005389 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005390 case Type::Complex:
5391 // Distinct complex types are incompatible.
5392 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005393 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005394 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005395 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5396 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005397 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005398 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005399 case Type::ObjCObject: {
5400 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005401 // FIXME: This should be type compatibility, e.g. whether
5402 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005403 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5404 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5405 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005406 return LHS;
5407
Eli Friedman47f77112008-08-22 00:56:42 +00005408 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005409 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005410 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005411 if (OfBlockPointer) {
5412 if (canAssignObjCInterfacesInBlockPointer(
5413 LHS->getAs<ObjCObjectPointerType>(),
5414 RHS->getAs<ObjCObjectPointerType>()))
5415 return LHS;
5416 return QualType();
5417 }
John McCall9dd450b2009-09-21 23:43:11 +00005418 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5419 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005420 return LHS;
5421
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005422 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005423 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005424 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005425
5426 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005427}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005428
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005429/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5430/// 'RHS' attributes and returns the merged version; including for function
5431/// return types.
5432QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5433 QualType LHSCan = getCanonicalType(LHS),
5434 RHSCan = getCanonicalType(RHS);
5435 // If two types are identical, they are compatible.
5436 if (LHSCan == RHSCan)
5437 return LHS;
5438 if (RHSCan->isFunctionType()) {
5439 if (!LHSCan->isFunctionType())
5440 return QualType();
5441 QualType OldReturnType =
5442 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5443 QualType NewReturnType =
5444 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5445 QualType ResReturnType =
5446 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5447 if (ResReturnType.isNull())
5448 return QualType();
5449 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5450 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5451 // In either case, use OldReturnType to build the new function type.
5452 const FunctionType *F = LHS->getAs<FunctionType>();
5453 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005454 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5455 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005456 QualType ResultType
5457 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005458 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005459 return ResultType;
5460 }
5461 }
5462 return QualType();
5463 }
5464
5465 // If the qualifiers are different, the types can still be merged.
5466 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5467 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5468 if (LQuals != RQuals) {
5469 // If any of these qualifiers are different, we have a type mismatch.
5470 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5471 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5472 return QualType();
5473
5474 // Exactly one GC qualifier difference is allowed: __strong is
5475 // okay if the other type has no GC qualifier but is an Objective
5476 // C object pointer (i.e. implicitly strong by default). We fix
5477 // this by pretending that the unqualified type was actually
5478 // qualified __strong.
5479 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5480 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5481 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5482
5483 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5484 return QualType();
5485
5486 if (GC_L == Qualifiers::Strong)
5487 return LHS;
5488 if (GC_R == Qualifiers::Strong)
5489 return RHS;
5490 return QualType();
5491 }
5492
5493 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5494 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5495 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5496 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5497 if (ResQT == LHSBaseQT)
5498 return LHS;
5499 if (ResQT == RHSBaseQT)
5500 return RHS;
5501 }
5502 return QualType();
5503}
5504
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005505//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005506// Integer Predicates
5507//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005508
Jay Foad39c79802011-01-12 09:06:06 +00005509unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005510 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005511 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005512 if (T->isBooleanType())
5513 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005514 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005515 return (unsigned)getTypeSize(T);
5516}
5517
5518QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005519 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005520
5521 // Turn <4 x signed int> -> <4 x unsigned int>
5522 if (const VectorType *VTy = T->getAs<VectorType>())
5523 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005524 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005525
5526 // For enums, we return the unsigned version of the base type.
5527 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005528 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005529
5530 const BuiltinType *BTy = T->getAs<BuiltinType>();
5531 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005532 switch (BTy->getKind()) {
5533 case BuiltinType::Char_S:
5534 case BuiltinType::SChar:
5535 return UnsignedCharTy;
5536 case BuiltinType::Short:
5537 return UnsignedShortTy;
5538 case BuiltinType::Int:
5539 return UnsignedIntTy;
5540 case BuiltinType::Long:
5541 return UnsignedLongTy;
5542 case BuiltinType::LongLong:
5543 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005544 case BuiltinType::Int128:
5545 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005546 default:
5547 assert(0 && "Unexpected signed integer type");
5548 return QualType();
5549 }
5550}
5551
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005552ExternalASTSource::~ExternalASTSource() { }
5553
5554void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00005555
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005556ASTMutationListener::~ASTMutationListener() { }
5557
Chris Lattnerecd79c62009-06-14 00:45:47 +00005558
5559//===----------------------------------------------------------------------===//
5560// Builtin Type Computation
5561//===----------------------------------------------------------------------===//
5562
5563/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005564/// pointer over the consumed characters. This returns the resultant type. If
5565/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5566/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5567/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005568///
5569/// RequiresICE is filled in on return to indicate whether the value is required
5570/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005571static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005572 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005573 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005574 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005575 // Modifiers.
5576 int HowLong = 0;
5577 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005578 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005579
Chris Lattnerdc226c22010-10-01 22:42:38 +00005580 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005581 bool Done = false;
5582 while (!Done) {
5583 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005584 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005585 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005586 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005587 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005588 case 'S':
5589 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5590 assert(!Signed && "Can't use 'S' modifier multiple times!");
5591 Signed = true;
5592 break;
5593 case 'U':
5594 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5595 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5596 Unsigned = true;
5597 break;
5598 case 'L':
5599 assert(HowLong <= 2 && "Can't have LLLL modifier");
5600 ++HowLong;
5601 break;
5602 }
5603 }
5604
5605 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005606
Chris Lattnerecd79c62009-06-14 00:45:47 +00005607 // Read the base type.
5608 switch (*Str++) {
5609 default: assert(0 && "Unknown builtin type letter!");
5610 case 'v':
5611 assert(HowLong == 0 && !Signed && !Unsigned &&
5612 "Bad modifiers used with 'v'!");
5613 Type = Context.VoidTy;
5614 break;
5615 case 'f':
5616 assert(HowLong == 0 && !Signed && !Unsigned &&
5617 "Bad modifiers used with 'f'!");
5618 Type = Context.FloatTy;
5619 break;
5620 case 'd':
5621 assert(HowLong < 2 && !Signed && !Unsigned &&
5622 "Bad modifiers used with 'd'!");
5623 if (HowLong)
5624 Type = Context.LongDoubleTy;
5625 else
5626 Type = Context.DoubleTy;
5627 break;
5628 case 's':
5629 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5630 if (Unsigned)
5631 Type = Context.UnsignedShortTy;
5632 else
5633 Type = Context.ShortTy;
5634 break;
5635 case 'i':
5636 if (HowLong == 3)
5637 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5638 else if (HowLong == 2)
5639 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5640 else if (HowLong == 1)
5641 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5642 else
5643 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5644 break;
5645 case 'c':
5646 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5647 if (Signed)
5648 Type = Context.SignedCharTy;
5649 else if (Unsigned)
5650 Type = Context.UnsignedCharTy;
5651 else
5652 Type = Context.CharTy;
5653 break;
5654 case 'b': // boolean
5655 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5656 Type = Context.BoolTy;
5657 break;
5658 case 'z': // size_t.
5659 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5660 Type = Context.getSizeType();
5661 break;
5662 case 'F':
5663 Type = Context.getCFConstantStringType();
5664 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005665 case 'G':
5666 Type = Context.getObjCIdType();
5667 break;
5668 case 'H':
5669 Type = Context.getObjCSelType();
5670 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005671 case 'a':
5672 Type = Context.getBuiltinVaListType();
5673 assert(!Type.isNull() && "builtin va list type not initialized!");
5674 break;
5675 case 'A':
5676 // This is a "reference" to a va_list; however, what exactly
5677 // this means depends on how va_list is defined. There are two
5678 // different kinds of va_list: ones passed by value, and ones
5679 // passed by reference. An example of a by-value va_list is
5680 // x86, where va_list is a char*. An example of by-ref va_list
5681 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5682 // we want this argument to be a char*&; for x86-64, we want
5683 // it to be a __va_list_tag*.
5684 Type = Context.getBuiltinVaListType();
5685 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005686 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005687 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005688 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005689 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005690 break;
5691 case 'V': {
5692 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005693 unsigned NumElements = strtoul(Str, &End, 10);
5694 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005695 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005696
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005697 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5698 RequiresICE, false);
5699 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005700
5701 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005702 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005703 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005704 break;
5705 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005706 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005707 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5708 false);
5709 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005710 Type = Context.getComplexType(ElementType);
5711 break;
5712 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005713 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005714 Type = Context.getFILEType();
5715 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005716 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005717 return QualType();
5718 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005719 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005720 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005721 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005722 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005723 else
5724 Type = Context.getjmp_bufType();
5725
Mike Stump2adb4da2009-07-28 23:47:15 +00005726 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005727 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005728 return QualType();
5729 }
5730 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005731 }
Mike Stump11289f42009-09-09 15:08:12 +00005732
Chris Lattnerdc226c22010-10-01 22:42:38 +00005733 // If there are modifiers and if we're allowed to parse them, go for it.
5734 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005735 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005736 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005737 default: Done = true; --Str; break;
5738 case '*':
5739 case '&': {
5740 // Both pointers and references can have their pointee types
5741 // qualified with an address space.
5742 char *End;
5743 unsigned AddrSpace = strtoul(Str, &End, 10);
5744 if (End != Str && AddrSpace != 0) {
5745 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5746 Str = End;
5747 }
5748 if (c == '*')
5749 Type = Context.getPointerType(Type);
5750 else
5751 Type = Context.getLValueReferenceType(Type);
5752 break;
5753 }
5754 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5755 case 'C':
5756 Type = Type.withConst();
5757 break;
5758 case 'D':
5759 Type = Context.getVolatileType(Type);
5760 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005761 }
5762 }
Chris Lattner84733392010-10-01 07:13:18 +00005763
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005764 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005765 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005766
Chris Lattnerecd79c62009-06-14 00:45:47 +00005767 return Type;
5768}
5769
5770/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005771QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005772 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005773 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005774 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005775
Chris Lattnerecd79c62009-06-14 00:45:47 +00005776 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005777
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005778 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005779 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005780 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5781 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005782 if (Error != GE_None)
5783 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005784
5785 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5786
Chris Lattnerecd79c62009-06-14 00:45:47 +00005787 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005788 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005789 if (Error != GE_None)
5790 return QualType();
5791
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005792 // If this argument is required to be an IntegerConstantExpression and the
5793 // caller cares, fill in the bitmask we return.
5794 if (RequiresICE && IntegerConstantArgs)
5795 *IntegerConstantArgs |= 1 << ArgTypes.size();
5796
Chris Lattnerecd79c62009-06-14 00:45:47 +00005797 // Do array -> pointer decay. The builtin should use the decayed type.
5798 if (Ty->isArrayType())
5799 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005800
Chris Lattnerecd79c62009-06-14 00:45:47 +00005801 ArgTypes.push_back(Ty);
5802 }
5803
5804 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5805 "'.' should only occur at end of builtin type list!");
5806
John McCall991eb4b2010-12-21 00:44:39 +00005807 FunctionType::ExtInfo EI;
5808 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5809
5810 bool Variadic = (TypeStr[0] == '.');
5811
5812 // We really shouldn't be making a no-proto type here, especially in C++.
5813 if (ArgTypes.empty() && Variadic)
5814 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005815
John McCalldb40c7f2010-12-14 08:05:40 +00005816 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005817 EPI.ExtInfo = EI;
5818 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00005819
5820 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005821}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005822
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005823GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5824 GVALinkage External = GVA_StrongExternal;
5825
5826 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005827 switch (L) {
5828 case NoLinkage:
5829 case InternalLinkage:
5830 case UniqueExternalLinkage:
5831 return GVA_Internal;
5832
5833 case ExternalLinkage:
5834 switch (FD->getTemplateSpecializationKind()) {
5835 case TSK_Undeclared:
5836 case TSK_ExplicitSpecialization:
5837 External = GVA_StrongExternal;
5838 break;
5839
5840 case TSK_ExplicitInstantiationDefinition:
5841 return GVA_ExplicitTemplateInstantiation;
5842
5843 case TSK_ExplicitInstantiationDeclaration:
5844 case TSK_ImplicitInstantiation:
5845 External = GVA_TemplateInstantiation;
5846 break;
5847 }
5848 }
5849
5850 if (!FD->isInlined())
5851 return External;
5852
5853 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5854 // GNU or C99 inline semantics. Determine whether this symbol should be
5855 // externally visible.
5856 if (FD->isInlineDefinitionExternallyVisible())
5857 return External;
5858
5859 // C99 inline semantics, where the symbol is not externally visible.
5860 return GVA_C99Inline;
5861 }
5862
5863 // C++0x [temp.explicit]p9:
5864 // [ Note: The intent is that an inline function that is the subject of
5865 // an explicit instantiation declaration will still be implicitly
5866 // instantiated when used so that the body can be considered for
5867 // inlining, but that no out-of-line copy of the inline function would be
5868 // generated in the translation unit. -- end note ]
5869 if (FD->getTemplateSpecializationKind()
5870 == TSK_ExplicitInstantiationDeclaration)
5871 return GVA_C99Inline;
5872
5873 return GVA_CXXInline;
5874}
5875
5876GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5877 // If this is a static data member, compute the kind of template
5878 // specialization. Otherwise, this variable is not part of a
5879 // template.
5880 TemplateSpecializationKind TSK = TSK_Undeclared;
5881 if (VD->isStaticDataMember())
5882 TSK = VD->getTemplateSpecializationKind();
5883
5884 Linkage L = VD->getLinkage();
5885 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5886 VD->getType()->getLinkage() == UniqueExternalLinkage)
5887 L = UniqueExternalLinkage;
5888
5889 switch (L) {
5890 case NoLinkage:
5891 case InternalLinkage:
5892 case UniqueExternalLinkage:
5893 return GVA_Internal;
5894
5895 case ExternalLinkage:
5896 switch (TSK) {
5897 case TSK_Undeclared:
5898 case TSK_ExplicitSpecialization:
5899 return GVA_StrongExternal;
5900
5901 case TSK_ExplicitInstantiationDeclaration:
5902 llvm_unreachable("Variable should not be instantiated");
5903 // Fall through to treat this like any other instantiation.
5904
5905 case TSK_ExplicitInstantiationDefinition:
5906 return GVA_ExplicitTemplateInstantiation;
5907
5908 case TSK_ImplicitInstantiation:
5909 return GVA_TemplateInstantiation;
5910 }
5911 }
5912
5913 return GVA_StrongExternal;
5914}
5915
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005916bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005917 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5918 if (!VD->isFileVarDecl())
5919 return false;
5920 } else if (!isa<FunctionDecl>(D))
5921 return false;
5922
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005923 // Weak references don't produce any output by themselves.
5924 if (D->hasAttr<WeakRefAttr>())
5925 return false;
5926
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005927 // Aliases and used decls are required.
5928 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5929 return true;
5930
5931 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5932 // Forward declarations aren't required.
5933 if (!FD->isThisDeclarationADefinition())
5934 return false;
5935
5936 // Constructors and destructors are required.
5937 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5938 return true;
5939
5940 // The key function for a class is required.
5941 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5942 const CXXRecordDecl *RD = MD->getParent();
5943 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5944 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5945 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5946 return true;
5947 }
5948 }
5949
5950 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5951
5952 // static, static inline, always_inline, and extern inline functions can
5953 // always be deferred. Normal inline functions can be deferred in C99/C++.
5954 // Implicit template instantiations can also be deferred in C++.
5955 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5956 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5957 return false;
5958 return true;
5959 }
5960
5961 const VarDecl *VD = cast<VarDecl>(D);
5962 assert(VD->isFileVarDecl() && "Expected file scoped var");
5963
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005964 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5965 return false;
5966
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005967 // Structs that have non-trivial constructors or destructors are required.
5968
5969 // FIXME: Handle references.
5970 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5971 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00005972 if (RD->hasDefinition() &&
5973 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005974 return true;
5975 }
5976 }
5977
5978 GVALinkage L = GetGVALinkageForVariable(VD);
5979 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5980 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5981 return false;
5982 }
5983
5984 return true;
5985}
Charles Davis53c59df2010-08-16 03:33:14 +00005986
Charles Davis99202b32010-11-09 18:04:24 +00005987CallingConv ASTContext::getDefaultMethodCallConv() {
5988 // Pass through to the C++ ABI object
5989 return ABI->getDefaultMethodCallConv();
5990}
5991
Jay Foad39c79802011-01-12 09:06:06 +00005992bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00005993 // Pass through to the C++ ABI object
5994 return ABI->isNearlyEmpty(RD);
5995}
5996
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00005997MangleContext *ASTContext::createMangleContext() {
5998 switch (Target.getCXXABI()) {
5999 case CXXABI_ARM:
6000 case CXXABI_Itanium:
6001 return createItaniumMangleContext(*this, getDiagnostics());
6002 case CXXABI_Microsoft:
6003 return createMicrosoftMangleContext(*this, getDiagnostics());
6004 }
6005 assert(0 && "Unsupported ABI");
6006 return 0;
6007}
6008
Charles Davis53c59df2010-08-16 03:33:14 +00006009CXXABI::~CXXABI() {}