blob: d20c25851e17cc7c0035c06de5a4f406f5fb2523 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Charles Davis53c59df2010-08-16 03:33:14 +000033#include "CXXABI.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000034
Chris Lattnerddc135e2006-11-10 06:34:16 +000035using namespace clang;
36
Douglas Gregor9672f922010-07-03 00:47:00 +000037unsigned ASTContext::NumImplicitDefaultConstructors;
38unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000039unsigned ASTContext::NumImplicitCopyConstructors;
40unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000041unsigned ASTContext::NumImplicitCopyAssignmentOperators;
42unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000043unsigned ASTContext::NumImplicitDestructors;
44unsigned ASTContext::NumImplicitDestructorsDeclared;
45
Steve Naroff0af91202007-04-27 21:51:21 +000046enum FloatingRank {
47 FloatRank, DoubleRank, LongDoubleRank
48};
49
Douglas Gregor7dbfb462010-06-16 21:09:37 +000050void
51ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
52 TemplateTemplateParmDecl *Parm) {
53 ID.AddInteger(Parm->getDepth());
54 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000055 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000056
57 TemplateParameterList *Params = Parm->getTemplateParameters();
58 ID.AddInteger(Params->size());
59 for (TemplateParameterList::const_iterator P = Params->begin(),
60 PEnd = Params->end();
61 P != PEnd; ++P) {
62 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
63 ID.AddInteger(0);
64 ID.AddBoolean(TTP->isParameterPack());
65 continue;
66 }
67
68 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
69 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000070 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000071 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +000072 if (NTTP->isExpandedParameterPack()) {
73 ID.AddBoolean(true);
74 ID.AddInteger(NTTP->getNumExpansionTypes());
75 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
76 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
77 } else
78 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +000079 continue;
80 }
81
82 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
83 ID.AddInteger(2);
84 Profile(ID, TTP);
85 }
86}
87
88TemplateTemplateParmDecl *
89ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000090 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000091 // Check if we already have a canonical template template parameter.
92 llvm::FoldingSetNodeID ID;
93 CanonicalTemplateTemplateParm::Profile(ID, TTP);
94 void *InsertPos = 0;
95 CanonicalTemplateTemplateParm *Canonical
96 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
97 if (Canonical)
98 return Canonical->getParam();
99
100 // Build a canonical template parameter list.
101 TemplateParameterList *Params = TTP->getTemplateParameters();
102 llvm::SmallVector<NamedDecl *, 4> CanonParams;
103 CanonParams.reserve(Params->size());
104 for (TemplateParameterList::const_iterator P = Params->begin(),
105 PEnd = Params->end();
106 P != PEnd; ++P) {
107 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
108 CanonParams.push_back(
109 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000110 SourceLocation(),
111 SourceLocation(),
112 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000113 TTP->getIndex(), 0, false,
114 TTP->isParameterPack()));
115 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000116 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
117 QualType T = getCanonicalType(NTTP->getType());
118 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
119 NonTypeTemplateParmDecl *Param;
120 if (NTTP->isExpandedParameterPack()) {
121 llvm::SmallVector<QualType, 2> ExpandedTypes;
122 llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
123 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
124 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
125 ExpandedTInfos.push_back(
126 getTrivialTypeSourceInfo(ExpandedTypes.back()));
127 }
128
129 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000130 SourceLocation(),
131 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000132 NTTP->getDepth(),
133 NTTP->getPosition(), 0,
134 T,
135 TInfo,
136 ExpandedTypes.data(),
137 ExpandedTypes.size(),
138 ExpandedTInfos.data());
139 } else {
140 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000141 SourceLocation(),
142 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000143 NTTP->getDepth(),
144 NTTP->getPosition(), 0,
145 T,
146 NTTP->isParameterPack(),
147 TInfo);
148 }
149 CanonParams.push_back(Param);
150
151 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000152 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
153 cast<TemplateTemplateParmDecl>(*P)));
154 }
155
156 TemplateTemplateParmDecl *CanonTTP
157 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
158 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000159 TTP->getPosition(),
160 TTP->isParameterPack(),
161 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000162 TemplateParameterList::Create(*this, SourceLocation(),
163 SourceLocation(),
164 CanonParams.data(),
165 CanonParams.size(),
166 SourceLocation()));
167
168 // Get the new insert position for the node we care about.
169 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
170 assert(Canonical == 0 && "Shouldn't be in the map!");
171 (void)Canonical;
172
173 // Create the canonical template template parameter entry.
174 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
175 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
176 return CanonTTP;
177}
178
Charles Davis53c59df2010-08-16 03:33:14 +0000179CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000180 if (!LangOpts.CPlusPlus) return 0;
181
Charles Davis6bcb07a2010-08-19 02:18:14 +0000182 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000183 case CXXABI_ARM:
184 return CreateARMCXXABI(*this);
185 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000186 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000187 case CXXABI_Microsoft:
188 return CreateMicrosoftCXXABI(*this);
189 }
John McCall86353412010-08-21 22:46:04 +0000190 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000191}
192
Chris Lattner465fa322008-10-05 17:34:18 +0000193ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000194 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000195 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000196 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000197 unsigned size_reserve) :
Sebastian Redl31ad7542011-03-13 17:09:40 +0000198 FunctionProtoTypes(this_()),
John McCall773cc982010-06-11 11:07:21 +0000199 TemplateSpecializationTypes(this_()),
200 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000201 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
202 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000203 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000204 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +0000205 cudaConfigureCallDecl(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000206 NullTypeSourceInfo(QualType()),
Charles Davis53c59df2010-08-16 03:33:14 +0000207 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000208 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000209 BuiltinInfo(builtins),
210 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000211 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000212 LastSDM(0, 0),
John McCall147d0212011-02-22 22:38:33 +0000213 UniqueBlockByRefTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000214 ObjCIdRedefinitionType = QualType();
215 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000216 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000217 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000218 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000219 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000220}
221
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000222ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000223 // Release the DenseMaps associated with DeclContext objects.
224 // FIXME: Is this the ideal solution?
225 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000226
Douglas Gregor5b11d492010-07-25 17:53:33 +0000227 // Call all of the deallocation functions.
228 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
229 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000230
Douglas Gregor832940b2010-03-02 23:58:15 +0000231 // Release all of the memory associated with overridden C++ methods.
232 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
233 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
234 OM != OMEnd; ++OM)
235 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000236
Ted Kremenek076baeb2010-06-08 23:00:58 +0000237 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000238 // because they can contain DenseMaps.
239 for (llvm::DenseMap<const ObjCContainerDecl*,
240 const ASTRecordLayout*>::iterator
241 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
242 // Increment in loop to prevent using deallocated memory.
243 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
244 R->Destroy(*this);
245
Ted Kremenek076baeb2010-06-08 23:00:58 +0000246 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
247 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
248 // Increment in loop to prevent using deallocated memory.
249 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
250 R->Destroy(*this);
251 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000252
253 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
254 AEnd = DeclAttrs.end();
255 A != AEnd; ++A)
256 A->second->~AttrVec();
257}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000258
Douglas Gregor1a809332010-05-23 18:26:36 +0000259void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
260 Deallocations.push_back(std::make_pair(Callback, Data));
261}
262
Mike Stump11289f42009-09-09 15:08:12 +0000263void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000264ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
265 ExternalSource.reset(Source.take());
266}
267
Chris Lattner4eb445d2007-01-26 01:27:23 +0000268void ASTContext::PrintStats() const {
269 fprintf(stderr, "*** AST Context Stats:\n");
270 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000271
Douglas Gregora30d0462009-05-26 14:40:08 +0000272 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000273#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000274#define ABSTRACT_TYPE(Name, Parent)
275#include "clang/AST/TypeNodes.def"
276 0 // Extra
277 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000278
Chris Lattner4eb445d2007-01-26 01:27:23 +0000279 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
280 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000281 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000282 }
283
Douglas Gregora30d0462009-05-26 14:40:08 +0000284 unsigned Idx = 0;
285 unsigned TotalBytes = 0;
286#define TYPE(Name, Parent) \
287 if (counts[Idx]) \
288 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
289 TotalBytes += counts[Idx] * sizeof(Name##Type); \
290 ++Idx;
291#define ABSTRACT_TYPE(Name, Parent)
292#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000293
Douglas Gregora30d0462009-05-26 14:40:08 +0000294 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000295
Douglas Gregor7454c562010-07-02 20:37:36 +0000296 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000297 fprintf(stderr, " %u/%u implicit default constructors created\n",
298 NumImplicitDefaultConstructorsDeclared,
299 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000300 fprintf(stderr, " %u/%u implicit copy constructors created\n",
301 NumImplicitCopyConstructorsDeclared,
302 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000303 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
304 NumImplicitCopyAssignmentOperatorsDeclared,
305 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000306 fprintf(stderr, " %u/%u implicit destructors created\n",
307 NumImplicitDestructorsDeclared, NumImplicitDestructors);
308
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000309 if (ExternalSource.get()) {
310 fprintf(stderr, "\n");
311 ExternalSource->PrintStats();
312 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000313
Douglas Gregor5b11d492010-07-25 17:53:33 +0000314 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000315}
316
317
John McCall48f2d582009-10-23 23:03:21 +0000318void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000319 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000320 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000321 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000322}
323
Chris Lattner970e54e2006-11-12 00:37:36 +0000324void ASTContext::InitBuiltinTypes() {
325 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000326
Chris Lattner970e54e2006-11-12 00:37:36 +0000327 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000328 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000329
Chris Lattner970e54e2006-11-12 00:37:36 +0000330 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000331 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000332 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000333 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000334 InitBuiltinType(CharTy, BuiltinType::Char_S);
335 else
336 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000337 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000338 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
339 InitBuiltinType(ShortTy, BuiltinType::Short);
340 InitBuiltinType(IntTy, BuiltinType::Int);
341 InitBuiltinType(LongTy, BuiltinType::Long);
342 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000343
Chris Lattner970e54e2006-11-12 00:37:36 +0000344 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000345 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
346 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
347 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
348 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
349 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000350
Chris Lattner970e54e2006-11-12 00:37:36 +0000351 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000352 InitBuiltinType(FloatTy, BuiltinType::Float);
353 InitBuiltinType(DoubleTy, BuiltinType::Double);
354 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000355
Chris Lattnerf122cef2009-04-30 02:43:43 +0000356 // GNU extension, 128-bit integers.
357 InitBuiltinType(Int128Ty, BuiltinType::Int128);
358 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
359
Chris Lattnerad3467e2010-12-25 23:25:43 +0000360 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
361 if (!LangOpts.ShortWChar)
362 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
363 else // -fshort-wchar makes wchar_t be unsigned.
364 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
365 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000366 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000367
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000368 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
369 InitBuiltinType(Char16Ty, BuiltinType::Char16);
370 else // C99
371 Char16Ty = getFromTargetType(Target.getChar16Type());
372
373 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
374 InitBuiltinType(Char32Ty, BuiltinType::Char32);
375 else // C99
376 Char32Ty = getFromTargetType(Target.getChar32Type());
377
Douglas Gregor4619e432008-12-05 23:32:09 +0000378 // Placeholder type for type-dependent expressions whose type is
379 // completely unknown. No code should ever check a type against
380 // DependentTy and users should never see it; however, it is here to
381 // help diagnose failures to properly check for type-dependent
382 // expressions.
383 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000384
John McCall36e7fe32010-10-12 00:20:44 +0000385 // Placeholder type for functions.
386 InitBuiltinType(OverloadTy, BuiltinType::Overload);
387
Chris Lattner970e54e2006-11-12 00:37:36 +0000388 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000389 FloatComplexTy = getComplexType(FloatTy);
390 DoubleComplexTy = getComplexType(DoubleTy);
391 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000392
Steve Naroff66e9f332007-10-15 14:41:52 +0000393 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000394
Steve Naroff1329fa02009-07-15 18:40:39 +0000395 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
396 ObjCIdTypedefType = QualType();
397 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000398 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000399
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000400 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000401 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
402 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000403 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000404
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000405 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000406
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000407 // void * type
408 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000409
410 // nullptr type (C++0x 2.14.7)
411 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000412}
413
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000414Diagnostic &ASTContext::getDiagnostics() const {
415 return SourceMgr.getDiagnostics();
416}
417
Douglas Gregor561eceb2010-08-30 16:49:28 +0000418AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
419 AttrVec *&Result = DeclAttrs[D];
420 if (!Result) {
421 void *Mem = Allocate(sizeof(AttrVec));
422 Result = new (Mem) AttrVec;
423 }
424
425 return *Result;
426}
427
428/// \brief Erase the attributes corresponding to the given declaration.
429void ASTContext::eraseDeclAttrs(const Decl *D) {
430 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
431 if (Pos != DeclAttrs.end()) {
432 Pos->second->~AttrVec();
433 DeclAttrs.erase(Pos);
434 }
435}
436
437
Douglas Gregor86d142a2009-10-08 07:24:58 +0000438MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000439ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000440 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000441 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000442 = InstantiatedFromStaticDataMember.find(Var);
443 if (Pos == InstantiatedFromStaticDataMember.end())
444 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000445
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000446 return Pos->second;
447}
448
Mike Stump11289f42009-09-09 15:08:12 +0000449void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000450ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000451 TemplateSpecializationKind TSK,
452 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000453 assert(Inst->isStaticDataMember() && "Not a static data member");
454 assert(Tmpl->isStaticDataMember() && "Not a static data member");
455 assert(!InstantiatedFromStaticDataMember[Inst] &&
456 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000457 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000458 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000459}
460
John McCalle61f2ba2009-11-18 02:36:19 +0000461NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000462ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000463 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000464 = InstantiatedFromUsingDecl.find(UUD);
465 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000466 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000467
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000468 return Pos->second;
469}
470
471void
John McCallb96ec562009-12-04 22:46:56 +0000472ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
473 assert((isa<UsingDecl>(Pattern) ||
474 isa<UnresolvedUsingValueDecl>(Pattern) ||
475 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
476 "pattern decl is not a using decl");
477 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
478 InstantiatedFromUsingDecl[Inst] = Pattern;
479}
480
481UsingShadowDecl *
482ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
483 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
484 = InstantiatedFromUsingShadowDecl.find(Inst);
485 if (Pos == InstantiatedFromUsingShadowDecl.end())
486 return 0;
487
488 return Pos->second;
489}
490
491void
492ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
493 UsingShadowDecl *Pattern) {
494 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
495 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000496}
497
Anders Carlsson5da84842009-09-01 04:26:58 +0000498FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
499 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
500 = InstantiatedFromUnnamedFieldDecl.find(Field);
501 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
502 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000503
Anders Carlsson5da84842009-09-01 04:26:58 +0000504 return Pos->second;
505}
506
507void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
508 FieldDecl *Tmpl) {
509 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
510 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
511 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
512 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000513
Anders Carlsson5da84842009-09-01 04:26:58 +0000514 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
515}
516
Douglas Gregor832940b2010-03-02 23:58:15 +0000517ASTContext::overridden_cxx_method_iterator
518ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
519 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
520 = OverriddenMethods.find(Method);
521 if (Pos == OverriddenMethods.end())
522 return 0;
523
524 return Pos->second.begin();
525}
526
527ASTContext::overridden_cxx_method_iterator
528ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
529 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
530 = OverriddenMethods.find(Method);
531 if (Pos == OverriddenMethods.end())
532 return 0;
533
534 return Pos->second.end();
535}
536
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000537unsigned
538ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
539 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
540 = OverriddenMethods.find(Method);
541 if (Pos == OverriddenMethods.end())
542 return 0;
543
544 return Pos->second.size();
545}
546
Douglas Gregor832940b2010-03-02 23:58:15 +0000547void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
548 const CXXMethodDecl *Overridden) {
549 OverriddenMethods[Method].push_back(Overridden);
550}
551
Chris Lattner53cfe802007-07-18 17:52:12 +0000552//===----------------------------------------------------------------------===//
553// Type Sizing and Analysis
554//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000555
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000556/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
557/// scalar floating point type.
558const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000559 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000560 assert(BT && "Not a floating point type!");
561 switch (BT->getKind()) {
562 default: assert(0 && "Not a floating point type!");
563 case BuiltinType::Float: return Target.getFloatFormat();
564 case BuiltinType::Double: return Target.getDoubleFormat();
565 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
566 }
567}
568
Ken Dyck160146e2010-01-27 17:10:57 +0000569/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000570/// specified decl. Note that bitfields do not have a valid alignment, so
571/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000572/// If @p RefAsPointee, references are treated like their underlying type
573/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000574CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000575 unsigned Align = Target.getCharWidth();
576
John McCall94268702010-10-08 18:24:19 +0000577 bool UseAlignAttrOnly = false;
578 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
579 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000580
John McCall94268702010-10-08 18:24:19 +0000581 // __attribute__((aligned)) can increase or decrease alignment
582 // *except* on a struct or struct member, where it only increases
583 // alignment unless 'packed' is also specified.
584 //
585 // It is an error for [[align]] to decrease alignment, so we can
586 // ignore that possibility; Sema should diagnose it.
587 if (isa<FieldDecl>(D)) {
588 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
589 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
590 } else {
591 UseAlignAttrOnly = true;
592 }
593 }
594
John McCall4e819612011-01-20 07:57:12 +0000595 // If we're using the align attribute only, just ignore everything
596 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000597 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000598 // do nothing
599
John McCall94268702010-10-08 18:24:19 +0000600 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000601 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000602 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000603 if (RefAsPointee)
604 T = RT->getPointeeType();
605 else
606 T = getPointerType(RT->getPointeeType());
607 }
608 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000609 // Adjust alignments of declarations with array type by the
610 // large-array alignment on the target.
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000611 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000612 const ArrayType *arrayType;
613 if (MinWidth && (arrayType = getAsArrayType(T))) {
614 if (isa<VariableArrayType>(arrayType))
615 Align = std::max(Align, Target.getLargeArrayAlign());
616 else if (isa<ConstantArrayType>(arrayType) &&
617 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
618 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000619
John McCall33ddac02011-01-19 10:06:00 +0000620 // Walk through any array types while we're at it.
621 T = getBaseElementType(arrayType);
622 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000623 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
624 }
John McCall4e819612011-01-20 07:57:12 +0000625
626 // Fields can be subject to extra alignment constraints, like if
627 // the field is packed, the struct is packed, or the struct has a
628 // a max-field-alignment constraint (#pragma pack). So calculate
629 // the actual alignment of the field within the struct, and then
630 // (as we're expected to) constrain that by the alignment of the type.
631 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
632 // So calculate the alignment of the field.
633 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
634
635 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000636 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000637
638 // Use the GCD of that and the offset within the record.
639 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
640 if (offset > 0) {
641 // Alignment is always a power of 2, so the GCD will be a power of 2,
642 // which means we get to do this crazy thing instead of Euclid's.
643 uint64_t lowBitOfOffset = offset & (~offset + 1);
644 if (lowBitOfOffset < fieldAlign)
645 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
646 }
647
648 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000649 }
Chris Lattner68061312009-01-24 21:53:27 +0000650 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000651
Ken Dyckcc56c542011-01-15 18:38:59 +0000652 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000653}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000654
John McCall87fe5d52010-05-20 01:18:31 +0000655std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000656ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000657 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000658 return std::make_pair(toCharUnitsFromBits(Info.first),
659 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000660}
661
662std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000663ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000664 return getTypeInfoInChars(T.getTypePtr());
665}
666
Chris Lattner983a8bb2007-07-13 22:13:22 +0000667/// getTypeSize - Return the size of the specified type, in bits. This method
668/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000669///
670/// FIXME: Pointers into different addr spaces could have different sizes and
671/// alignment requirements: getPointerInfo should take an AddrSpace, this
672/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000673std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000674ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000675 uint64_t Width=0;
676 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000677 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000678#define TYPE(Class, Base)
679#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000680#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000681#define DEPENDENT_TYPE(Class, Base) case Type::Class:
682#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000683 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000684 break;
685
Chris Lattner355332d2007-07-13 22:27:08 +0000686 case Type::FunctionNoProto:
687 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000688 // GCC extension: alignof(function) = 32 bits
689 Width = 0;
690 Align = 32;
691 break;
692
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000693 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000694 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000695 Width = 0;
696 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
697 break;
698
Steve Naroff5c131802007-08-30 01:06:46 +0000699 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000700 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000701
Chris Lattner37e05872008-03-05 18:54:05 +0000702 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000703 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000704 Align = EltInfo.second;
705 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000706 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000707 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000708 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000709 const VectorType *VT = cast<VectorType>(T);
710 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
711 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000712 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000713 // If the alignment is not a power of 2, round up to the next power of 2.
714 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000715 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000716 Align = llvm::NextPowerOf2(Align);
717 Width = llvm::RoundUpToAlignment(Width, Align);
718 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000719 break;
720 }
Chris Lattner647fb222007-07-18 18:26:58 +0000721
Chris Lattner7570e9c2008-03-08 08:52:55 +0000722 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000723 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000724 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000725 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000726 // GCC extension: alignof(void) = 8 bits.
727 Width = 0;
728 Align = 8;
729 break;
730
Chris Lattner6a4f7452007-12-19 19:23:28 +0000731 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000732 Width = Target.getBoolWidth();
733 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000734 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000735 case BuiltinType::Char_S:
736 case BuiltinType::Char_U:
737 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000738 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000739 Width = Target.getCharWidth();
740 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000741 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000742 case BuiltinType::WChar_S:
743 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000744 Width = Target.getWCharWidth();
745 Align = Target.getWCharAlign();
746 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000747 case BuiltinType::Char16:
748 Width = Target.getChar16Width();
749 Align = Target.getChar16Align();
750 break;
751 case BuiltinType::Char32:
752 Width = Target.getChar32Width();
753 Align = Target.getChar32Align();
754 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000755 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000756 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000757 Width = Target.getShortWidth();
758 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000759 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000760 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000761 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000762 Width = Target.getIntWidth();
763 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000764 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000765 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000766 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000767 Width = Target.getLongWidth();
768 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000769 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000770 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000771 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000772 Width = Target.getLongLongWidth();
773 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000774 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000775 case BuiltinType::Int128:
776 case BuiltinType::UInt128:
777 Width = 128;
778 Align = 128; // int128_t is 128-bit aligned on all targets.
779 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000780 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000781 Width = Target.getFloatWidth();
782 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000783 break;
784 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000785 Width = Target.getDoubleWidth();
786 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000787 break;
788 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000789 Width = Target.getLongDoubleWidth();
790 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000791 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000792 case BuiltinType::NullPtr:
793 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
794 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000795 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000796 case BuiltinType::ObjCId:
797 case BuiltinType::ObjCClass:
798 case BuiltinType::ObjCSel:
799 Width = Target.getPointerWidth(0);
800 Align = Target.getPointerAlign(0);
801 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000802 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000803 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000804 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000805 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000806 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000807 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000808 case Type::BlockPointer: {
809 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
810 Width = Target.getPointerWidth(AS);
811 Align = Target.getPointerAlign(AS);
812 break;
813 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000814 case Type::LValueReference:
815 case Type::RValueReference: {
816 // alignof and sizeof should never enter this code path here, so we go
817 // the pointer route.
818 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
819 Width = Target.getPointerWidth(AS);
820 Align = Target.getPointerAlign(AS);
821 break;
822 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000823 case Type::Pointer: {
824 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000825 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000826 Align = Target.getPointerAlign(AS);
827 break;
828 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000829 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000830 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000831 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000832 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000833 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000834 Align = PtrDiffInfo.second;
835 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000836 }
Chris Lattner647fb222007-07-18 18:26:58 +0000837 case Type::Complex: {
838 // Complex types have the same alignment as their elements, but twice the
839 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000840 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000841 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000842 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000843 Align = EltInfo.second;
844 break;
845 }
John McCall8b07ec22010-05-15 11:32:37 +0000846 case Type::ObjCObject:
847 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000848 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000849 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000850 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000851 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000852 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000853 break;
854 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000855 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000856 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000857 const TagType *TT = cast<TagType>(T);
858
859 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000860 Width = 1;
861 Align = 1;
862 break;
863 }
Mike Stump11289f42009-09-09 15:08:12 +0000864
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000865 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000866 return getTypeInfo(ET->getDecl()->getIntegerType());
867
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000868 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000869 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000870 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000871 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +0000872 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000873 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000874
Chris Lattner63d2b362009-10-22 05:17:15 +0000875 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000876 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
877 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000878
Richard Smith30482bc2011-02-20 03:19:35 +0000879 case Type::Auto: {
880 const AutoType *A = cast<AutoType>(T);
881 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +0000882 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +0000883 }
884
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000885 case Type::Paren:
886 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
887
Douglas Gregoref462e62009-04-30 17:32:17 +0000888 case Type::Typedef: {
889 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000890 std::pair<uint64_t, unsigned> Info
891 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +0000892 // If the typedef has an aligned attribute on it, it overrides any computed
893 // alignment we have. This violates the GCC documentation (which says that
894 // attribute(aligned) can only round up) but matches its implementation.
895 if (unsigned AttrAlign = Typedef->getMaxAlignment())
896 Align = AttrAlign;
897 else
898 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +0000899 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000900 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000901 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000902
903 case Type::TypeOfExpr:
904 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
905 .getTypePtr());
906
907 case Type::TypeOf:
908 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
909
Anders Carlsson81df7b82009-06-24 19:06:50 +0000910 case Type::Decltype:
911 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
912 .getTypePtr());
913
Abramo Bagnara6150c882010-05-11 21:36:43 +0000914 case Type::Elaborated:
915 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000916
John McCall81904512011-01-06 01:58:22 +0000917 case Type::Attributed:
918 return getTypeInfo(
919 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
920
Douglas Gregoref462e62009-04-30 17:32:17 +0000921 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000922 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000923 "Cannot request the size of a dependent type");
924 // FIXME: this is likely to be wrong once we support template
925 // aliases, since a template alias could refer to a typedef that
926 // has an __aligned__ attribute on it.
927 return getTypeInfo(getCanonicalType(T));
928 }
Mike Stump11289f42009-09-09 15:08:12 +0000929
Chris Lattner53cfe802007-07-18 17:52:12 +0000930 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000931 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000932}
933
Ken Dyckcc56c542011-01-15 18:38:59 +0000934/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
935CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
936 return CharUnits::fromQuantity(BitSize / getCharWidth());
937}
938
Ken Dyckb0fcc592011-02-11 01:54:29 +0000939/// toBits - Convert a size in characters to a size in characters.
940int64_t ASTContext::toBits(CharUnits CharSize) const {
941 return CharSize.getQuantity() * getCharWidth();
942}
943
Ken Dyck8c89d592009-12-22 14:23:30 +0000944/// getTypeSizeInChars - Return the size of the specified type, in characters.
945/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000946CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000947 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000948}
Jay Foad39c79802011-01-12 09:06:06 +0000949CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000950 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000951}
952
Ken Dycka6046ab2010-01-26 17:25:18 +0000953/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000954/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000955CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000956 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000957}
Jay Foad39c79802011-01-12 09:06:06 +0000958CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000959 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000960}
961
Chris Lattnera3402cd2009-01-27 18:08:34 +0000962/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
963/// type for the current target in bits. This can be different than the ABI
964/// alignment in cases where it is beneficial for performance to overalign
965/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +0000966unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +0000967 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000968
969 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000970 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000971 T = CT->getElementType().getTypePtr();
972 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
973 T->isSpecificBuiltinType(BuiltinType::LongLong))
974 return std::max(ABIAlign, (unsigned)getTypeSize(T));
975
Chris Lattnera3402cd2009-01-27 18:08:34 +0000976 return ABIAlign;
977}
978
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000979/// ShallowCollectObjCIvars -
980/// Collect all ivars, including those synthesized, in the current class.
981///
982void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +0000983 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000984 // FIXME. This need be removed but there are two many places which
985 // assume const-ness of ObjCInterfaceDecl
986 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
987 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
988 Iv= Iv->getNextIvar())
989 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000990}
991
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000992/// DeepCollectObjCIvars -
993/// This routine first collects all declared, but not synthesized, ivars in
994/// super class and then collects all ivars, including those synthesized for
995/// current class. This routine is used for implementation of current class
996/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000997///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000998void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
999 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +00001000 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001001 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1002 DeepCollectObjCIvars(SuperClass, false, Ivars);
1003 if (!leafClass) {
1004 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1005 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001006 Ivars.push_back(*I);
1007 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001008 else
1009 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001010}
1011
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001012/// CollectInheritedProtocols - Collect all protocols in current class and
1013/// those inherited by it.
1014void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001015 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001016 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001017 // We can use protocol_iterator here instead of
1018 // all_referenced_protocol_iterator since we are walking all categories.
1019 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1020 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001021 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001022 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001023 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001024 PE = Proto->protocol_end(); P != PE; ++P) {
1025 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001026 CollectInheritedProtocols(*P, Protocols);
1027 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001028 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001029
1030 // Categories of this Interface.
1031 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1032 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1033 CollectInheritedProtocols(CDeclChain, Protocols);
1034 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1035 while (SD) {
1036 CollectInheritedProtocols(SD, Protocols);
1037 SD = SD->getSuperClass();
1038 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001039 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001040 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001041 PE = OC->protocol_end(); P != PE; ++P) {
1042 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001043 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001044 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1045 PE = Proto->protocol_end(); P != PE; ++P)
1046 CollectInheritedProtocols(*P, Protocols);
1047 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001048 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001049 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1050 PE = OP->protocol_end(); P != PE; ++P) {
1051 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001052 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001053 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1054 PE = Proto->protocol_end(); P != PE; ++P)
1055 CollectInheritedProtocols(*P, Protocols);
1056 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001057 }
1058}
1059
Jay Foad39c79802011-01-12 09:06:06 +00001060unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001061 unsigned count = 0;
1062 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001063 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1064 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001065 count += CDecl->ivar_size();
1066
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001067 // Count ivar defined in this class's implementation. This
1068 // includes synthesized ivars.
1069 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001070 count += ImplDecl->ivar_size();
1071
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001072 return count;
1073}
1074
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001075/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1076ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1077 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1078 I = ObjCImpls.find(D);
1079 if (I != ObjCImpls.end())
1080 return cast<ObjCImplementationDecl>(I->second);
1081 return 0;
1082}
1083/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1084ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1085 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1086 I = ObjCImpls.find(D);
1087 if (I != ObjCImpls.end())
1088 return cast<ObjCCategoryImplDecl>(I->second);
1089 return 0;
1090}
1091
1092/// \brief Set the implementation of ObjCInterfaceDecl.
1093void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1094 ObjCImplementationDecl *ImplD) {
1095 assert(IFaceD && ImplD && "Passed null params");
1096 ObjCImpls[IFaceD] = ImplD;
1097}
1098/// \brief Set the implementation of ObjCCategoryDecl.
1099void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1100 ObjCCategoryImplDecl *ImplD) {
1101 assert(CatD && ImplD && "Passed null params");
1102 ObjCImpls[CatD] = ImplD;
1103}
1104
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001105/// \brief Get the copy initialization expression of VarDecl,or NULL if
1106/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001107Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001108 assert(VD && "Passed null params");
1109 assert(VD->hasAttr<BlocksAttr>() &&
1110 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001111 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001112 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001113 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1114}
1115
1116/// \brief Set the copy inialization expression of a block var decl.
1117void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1118 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001119 assert(VD->hasAttr<BlocksAttr>() &&
1120 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001121 BlockVarCopyInits[VD] = Init;
1122}
1123
John McCallbcd03502009-12-07 02:54:59 +00001124/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001125///
John McCallbcd03502009-12-07 02:54:59 +00001126/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001127/// the TypeLoc wrappers.
1128///
1129/// \param T the type that will be the basis for type source info. This type
1130/// should refer to how the declarator was written in source code, not to
1131/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001132TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001133 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001134 if (!DataSize)
1135 DataSize = TypeLoc::getFullDataSizeForType(T);
1136 else
1137 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001138 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001139
John McCallbcd03502009-12-07 02:54:59 +00001140 TypeSourceInfo *TInfo =
1141 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1142 new (TInfo) TypeSourceInfo(T);
1143 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001144}
1145
John McCallbcd03502009-12-07 02:54:59 +00001146TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001147 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001148 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001149 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001150 return DI;
1151}
1152
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001153const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001154ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001155 return getObjCLayout(D, 0);
1156}
1157
1158const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001159ASTContext::getASTObjCImplementationLayout(
1160 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001161 return getObjCLayout(D->getClassInterface(), D);
1162}
1163
Chris Lattner983a8bb2007-07-13 22:13:22 +00001164//===----------------------------------------------------------------------===//
1165// Type creation/memoization methods
1166//===----------------------------------------------------------------------===//
1167
Jay Foad39c79802011-01-12 09:06:06 +00001168QualType
John McCall33ddac02011-01-19 10:06:00 +00001169ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1170 unsigned fastQuals = quals.getFastQualifiers();
1171 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001172
1173 // Check if we've already instantiated this type.
1174 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001175 ExtQuals::Profile(ID, baseType, quals);
1176 void *insertPos = 0;
1177 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1178 assert(eq->getQualifiers() == quals);
1179 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001180 }
1181
John McCall33ddac02011-01-19 10:06:00 +00001182 // If the base type is not canonical, make the appropriate canonical type.
1183 QualType canon;
1184 if (!baseType->isCanonicalUnqualified()) {
1185 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1186 canonSplit.second.addConsistentQualifiers(quals);
1187 canon = getExtQualType(canonSplit.first, canonSplit.second);
1188
1189 // Re-find the insert position.
1190 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1191 }
1192
1193 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1194 ExtQualNodes.InsertNode(eq, insertPos);
1195 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001196}
1197
Jay Foad39c79802011-01-12 09:06:06 +00001198QualType
1199ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001200 QualType CanT = getCanonicalType(T);
1201 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001202 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001203
John McCall8ccfcb52009-09-24 19:53:00 +00001204 // If we are composing extended qualifiers together, merge together
1205 // into one ExtQuals node.
1206 QualifierCollector Quals;
1207 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001208
John McCall8ccfcb52009-09-24 19:53:00 +00001209 // If this type already has an address space specified, it cannot get
1210 // another one.
1211 assert(!Quals.hasAddressSpace() &&
1212 "Type cannot be in multiple addr spaces!");
1213 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001214
John McCall8ccfcb52009-09-24 19:53:00 +00001215 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001216}
1217
Chris Lattnerd60183d2009-02-18 22:53:11 +00001218QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001219 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001220 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001221 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001222 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001223
John McCall53fa7142010-12-24 02:08:15 +00001224 if (const PointerType *ptr = T->getAs<PointerType>()) {
1225 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001226 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001227 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1228 return getPointerType(ResultType);
1229 }
1230 }
Mike Stump11289f42009-09-09 15:08:12 +00001231
John McCall8ccfcb52009-09-24 19:53:00 +00001232 // If we are composing extended qualifiers together, merge together
1233 // into one ExtQuals node.
1234 QualifierCollector Quals;
1235 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001236
John McCall8ccfcb52009-09-24 19:53:00 +00001237 // If this type already has an ObjCGC specified, it cannot get
1238 // another one.
1239 assert(!Quals.hasObjCGCAttr() &&
1240 "Type cannot have multiple ObjCGCs!");
1241 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001242
John McCall8ccfcb52009-09-24 19:53:00 +00001243 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001244}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001245
John McCall4f5019e2010-12-19 02:44:49 +00001246const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1247 FunctionType::ExtInfo Info) {
1248 if (T->getExtInfo() == Info)
1249 return T;
1250
1251 QualType Result;
1252 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1253 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1254 } else {
1255 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1256 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1257 EPI.ExtInfo = Info;
1258 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1259 FPT->getNumArgs(), EPI);
1260 }
1261
1262 return cast<FunctionType>(Result.getTypePtr());
1263}
1264
Chris Lattnerc6395932007-06-22 20:56:16 +00001265/// getComplexType - Return the uniqued reference to the type for a complex
1266/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001267QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001268 // Unique pointers, to guarantee there is only one pointer of a particular
1269 // structure.
1270 llvm::FoldingSetNodeID ID;
1271 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001272
Chris Lattnerc6395932007-06-22 20:56:16 +00001273 void *InsertPos = 0;
1274 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1275 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001276
Chris Lattnerc6395932007-06-22 20:56:16 +00001277 // If the pointee type isn't canonical, this won't be a canonical type either,
1278 // so fill in the canonical type field.
1279 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001280 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001281 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001282
Chris Lattnerc6395932007-06-22 20:56:16 +00001283 // Get the new insert position for the node we care about.
1284 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001285 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001286 }
John McCall90d1c2d2009-09-24 23:30:46 +00001287 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001288 Types.push_back(New);
1289 ComplexTypes.InsertNode(New, InsertPos);
1290 return QualType(New, 0);
1291}
1292
Chris Lattner970e54e2006-11-12 00:37:36 +00001293/// getPointerType - Return the uniqued reference to the type for a pointer to
1294/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001295QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001296 // Unique pointers, to guarantee there is only one pointer of a particular
1297 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001298 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001299 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001300
Chris Lattner67521df2007-01-27 01:29:36 +00001301 void *InsertPos = 0;
1302 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001303 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001304
Chris Lattner7ccecb92006-11-12 08:50:50 +00001305 // If the pointee type isn't canonical, this won't be a canonical type either,
1306 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001307 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001308 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001309 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001310
Chris Lattner67521df2007-01-27 01:29:36 +00001311 // Get the new insert position for the node we care about.
1312 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001313 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001314 }
John McCall90d1c2d2009-09-24 23:30:46 +00001315 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001316 Types.push_back(New);
1317 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001318 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001319}
1320
Mike Stump11289f42009-09-09 15:08:12 +00001321/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001322/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001323QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001324 assert(T->isFunctionType() && "block of function types only");
1325 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001326 // structure.
1327 llvm::FoldingSetNodeID ID;
1328 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001329
Steve Naroffec33ed92008-08-27 16:04:49 +00001330 void *InsertPos = 0;
1331 if (BlockPointerType *PT =
1332 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1333 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001334
1335 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001336 // type either so fill in the canonical type field.
1337 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001338 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001339 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001340
Steve Naroffec33ed92008-08-27 16:04:49 +00001341 // Get the new insert position for the node we care about.
1342 BlockPointerType *NewIP =
1343 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001344 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001345 }
John McCall90d1c2d2009-09-24 23:30:46 +00001346 BlockPointerType *New
1347 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001348 Types.push_back(New);
1349 BlockPointerTypes.InsertNode(New, InsertPos);
1350 return QualType(New, 0);
1351}
1352
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001353/// getLValueReferenceType - Return the uniqued reference to the type for an
1354/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001355QualType
1356ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001357 // Unique pointers, to guarantee there is only one pointer of a particular
1358 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001359 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001360 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001361
1362 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001363 if (LValueReferenceType *RT =
1364 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001365 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001366
John McCallfc93cf92009-10-22 22:37:11 +00001367 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1368
Bill Wendling3708c182007-05-27 10:15:43 +00001369 // If the referencee type isn't canonical, this won't be a canonical type
1370 // either, so fill in the canonical type field.
1371 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001372 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1373 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1374 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001375
Bill Wendling3708c182007-05-27 10:15:43 +00001376 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001377 LValueReferenceType *NewIP =
1378 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001379 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001380 }
1381
John McCall90d1c2d2009-09-24 23:30:46 +00001382 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001383 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1384 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001385 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001386 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001387
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001388 return QualType(New, 0);
1389}
1390
1391/// getRValueReferenceType - Return the uniqued reference to the type for an
1392/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001393QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001394 // Unique pointers, to guarantee there is only one pointer of a particular
1395 // structure.
1396 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001397 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001398
1399 void *InsertPos = 0;
1400 if (RValueReferenceType *RT =
1401 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1402 return QualType(RT, 0);
1403
John McCallfc93cf92009-10-22 22:37:11 +00001404 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1405
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001406 // If the referencee type isn't canonical, this won't be a canonical type
1407 // either, so fill in the canonical type field.
1408 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001409 if (InnerRef || !T.isCanonical()) {
1410 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1411 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001412
1413 // Get the new insert position for the node we care about.
1414 RValueReferenceType *NewIP =
1415 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001416 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001417 }
1418
John McCall90d1c2d2009-09-24 23:30:46 +00001419 RValueReferenceType *New
1420 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001421 Types.push_back(New);
1422 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001423 return QualType(New, 0);
1424}
1425
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001426/// getMemberPointerType - Return the uniqued reference to the type for a
1427/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001428QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001429 // Unique pointers, to guarantee there is only one pointer of a particular
1430 // structure.
1431 llvm::FoldingSetNodeID ID;
1432 MemberPointerType::Profile(ID, T, Cls);
1433
1434 void *InsertPos = 0;
1435 if (MemberPointerType *PT =
1436 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1437 return QualType(PT, 0);
1438
1439 // If the pointee or class type isn't canonical, this won't be a canonical
1440 // type either, so fill in the canonical type field.
1441 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001442 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001443 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1444
1445 // Get the new insert position for the node we care about.
1446 MemberPointerType *NewIP =
1447 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001448 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001449 }
John McCall90d1c2d2009-09-24 23:30:46 +00001450 MemberPointerType *New
1451 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001452 Types.push_back(New);
1453 MemberPointerTypes.InsertNode(New, InsertPos);
1454 return QualType(New, 0);
1455}
1456
Mike Stump11289f42009-09-09 15:08:12 +00001457/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001458/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001459QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001460 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001461 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001462 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001463 assert((EltTy->isDependentType() ||
1464 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001465 "Constant array of VLAs is illegal!");
1466
Chris Lattnere2df3f92009-05-13 04:12:56 +00001467 // Convert the array size into a canonical width matching the pointer size for
1468 // the target.
1469 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001470 ArySize =
1471 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001472
Chris Lattner23b7eb62007-06-15 23:05:46 +00001473 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001474 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001475
Chris Lattner36f8e652007-01-27 08:31:04 +00001476 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001477 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001478 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001479 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001480
John McCall33ddac02011-01-19 10:06:00 +00001481 // If the element type isn't canonical or has qualifiers, this won't
1482 // be a canonical type either, so fill in the canonical type field.
1483 QualType Canon;
1484 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1485 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1486 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001487 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001488 Canon = getQualifiedType(Canon, canonSplit.second);
1489
Chris Lattner36f8e652007-01-27 08:31:04 +00001490 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001491 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001492 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001493 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001494 }
Mike Stump11289f42009-09-09 15:08:12 +00001495
John McCall90d1c2d2009-09-24 23:30:46 +00001496 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001497 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001498 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001499 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001500 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001501}
1502
John McCall06549462011-01-18 08:40:38 +00001503/// getVariableArrayDecayedType - Turns the given type, which may be
1504/// variably-modified, into the corresponding type with all the known
1505/// sizes replaced with [*].
1506QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1507 // Vastly most common case.
1508 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001509
John McCall06549462011-01-18 08:40:38 +00001510 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001511
John McCall06549462011-01-18 08:40:38 +00001512 SplitQualType split = type.getSplitDesugaredType();
1513 const Type *ty = split.first;
1514 switch (ty->getTypeClass()) {
1515#define TYPE(Class, Base)
1516#define ABSTRACT_TYPE(Class, Base)
1517#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1518#include "clang/AST/TypeNodes.def"
1519 llvm_unreachable("didn't desugar past all non-canonical types?");
1520
1521 // These types should never be variably-modified.
1522 case Type::Builtin:
1523 case Type::Complex:
1524 case Type::Vector:
1525 case Type::ExtVector:
1526 case Type::DependentSizedExtVector:
1527 case Type::ObjCObject:
1528 case Type::ObjCInterface:
1529 case Type::ObjCObjectPointer:
1530 case Type::Record:
1531 case Type::Enum:
1532 case Type::UnresolvedUsing:
1533 case Type::TypeOfExpr:
1534 case Type::TypeOf:
1535 case Type::Decltype:
1536 case Type::DependentName:
1537 case Type::InjectedClassName:
1538 case Type::TemplateSpecialization:
1539 case Type::DependentTemplateSpecialization:
1540 case Type::TemplateTypeParm:
1541 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001542 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001543 case Type::PackExpansion:
1544 llvm_unreachable("type should never be variably-modified");
1545
1546 // These types can be variably-modified but should never need to
1547 // further decay.
1548 case Type::FunctionNoProto:
1549 case Type::FunctionProto:
1550 case Type::BlockPointer:
1551 case Type::MemberPointer:
1552 return type;
1553
1554 // These types can be variably-modified. All these modifications
1555 // preserve structure except as noted by comments.
1556 // TODO: if we ever care about optimizing VLAs, there are no-op
1557 // optimizations available here.
1558 case Type::Pointer:
1559 result = getPointerType(getVariableArrayDecayedType(
1560 cast<PointerType>(ty)->getPointeeType()));
1561 break;
1562
1563 case Type::LValueReference: {
1564 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1565 result = getLValueReferenceType(
1566 getVariableArrayDecayedType(lv->getPointeeType()),
1567 lv->isSpelledAsLValue());
1568 break;
1569 }
1570
1571 case Type::RValueReference: {
1572 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1573 result = getRValueReferenceType(
1574 getVariableArrayDecayedType(lv->getPointeeType()));
1575 break;
1576 }
1577
1578 case Type::ConstantArray: {
1579 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1580 result = getConstantArrayType(
1581 getVariableArrayDecayedType(cat->getElementType()),
1582 cat->getSize(),
1583 cat->getSizeModifier(),
1584 cat->getIndexTypeCVRQualifiers());
1585 break;
1586 }
1587
1588 case Type::DependentSizedArray: {
1589 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1590 result = getDependentSizedArrayType(
1591 getVariableArrayDecayedType(dat->getElementType()),
1592 dat->getSizeExpr(),
1593 dat->getSizeModifier(),
1594 dat->getIndexTypeCVRQualifiers(),
1595 dat->getBracketsRange());
1596 break;
1597 }
1598
1599 // Turn incomplete types into [*] types.
1600 case Type::IncompleteArray: {
1601 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1602 result = getVariableArrayType(
1603 getVariableArrayDecayedType(iat->getElementType()),
1604 /*size*/ 0,
1605 ArrayType::Normal,
1606 iat->getIndexTypeCVRQualifiers(),
1607 SourceRange());
1608 break;
1609 }
1610
1611 // Turn VLA types into [*] types.
1612 case Type::VariableArray: {
1613 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1614 result = getVariableArrayType(
1615 getVariableArrayDecayedType(vat->getElementType()),
1616 /*size*/ 0,
1617 ArrayType::Star,
1618 vat->getIndexTypeCVRQualifiers(),
1619 vat->getBracketsRange());
1620 break;
1621 }
1622 }
1623
1624 // Apply the top-level qualifiers from the original.
1625 return getQualifiedType(result, split.second);
1626}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001627
Steve Naroffcadebd02007-08-30 18:14:25 +00001628/// getVariableArrayType - Returns a non-unique reference to the type for a
1629/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001630QualType ASTContext::getVariableArrayType(QualType EltTy,
1631 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001632 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001633 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001634 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001635 // Since we don't unique expressions, it isn't possible to unique VLA's
1636 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001637 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001638
John McCall33ddac02011-01-19 10:06:00 +00001639 // Be sure to pull qualifiers off the element type.
1640 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1641 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1642 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001643 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001644 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001645 }
1646
John McCall90d1c2d2009-09-24 23:30:46 +00001647 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001648 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001649
1650 VariableArrayTypes.push_back(New);
1651 Types.push_back(New);
1652 return QualType(New, 0);
1653}
1654
Douglas Gregor4619e432008-12-05 23:32:09 +00001655/// getDependentSizedArrayType - Returns a non-unique reference to
1656/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001657/// type.
John McCall33ddac02011-01-19 10:06:00 +00001658QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1659 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001660 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001661 unsigned elementTypeQuals,
1662 SourceRange brackets) const {
1663 assert((!numElements || numElements->isTypeDependent() ||
1664 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001665 "Size must be type- or value-dependent!");
1666
John McCall33ddac02011-01-19 10:06:00 +00001667 // Dependently-sized array types that do not have a specified number
1668 // of elements will have their sizes deduced from a dependent
1669 // initializer. We do no canonicalization here at all, which is okay
1670 // because they can't be used in most locations.
1671 if (!numElements) {
1672 DependentSizedArrayType *newType
1673 = new (*this, TypeAlignment)
1674 DependentSizedArrayType(*this, elementType, QualType(),
1675 numElements, ASM, elementTypeQuals,
1676 brackets);
1677 Types.push_back(newType);
1678 return QualType(newType, 0);
1679 }
1680
1681 // Otherwise, we actually build a new type every time, but we
1682 // also build a canonical type.
1683
1684 SplitQualType canonElementType = getCanonicalType(elementType).split();
1685
1686 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001687 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001688 DependentSizedArrayType::Profile(ID, *this,
1689 QualType(canonElementType.first, 0),
1690 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001691
John McCall33ddac02011-01-19 10:06:00 +00001692 // Look for an existing type with these properties.
1693 DependentSizedArrayType *canonTy =
1694 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001695
John McCall33ddac02011-01-19 10:06:00 +00001696 // If we don't have one, build one.
1697 if (!canonTy) {
1698 canonTy = new (*this, TypeAlignment)
1699 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1700 QualType(), numElements, ASM, elementTypeQuals,
1701 brackets);
1702 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1703 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001704 }
1705
John McCall33ddac02011-01-19 10:06:00 +00001706 // Apply qualifiers from the element type to the array.
1707 QualType canon = getQualifiedType(QualType(canonTy,0),
1708 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001709
John McCall33ddac02011-01-19 10:06:00 +00001710 // If we didn't need extra canonicalization for the element type,
1711 // then just use that as our result.
1712 if (QualType(canonElementType.first, 0) == elementType)
1713 return canon;
1714
1715 // Otherwise, we need to build a type which follows the spelling
1716 // of the element type.
1717 DependentSizedArrayType *sugaredType
1718 = new (*this, TypeAlignment)
1719 DependentSizedArrayType(*this, elementType, canon, numElements,
1720 ASM, elementTypeQuals, brackets);
1721 Types.push_back(sugaredType);
1722 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001723}
1724
John McCall33ddac02011-01-19 10:06:00 +00001725QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001726 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001727 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001728 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001729 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001730
John McCall33ddac02011-01-19 10:06:00 +00001731 void *insertPos = 0;
1732 if (IncompleteArrayType *iat =
1733 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1734 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001735
1736 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001737 // either, so fill in the canonical type field. We also have to pull
1738 // qualifiers off the element type.
1739 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001740
John McCall33ddac02011-01-19 10:06:00 +00001741 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1742 SplitQualType canonSplit = getCanonicalType(elementType).split();
1743 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1744 ASM, elementTypeQuals);
1745 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001746
1747 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001748 IncompleteArrayType *existing =
1749 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1750 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001751 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001752
John McCall33ddac02011-01-19 10:06:00 +00001753 IncompleteArrayType *newType = new (*this, TypeAlignment)
1754 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001755
John McCall33ddac02011-01-19 10:06:00 +00001756 IncompleteArrayTypes.InsertNode(newType, insertPos);
1757 Types.push_back(newType);
1758 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001759}
1760
Steve Naroff91fcddb2007-07-18 18:00:27 +00001761/// getVectorType - Return the unique reference to a vector type of
1762/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001763QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001764 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001765 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001766
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001767 // Check if we've already instantiated a vector of this type.
1768 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001769 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001770
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001771 void *InsertPos = 0;
1772 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1773 return QualType(VTP, 0);
1774
1775 // If the element type isn't canonical, this won't be a canonical type either,
1776 // so fill in the canonical type field.
1777 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001778 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001779 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001780
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001781 // Get the new insert position for the node we care about.
1782 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001783 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001784 }
John McCall90d1c2d2009-09-24 23:30:46 +00001785 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001786 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001787 VectorTypes.InsertNode(New, InsertPos);
1788 Types.push_back(New);
1789 return QualType(New, 0);
1790}
1791
Nate Begemance4d7fc2008-04-18 23:10:10 +00001792/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001793/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001794QualType
1795ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall33ddac02011-01-19 10:06:00 +00001796 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001797
Steve Naroff91fcddb2007-07-18 18:00:27 +00001798 // Check if we've already instantiated a vector of this type.
1799 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001800 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001801 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001802 void *InsertPos = 0;
1803 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1804 return QualType(VTP, 0);
1805
1806 // If the element type isn't canonical, this won't be a canonical type either,
1807 // so fill in the canonical type field.
1808 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001809 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001810 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001811
Steve Naroff91fcddb2007-07-18 18:00:27 +00001812 // Get the new insert position for the node we care about.
1813 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001814 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001815 }
John McCall90d1c2d2009-09-24 23:30:46 +00001816 ExtVectorType *New = new (*this, TypeAlignment)
1817 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001818 VectorTypes.InsertNode(New, InsertPos);
1819 Types.push_back(New);
1820 return QualType(New, 0);
1821}
1822
Jay Foad39c79802011-01-12 09:06:06 +00001823QualType
1824ASTContext::getDependentSizedExtVectorType(QualType vecType,
1825 Expr *SizeExpr,
1826 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001827 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001828 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001829 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001830
Douglas Gregor352169a2009-07-31 03:54:25 +00001831 void *InsertPos = 0;
1832 DependentSizedExtVectorType *Canon
1833 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1834 DependentSizedExtVectorType *New;
1835 if (Canon) {
1836 // We already have a canonical version of this array type; use it as
1837 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001838 New = new (*this, TypeAlignment)
1839 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1840 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001841 } else {
1842 QualType CanonVecTy = getCanonicalType(vecType);
1843 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001844 New = new (*this, TypeAlignment)
1845 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1846 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001847
1848 DependentSizedExtVectorType *CanonCheck
1849 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1850 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1851 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001852 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1853 } else {
1854 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1855 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001856 New = new (*this, TypeAlignment)
1857 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001858 }
1859 }
Mike Stump11289f42009-09-09 15:08:12 +00001860
Douglas Gregor758a8692009-06-17 21:51:59 +00001861 Types.push_back(New);
1862 return QualType(New, 0);
1863}
1864
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001865/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001866///
Jay Foad39c79802011-01-12 09:06:06 +00001867QualType
1868ASTContext::getFunctionNoProtoType(QualType ResultTy,
1869 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00001870 const CallingConv DefaultCC = Info.getCC();
1871 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1872 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001873 // Unique functions, to guarantee there is only one function of a particular
1874 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001875 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001876 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001877
Chris Lattner47955de2007-01-27 08:37:20 +00001878 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001879 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001880 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001881 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001882
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001883 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001884 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001885 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001886 Canonical =
1887 getFunctionNoProtoType(getCanonicalType(ResultTy),
1888 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001889
Chris Lattner47955de2007-01-27 08:37:20 +00001890 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001891 FunctionNoProtoType *NewIP =
1892 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001893 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001894 }
Mike Stump11289f42009-09-09 15:08:12 +00001895
Roman Divacky65b88cd2011-03-01 17:40:53 +00001896 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00001897 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00001898 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00001899 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001900 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001901 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001902}
1903
1904/// getFunctionType - Return a normal function type with a typed argument
1905/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001906QualType
1907ASTContext::getFunctionType(QualType ResultTy,
1908 const QualType *ArgArray, unsigned NumArgs,
1909 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001910 // Unique functions, to guarantee there is only one function of a particular
1911 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001912 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00001913 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001914
1915 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001916 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001917 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001918 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001919
1920 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00001921 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001922 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001923 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001924 isCanonical = false;
1925
Roman Divacky65b88cd2011-03-01 17:40:53 +00001926 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
1927 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1928 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00001929
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001930 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001931 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001932 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001933 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001934 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001935 CanonicalArgs.reserve(NumArgs);
1936 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001937 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001938
John McCalldb40c7f2010-12-14 08:05:40 +00001939 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00001940 CanonicalEPI.ExceptionSpecType = EST_None;
1941 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00001942 CanonicalEPI.ExtInfo
1943 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1944
Chris Lattner76a00cf2008-04-06 22:59:24 +00001945 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001946 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00001947 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001948
Chris Lattnerfd4de792007-01-27 01:15:32 +00001949 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001950 FunctionProtoType *NewIP =
1951 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001952 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001953 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001954
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001955 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001956 // for two variable size arrays (for parameter and exception types) at the
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001957 // end of them. Instead of the exception types, there could be a noexcept
1958 // expression and a context pointer.
John McCalldb40c7f2010-12-14 08:05:40 +00001959 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001960 NumArgs * sizeof(QualType);
1961 if (EPI.ExceptionSpecType == EST_Dynamic)
1962 Size += EPI.NumExceptions * sizeof(QualType);
1963 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00001964 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001965 }
John McCalldb40c7f2010-12-14 08:05:40 +00001966 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00001967 FunctionProtoType::ExtProtoInfo newEPI = EPI;
1968 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00001969 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001970 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001971 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001972 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001973}
Chris Lattneref51c202006-11-10 07:17:23 +00001974
John McCalle78aac42010-03-10 03:28:59 +00001975#ifndef NDEBUG
1976static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1977 if (!isa<CXXRecordDecl>(D)) return false;
1978 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1979 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1980 return true;
1981 if (RD->getDescribedClassTemplate() &&
1982 !isa<ClassTemplateSpecializationDecl>(RD))
1983 return true;
1984 return false;
1985}
1986#endif
1987
1988/// getInjectedClassNameType - Return the unique reference to the
1989/// injected class name type for the specified templated declaration.
1990QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00001991 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00001992 assert(NeedsInjectedClassNameType(Decl));
1993 if (Decl->TypeForDecl) {
1994 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001995 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001996 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1997 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1998 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1999 } else {
John McCall424cec92011-01-19 06:33:43 +00002000 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002001 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002002 Decl->TypeForDecl = newType;
2003 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002004 }
2005 return QualType(Decl->TypeForDecl, 0);
2006}
2007
Douglas Gregor83a586e2008-04-13 21:07:44 +00002008/// getTypeDeclType - Return the unique reference to the type for the
2009/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002010QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002011 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002012 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002013
John McCall81e38502010-02-16 03:57:14 +00002014 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002015 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002016
John McCall96f0b5f2010-03-10 06:48:02 +00002017 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2018 "Template type parameter types are always available.");
2019
John McCall81e38502010-02-16 03:57:14 +00002020 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002021 assert(!Record->getPreviousDeclaration() &&
2022 "struct/union has previous declaration");
2023 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002024 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002025 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002026 assert(!Enum->getPreviousDeclaration() &&
2027 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002028 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002029 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002030 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002031 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2032 Decl->TypeForDecl = newType;
2033 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002034 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002035 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002036
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002037 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002038}
2039
Chris Lattner32d920b2007-01-26 02:01:53 +00002040/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00002041/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002042QualType
Jay Foad39c79802011-01-12 09:06:06 +00002043ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002044 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002045
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002046 if (Canonical.isNull())
2047 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002048 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002049 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002050 Decl->TypeForDecl = newType;
2051 Types.push_back(newType);
2052 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002053}
2054
Jay Foad39c79802011-01-12 09:06:06 +00002055QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002056 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2057
2058 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2059 if (PrevDecl->TypeForDecl)
2060 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2061
John McCall424cec92011-01-19 06:33:43 +00002062 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2063 Decl->TypeForDecl = newType;
2064 Types.push_back(newType);
2065 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002066}
2067
Jay Foad39c79802011-01-12 09:06:06 +00002068QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002069 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2070
2071 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2072 if (PrevDecl->TypeForDecl)
2073 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2074
John McCall424cec92011-01-19 06:33:43 +00002075 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2076 Decl->TypeForDecl = newType;
2077 Types.push_back(newType);
2078 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002079}
2080
John McCall81904512011-01-06 01:58:22 +00002081QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2082 QualType modifiedType,
2083 QualType equivalentType) {
2084 llvm::FoldingSetNodeID id;
2085 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2086
2087 void *insertPos = 0;
2088 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2089 if (type) return QualType(type, 0);
2090
2091 QualType canon = getCanonicalType(equivalentType);
2092 type = new (*this, TypeAlignment)
2093 AttributedType(canon, attrKind, modifiedType, equivalentType);
2094
2095 Types.push_back(type);
2096 AttributedTypes.InsertNode(type, insertPos);
2097
2098 return QualType(type, 0);
2099}
2100
2101
John McCallcebee162009-10-18 09:09:24 +00002102/// \brief Retrieve a substitution-result type.
2103QualType
2104ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002105 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002106 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002107 && "replacement types must always be canonical");
2108
2109 llvm::FoldingSetNodeID ID;
2110 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2111 void *InsertPos = 0;
2112 SubstTemplateTypeParmType *SubstParm
2113 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2114
2115 if (!SubstParm) {
2116 SubstParm = new (*this, TypeAlignment)
2117 SubstTemplateTypeParmType(Parm, Replacement);
2118 Types.push_back(SubstParm);
2119 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2120 }
2121
2122 return QualType(SubstParm, 0);
2123}
2124
Douglas Gregorada4b792011-01-14 02:55:32 +00002125/// \brief Retrieve a
2126QualType ASTContext::getSubstTemplateTypeParmPackType(
2127 const TemplateTypeParmType *Parm,
2128 const TemplateArgument &ArgPack) {
2129#ifndef NDEBUG
2130 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2131 PEnd = ArgPack.pack_end();
2132 P != PEnd; ++P) {
2133 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2134 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2135 }
2136#endif
2137
2138 llvm::FoldingSetNodeID ID;
2139 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2140 void *InsertPos = 0;
2141 if (SubstTemplateTypeParmPackType *SubstParm
2142 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2143 return QualType(SubstParm, 0);
2144
2145 QualType Canon;
2146 if (!Parm->isCanonicalUnqualified()) {
2147 Canon = getCanonicalType(QualType(Parm, 0));
2148 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2149 ArgPack);
2150 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2151 }
2152
2153 SubstTemplateTypeParmPackType *SubstParm
2154 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2155 ArgPack);
2156 Types.push_back(SubstParm);
2157 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2158 return QualType(SubstParm, 0);
2159}
2160
Douglas Gregoreff93e02009-02-05 23:33:38 +00002161/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002162/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002163/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002164QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002165 bool ParameterPack,
Jay Foad39c79802011-01-12 09:06:06 +00002166 IdentifierInfo *Name) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002167 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002168 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002169 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002170 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002171 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2172
2173 if (TypeParm)
2174 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002175
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002176 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002177 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002178 TypeParm = new (*this, TypeAlignment)
2179 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002180
2181 TemplateTypeParmType *TypeCheck
2182 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2183 assert(!TypeCheck && "Template type parameter canonical type broken");
2184 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002185 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002186 TypeParm = new (*this, TypeAlignment)
2187 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002188
2189 Types.push_back(TypeParm);
2190 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2191
2192 return QualType(TypeParm, 0);
2193}
2194
John McCalle78aac42010-03-10 03:28:59 +00002195TypeSourceInfo *
2196ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2197 SourceLocation NameLoc,
2198 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002199 QualType CanonType) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002200 assert(!Name.getAsDependentTemplateName() &&
2201 "No dependent template names here!");
John McCalle78aac42010-03-10 03:28:59 +00002202 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2203
2204 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2205 TemplateSpecializationTypeLoc TL
2206 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2207 TL.setTemplateNameLoc(NameLoc);
2208 TL.setLAngleLoc(Args.getLAngleLoc());
2209 TL.setRAngleLoc(Args.getRAngleLoc());
2210 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2211 TL.setArgLocInfo(i, Args[i].getLocInfo());
2212 return DI;
2213}
2214
Mike Stump11289f42009-09-09 15:08:12 +00002215QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002216ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002217 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002218 QualType Canon) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002219 assert(!Template.getAsDependentTemplateName() &&
2220 "No dependent template names here!");
2221
John McCall6b51f282009-11-23 01:53:49 +00002222 unsigned NumArgs = Args.size();
2223
John McCall0ad16662009-10-29 08:12:44 +00002224 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2225 ArgVec.reserve(NumArgs);
2226 for (unsigned i = 0; i != NumArgs; ++i)
2227 ArgVec.push_back(Args[i].getArgument());
2228
John McCall2408e322010-04-27 00:57:59 +00002229 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00002230 Canon);
John McCall0ad16662009-10-29 08:12:44 +00002231}
2232
2233QualType
2234ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002235 const TemplateArgument *Args,
2236 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002237 QualType Canon) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002238 assert(!Template.getAsDependentTemplateName() &&
2239 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002240 // Look through qualified template names.
2241 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2242 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002243
Douglas Gregor15301382009-07-30 17:40:51 +00002244 if (!Canon.isNull())
2245 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002246 else
2247 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00002248
Douglas Gregora8e02e72009-07-28 23:00:59 +00002249 // Allocate the (non-canonical) template specialization type, but don't
2250 // try to unique it: these types typically have location information that
2251 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002252 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002253 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002254 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002255 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002256 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002257 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002258 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002259
Douglas Gregor8bf42052009-02-09 18:46:07 +00002260 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002261 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002262}
2263
Mike Stump11289f42009-09-09 15:08:12 +00002264QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002265ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2266 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002267 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002268 assert(!Template.getAsDependentTemplateName() &&
2269 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002270 // Look through qualified template names.
2271 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2272 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002273
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002274 // Build the canonical template specialization type.
2275 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2276 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2277 CanonArgs.reserve(NumArgs);
2278 for (unsigned I = 0; I != NumArgs; ++I)
2279 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2280
2281 // Determine whether this canonical template specialization type already
2282 // exists.
2283 llvm::FoldingSetNodeID ID;
2284 TemplateSpecializationType::Profile(ID, CanonTemplate,
2285 CanonArgs.data(), NumArgs, *this);
2286
2287 void *InsertPos = 0;
2288 TemplateSpecializationType *Spec
2289 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2290
2291 if (!Spec) {
2292 // Allocate a new canonical template specialization type.
2293 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2294 sizeof(TemplateArgument) * NumArgs),
2295 TypeAlignment);
2296 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2297 CanonArgs.data(), NumArgs,
2298 QualType());
2299 Types.push_back(Spec);
2300 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2301 }
2302
2303 assert(Spec->isDependentType() &&
2304 "Non-dependent template-id type must have a canonical type");
2305 return QualType(Spec, 0);
2306}
2307
2308QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002309ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2310 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002311 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002312 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002313 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002314
2315 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002316 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002317 if (T)
2318 return QualType(T, 0);
2319
Douglas Gregorc42075a2010-02-04 18:10:26 +00002320 QualType Canon = NamedType;
2321 if (!Canon.isCanonical()) {
2322 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002323 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2324 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002325 (void)CheckT;
2326 }
2327
Abramo Bagnara6150c882010-05-11 21:36:43 +00002328 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002329 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002330 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002331 return QualType(T, 0);
2332}
2333
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002334QualType
Jay Foad39c79802011-01-12 09:06:06 +00002335ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002336 llvm::FoldingSetNodeID ID;
2337 ParenType::Profile(ID, InnerType);
2338
2339 void *InsertPos = 0;
2340 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2341 if (T)
2342 return QualType(T, 0);
2343
2344 QualType Canon = InnerType;
2345 if (!Canon.isCanonical()) {
2346 Canon = getCanonicalType(InnerType);
2347 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2348 assert(!CheckT && "Paren canonical type broken");
2349 (void)CheckT;
2350 }
2351
2352 T = new (*this) ParenType(InnerType, Canon);
2353 Types.push_back(T);
2354 ParenTypes.InsertNode(T, InsertPos);
2355 return QualType(T, 0);
2356}
2357
Douglas Gregor02085352010-03-31 20:19:30 +00002358QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2359 NestedNameSpecifier *NNS,
2360 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002361 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002362 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2363
2364 if (Canon.isNull()) {
2365 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002366 ElaboratedTypeKeyword CanonKeyword = Keyword;
2367 if (Keyword == ETK_None)
2368 CanonKeyword = ETK_Typename;
2369
2370 if (CanonNNS != NNS || CanonKeyword != Keyword)
2371 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002372 }
2373
2374 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002375 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002376
2377 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002378 DependentNameType *T
2379 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002380 if (T)
2381 return QualType(T, 0);
2382
Douglas Gregor02085352010-03-31 20:19:30 +00002383 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002384 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002385 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002386 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002387}
2388
Mike Stump11289f42009-09-09 15:08:12 +00002389QualType
John McCallc392f372010-06-11 00:33:02 +00002390ASTContext::getDependentTemplateSpecializationType(
2391 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002392 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002393 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002394 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002395 // TODO: avoid this copy
2396 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2397 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2398 ArgCopy.push_back(Args[I].getArgument());
2399 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2400 ArgCopy.size(),
2401 ArgCopy.data());
2402}
2403
2404QualType
2405ASTContext::getDependentTemplateSpecializationType(
2406 ElaboratedTypeKeyword Keyword,
2407 NestedNameSpecifier *NNS,
2408 const IdentifierInfo *Name,
2409 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002410 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002411 assert((!NNS || NNS->isDependent()) &&
2412 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002413
Douglas Gregorc42075a2010-02-04 18:10:26 +00002414 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002415 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2416 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002417
2418 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002419 DependentTemplateSpecializationType *T
2420 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002421 if (T)
2422 return QualType(T, 0);
2423
John McCallc392f372010-06-11 00:33:02 +00002424 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002425
John McCallc392f372010-06-11 00:33:02 +00002426 ElaboratedTypeKeyword CanonKeyword = Keyword;
2427 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2428
2429 bool AnyNonCanonArgs = false;
2430 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2431 for (unsigned I = 0; I != NumArgs; ++I) {
2432 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2433 if (!CanonArgs[I].structurallyEquals(Args[I]))
2434 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002435 }
2436
John McCallc392f372010-06-11 00:33:02 +00002437 QualType Canon;
2438 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2439 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2440 Name, NumArgs,
2441 CanonArgs.data());
2442
2443 // Find the insert position again.
2444 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2445 }
2446
2447 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2448 sizeof(TemplateArgument) * NumArgs),
2449 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002450 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002451 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002452 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002453 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002454 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002455}
2456
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002457QualType ASTContext::getPackExpansionType(QualType Pattern,
2458 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002459 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002460 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002461
2462 assert(Pattern->containsUnexpandedParameterPack() &&
2463 "Pack expansions must expand one or more parameter packs");
2464 void *InsertPos = 0;
2465 PackExpansionType *T
2466 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2467 if (T)
2468 return QualType(T, 0);
2469
2470 QualType Canon;
2471 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002472 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002473
2474 // Find the insert position again.
2475 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2476 }
2477
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002478 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002479 Types.push_back(T);
2480 PackExpansionTypes.InsertNode(T, InsertPos);
2481 return QualType(T, 0);
2482}
2483
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002484/// CmpProtocolNames - Comparison predicate for sorting protocols
2485/// alphabetically.
2486static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2487 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002488 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002489}
2490
John McCall8b07ec22010-05-15 11:32:37 +00002491static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002492 unsigned NumProtocols) {
2493 if (NumProtocols == 0) return true;
2494
2495 for (unsigned i = 1; i != NumProtocols; ++i)
2496 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2497 return false;
2498 return true;
2499}
2500
2501static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002502 unsigned &NumProtocols) {
2503 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002504
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002505 // Sort protocols, keyed by name.
2506 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2507
2508 // Remove duplicates.
2509 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2510 NumProtocols = ProtocolsEnd-Protocols;
2511}
2512
John McCall8b07ec22010-05-15 11:32:37 +00002513QualType ASTContext::getObjCObjectType(QualType BaseType,
2514 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002515 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002516 // If the base type is an interface and there aren't any protocols
2517 // to add, then the interface type will do just fine.
2518 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2519 return BaseType;
2520
2521 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002522 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002523 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002524 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002525 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2526 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002527
John McCall8b07ec22010-05-15 11:32:37 +00002528 // Build the canonical type, which has the canonical base type and
2529 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002530 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002531 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2532 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2533 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002534 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2535 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002536 unsigned UniqueCount = NumProtocols;
2537
John McCallfc93cf92009-10-22 22:37:11 +00002538 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002539 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2540 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002541 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002542 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2543 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002544 }
2545
2546 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002547 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2548 }
2549
2550 unsigned Size = sizeof(ObjCObjectTypeImpl);
2551 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2552 void *Mem = Allocate(Size, TypeAlignment);
2553 ObjCObjectTypeImpl *T =
2554 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2555
2556 Types.push_back(T);
2557 ObjCObjectTypes.InsertNode(T, InsertPos);
2558 return QualType(T, 0);
2559}
2560
2561/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2562/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002563QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002564 llvm::FoldingSetNodeID ID;
2565 ObjCObjectPointerType::Profile(ID, ObjectT);
2566
2567 void *InsertPos = 0;
2568 if (ObjCObjectPointerType *QT =
2569 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2570 return QualType(QT, 0);
2571
2572 // Find the canonical object type.
2573 QualType Canonical;
2574 if (!ObjectT.isCanonical()) {
2575 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2576
2577 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002578 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2579 }
2580
Douglas Gregorf85bee62010-02-08 22:59:26 +00002581 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002582 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2583 ObjCObjectPointerType *QType =
2584 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002585
Steve Narofffb4330f2009-06-17 22:40:22 +00002586 Types.push_back(QType);
2587 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002588 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002589}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002590
Douglas Gregor1c283312010-08-11 12:19:30 +00002591/// getObjCInterfaceType - Return the unique reference to the type for the
2592/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002593QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002594 if (Decl->TypeForDecl)
2595 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002596
Douglas Gregor1c283312010-08-11 12:19:30 +00002597 // FIXME: redeclarations?
2598 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2599 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2600 Decl->TypeForDecl = T;
2601 Types.push_back(T);
2602 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002603}
2604
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002605/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2606/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002607/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002608/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002609/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002610QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002611 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002612 if (tofExpr->isTypeDependent()) {
2613 llvm::FoldingSetNodeID ID;
2614 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002615
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002616 void *InsertPos = 0;
2617 DependentTypeOfExprType *Canon
2618 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2619 if (Canon) {
2620 // We already have a "canonical" version of an identical, dependent
2621 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002622 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002623 QualType((TypeOfExprType*)Canon, 0));
2624 }
2625 else {
2626 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002627 Canon
2628 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002629 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2630 toe = Canon;
2631 }
2632 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002633 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002634 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002635 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002636 Types.push_back(toe);
2637 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002638}
2639
Steve Naroffa773cd52007-08-01 18:02:17 +00002640/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2641/// TypeOfType AST's. The only motivation to unique these nodes would be
2642/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002643/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002644/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002645QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002646 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002647 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002648 Types.push_back(tot);
2649 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002650}
2651
Anders Carlssonad6bd352009-06-24 21:24:56 +00002652/// getDecltypeForExpr - Given an expr, will return the decltype for that
2653/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002654static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002655 if (e->isTypeDependent())
2656 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002657
Anders Carlssonad6bd352009-06-24 21:24:56 +00002658 // If e is an id expression or a class member access, decltype(e) is defined
2659 // as the type of the entity named by e.
2660 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2661 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2662 return VD->getType();
2663 }
2664 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2665 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2666 return FD->getType();
2667 }
2668 // If e is a function call or an invocation of an overloaded operator,
2669 // (parentheses around e are ignored), decltype(e) is defined as the
2670 // return type of that function.
2671 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2672 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002673
Anders Carlssonad6bd352009-06-24 21:24:56 +00002674 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002675
2676 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002677 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002678 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002679 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002680
Anders Carlssonad6bd352009-06-24 21:24:56 +00002681 return T;
2682}
2683
Anders Carlsson81df7b82009-06-24 19:06:50 +00002684/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2685/// DecltypeType AST's. The only motivation to unique these nodes would be
2686/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002687/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002688/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002689QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002690 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002691 if (e->isTypeDependent()) {
2692 llvm::FoldingSetNodeID ID;
2693 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002694
Douglas Gregora21f6c32009-07-30 23:36:40 +00002695 void *InsertPos = 0;
2696 DependentDecltypeType *Canon
2697 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2698 if (Canon) {
2699 // We already have a "canonical" version of an equivalent, dependent
2700 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002701 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002702 QualType((DecltypeType*)Canon, 0));
2703 }
2704 else {
2705 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002706 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002707 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2708 dt = Canon;
2709 }
2710 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002711 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002712 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002713 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002714 Types.push_back(dt);
2715 return QualType(dt, 0);
2716}
2717
Richard Smithb2bc2e62011-02-21 20:05:19 +00002718/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002719QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002720 void *InsertPos = 0;
2721 if (!DeducedType.isNull()) {
2722 // Look in the folding set for an existing type.
2723 llvm::FoldingSetNodeID ID;
2724 AutoType::Profile(ID, DeducedType);
2725 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2726 return QualType(AT, 0);
2727 }
2728
2729 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2730 Types.push_back(AT);
2731 if (InsertPos)
2732 AutoTypes.InsertNode(AT, InsertPos);
2733 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002734}
2735
Chris Lattnerfb072462007-01-23 05:45:31 +00002736/// getTagDeclType - Return the unique reference to the type for the
2737/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002738QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002739 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002740 // FIXME: What is the design on getTagDeclType when it requires casting
2741 // away const? mutable?
2742 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002743}
2744
Mike Stump11289f42009-09-09 15:08:12 +00002745/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2746/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2747/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002748CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002749 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002750}
Chris Lattnerfb072462007-01-23 05:45:31 +00002751
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002752/// getSignedWCharType - Return the type of "signed wchar_t".
2753/// Used when in C++, as a GCC extension.
2754QualType ASTContext::getSignedWCharType() const {
2755 // FIXME: derive from "Target" ?
2756 return WCharTy;
2757}
2758
2759/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2760/// Used when in C++, as a GCC extension.
2761QualType ASTContext::getUnsignedWCharType() const {
2762 // FIXME: derive from "Target" ?
2763 return UnsignedIntTy;
2764}
2765
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002766/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2767/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2768QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002769 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002770}
2771
Chris Lattnera21ad802008-04-02 05:18:44 +00002772//===----------------------------------------------------------------------===//
2773// Type Operators
2774//===----------------------------------------------------------------------===//
2775
Jay Foad39c79802011-01-12 09:06:06 +00002776CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002777 // Push qualifiers into arrays, and then discard any remaining
2778 // qualifiers.
2779 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002780 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002781 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002782 QualType Result;
2783 if (isa<ArrayType>(Ty)) {
2784 Result = getArrayDecayedType(QualType(Ty,0));
2785 } else if (isa<FunctionType>(Ty)) {
2786 Result = getPointerType(QualType(Ty, 0));
2787 } else {
2788 Result = QualType(Ty, 0);
2789 }
2790
2791 return CanQualType::CreateUnsafe(Result);
2792}
2793
Chris Lattner7adf0762008-08-04 07:31:14 +00002794
John McCall6c9dd522011-01-18 07:41:22 +00002795QualType ASTContext::getUnqualifiedArrayType(QualType type,
2796 Qualifiers &quals) {
2797 SplitQualType splitType = type.getSplitUnqualifiedType();
2798
2799 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2800 // the unqualified desugared type and then drops it on the floor.
2801 // We then have to strip that sugar back off with
2802 // getUnqualifiedDesugaredType(), which is silly.
2803 const ArrayType *AT =
2804 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2805
2806 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002807 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002808 quals = splitType.second;
2809 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002810 }
2811
John McCall6c9dd522011-01-18 07:41:22 +00002812 // Otherwise, recurse on the array's element type.
2813 QualType elementType = AT->getElementType();
2814 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2815
2816 // If that didn't change the element type, AT has no qualifiers, so we
2817 // can just use the results in splitType.
2818 if (elementType == unqualElementType) {
2819 assert(quals.empty()); // from the recursive call
2820 quals = splitType.second;
2821 return QualType(splitType.first, 0);
2822 }
2823
2824 // Otherwise, add in the qualifiers from the outermost type, then
2825 // build the type back up.
2826 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002827
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002828 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002829 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002830 CAT->getSizeModifier(), 0);
2831 }
2832
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002833 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002834 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002835 }
2836
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002837 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002838 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002839 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002840 VAT->getSizeModifier(),
2841 VAT->getIndexTypeCVRQualifiers(),
2842 VAT->getBracketsRange());
2843 }
2844
2845 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002846 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002847 DSAT->getSizeModifier(), 0,
2848 SourceRange());
2849}
2850
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002851/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2852/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2853/// they point to and return true. If T1 and T2 aren't pointer types
2854/// or pointer-to-member types, or if they are not similar at this
2855/// level, returns false and leaves T1 and T2 unchanged. Top-level
2856/// qualifiers on T1 and T2 are ignored. This function will typically
2857/// be called in a loop that successively "unwraps" pointer and
2858/// pointer-to-member types to compare them at each level.
2859bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2860 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2861 *T2PtrType = T2->getAs<PointerType>();
2862 if (T1PtrType && T2PtrType) {
2863 T1 = T1PtrType->getPointeeType();
2864 T2 = T2PtrType->getPointeeType();
2865 return true;
2866 }
2867
2868 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2869 *T2MPType = T2->getAs<MemberPointerType>();
2870 if (T1MPType && T2MPType &&
2871 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2872 QualType(T2MPType->getClass(), 0))) {
2873 T1 = T1MPType->getPointeeType();
2874 T2 = T2MPType->getPointeeType();
2875 return true;
2876 }
2877
2878 if (getLangOptions().ObjC1) {
2879 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2880 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2881 if (T1OPType && T2OPType) {
2882 T1 = T1OPType->getPointeeType();
2883 T2 = T2OPType->getPointeeType();
2884 return true;
2885 }
2886 }
2887
2888 // FIXME: Block pointers, too?
2889
2890 return false;
2891}
2892
Jay Foad39c79802011-01-12 09:06:06 +00002893DeclarationNameInfo
2894ASTContext::getNameForTemplate(TemplateName Name,
2895 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002896 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002897 // DNInfo work in progress: CHECKME: what about DNLoc?
2898 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2899
John McCall847e2a12009-11-24 18:42:40 +00002900 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002901 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002902 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002903 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2904 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002905 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002906 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2907 // DNInfo work in progress: FIXME: source locations?
2908 DeclarationNameLoc DNLoc;
2909 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2910 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2911 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002912 }
2913 }
2914
John McCalld28ae272009-12-02 08:04:21 +00002915 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2916 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002917 // DNInfo work in progress: CHECKME: what about DNLoc?
2918 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002919}
2920
Jay Foad39c79802011-01-12 09:06:06 +00002921TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002922 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2923 if (TemplateTemplateParmDecl *TTP
2924 = dyn_cast<TemplateTemplateParmDecl>(Template))
2925 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2926
2927 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002928 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002929 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002930
Douglas Gregor5590be02011-01-15 06:45:20 +00002931 if (SubstTemplateTemplateParmPackStorage *SubstPack
2932 = Name.getAsSubstTemplateTemplateParmPack()) {
2933 TemplateTemplateParmDecl *CanonParam
2934 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2935 TemplateArgument CanonArgPack
2936 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2937 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2938 }
2939
John McCalld28ae272009-12-02 08:04:21 +00002940 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002941
Douglas Gregor6bc50582009-05-07 06:41:52 +00002942 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2943 assert(DTN && "Non-dependent template names must refer to template decls.");
2944 return DTN->CanonicalTemplateName;
2945}
2946
Douglas Gregoradee3e32009-11-11 23:06:43 +00002947bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2948 X = getCanonicalTemplateName(X);
2949 Y = getCanonicalTemplateName(Y);
2950 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2951}
2952
Mike Stump11289f42009-09-09 15:08:12 +00002953TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00002954ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00002955 switch (Arg.getKind()) {
2956 case TemplateArgument::Null:
2957 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002958
Douglas Gregora8e02e72009-07-28 23:00:59 +00002959 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002960 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002961
Douglas Gregora8e02e72009-07-28 23:00:59 +00002962 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002963 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002964
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002965 case TemplateArgument::Template:
2966 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002967
2968 case TemplateArgument::TemplateExpansion:
2969 return TemplateArgument(getCanonicalTemplateName(
2970 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00002971 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002972
Douglas Gregora8e02e72009-07-28 23:00:59 +00002973 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002974 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002975 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002976
Douglas Gregora8e02e72009-07-28 23:00:59 +00002977 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002978 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002979
Douglas Gregora8e02e72009-07-28 23:00:59 +00002980 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00002981 if (Arg.pack_size() == 0)
2982 return Arg;
2983
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002984 TemplateArgument *CanonArgs
2985 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00002986 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002987 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002988 AEnd = Arg.pack_end();
2989 A != AEnd; (void)++A, ++Idx)
2990 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002991
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002992 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00002993 }
2994 }
2995
2996 // Silence GCC warning
2997 assert(false && "Unhandled template argument kind");
2998 return TemplateArgument();
2999}
3000
Douglas Gregor333489b2009-03-27 23:10:48 +00003001NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003002ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003003 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003004 return 0;
3005
3006 switch (NNS->getKind()) {
3007 case NestedNameSpecifier::Identifier:
3008 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003009 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003010 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3011 NNS->getAsIdentifier());
3012
3013 case NestedNameSpecifier::Namespace:
3014 // A namespace is canonical; build a nested-name-specifier with
3015 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003016 return NestedNameSpecifier::Create(*this, 0,
3017 NNS->getAsNamespace()->getOriginalNamespace());
3018
3019 case NestedNameSpecifier::NamespaceAlias:
3020 // A namespace is canonical; build a nested-name-specifier with
3021 // this namespace and no prefix.
3022 return NestedNameSpecifier::Create(*this, 0,
3023 NNS->getAsNamespaceAlias()->getNamespace()
3024 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003025
3026 case NestedNameSpecifier::TypeSpec:
3027 case NestedNameSpecifier::TypeSpecWithTemplate: {
3028 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003029
3030 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3031 // break it apart into its prefix and identifier, then reconsititute those
3032 // as the canonical nested-name-specifier. This is required to canonicalize
3033 // a dependent nested-name-specifier involving typedefs of dependent-name
3034 // types, e.g.,
3035 // typedef typename T::type T1;
3036 // typedef typename T1::type T2;
3037 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3038 NestedNameSpecifier *Prefix
3039 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3040 return NestedNameSpecifier::Create(*this, Prefix,
3041 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3042 }
3043
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003044 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003045 if (const DependentTemplateSpecializationType *DTST
3046 = T->getAs<DependentTemplateSpecializationType>()) {
3047 NestedNameSpecifier *Prefix
3048 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003049
3050 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3051 Prefix, DTST->getIdentifier(),
3052 DTST->getNumArgs(),
3053 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003054 T = getCanonicalType(T);
3055 }
3056
John McCall33ddac02011-01-19 10:06:00 +00003057 return NestedNameSpecifier::Create(*this, 0, false,
3058 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003059 }
3060
3061 case NestedNameSpecifier::Global:
3062 // The global specifier is canonical and unique.
3063 return NNS;
3064 }
3065
3066 // Required to silence a GCC warning
3067 return 0;
3068}
3069
Chris Lattner7adf0762008-08-04 07:31:14 +00003070
Jay Foad39c79802011-01-12 09:06:06 +00003071const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003072 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003073 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003074 // Handle the common positive case fast.
3075 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3076 return AT;
3077 }
Mike Stump11289f42009-09-09 15:08:12 +00003078
John McCall8ccfcb52009-09-24 19:53:00 +00003079 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003080 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003081 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003082
John McCall8ccfcb52009-09-24 19:53:00 +00003083 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003084 // implements C99 6.7.3p8: "If the specification of an array type includes
3085 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003086
Chris Lattner7adf0762008-08-04 07:31:14 +00003087 // If we get here, we either have type qualifiers on the type, or we have
3088 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003089 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003090
John McCall33ddac02011-01-19 10:06:00 +00003091 SplitQualType split = T.getSplitDesugaredType();
3092 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003093
Chris Lattner7adf0762008-08-04 07:31:14 +00003094 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003095 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3096 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003097 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003098
Chris Lattner7adf0762008-08-04 07:31:14 +00003099 // Otherwise, we have an array and we have qualifiers on it. Push the
3100 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003101 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003102
Chris Lattner7adf0762008-08-04 07:31:14 +00003103 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3104 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3105 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003106 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003107 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3108 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3109 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003110 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003111
Mike Stump11289f42009-09-09 15:08:12 +00003112 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003113 = dyn_cast<DependentSizedArrayType>(ATy))
3114 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003115 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003116 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003117 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003118 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003119 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003120
Chris Lattner7adf0762008-08-04 07:31:14 +00003121 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003122 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003123 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003124 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003125 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003126 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003127}
3128
Chris Lattnera21ad802008-04-02 05:18:44 +00003129/// getArrayDecayedType - Return the properly qualified result of decaying the
3130/// specified array type to a pointer. This operation is non-trivial when
3131/// handling typedefs etc. The canonical type of "T" must be an array type,
3132/// this returns a pointer to a properly qualified element of the array.
3133///
3134/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003135QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003136 // Get the element type with 'getAsArrayType' so that we don't lose any
3137 // typedefs in the element type of the array. This also handles propagation
3138 // of type qualifiers from the array type into the element type if present
3139 // (C99 6.7.3p8).
3140 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3141 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003142
Chris Lattner7adf0762008-08-04 07:31:14 +00003143 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003144
3145 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003146 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003147}
3148
John McCall33ddac02011-01-19 10:06:00 +00003149QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3150 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003151}
3152
John McCall33ddac02011-01-19 10:06:00 +00003153QualType ASTContext::getBaseElementType(QualType type) const {
3154 Qualifiers qs;
3155 while (true) {
3156 SplitQualType split = type.getSplitDesugaredType();
3157 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3158 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003159
John McCall33ddac02011-01-19 10:06:00 +00003160 type = array->getElementType();
3161 qs.addConsistentQualifiers(split.second);
3162 }
Mike Stump11289f42009-09-09 15:08:12 +00003163
John McCall33ddac02011-01-19 10:06:00 +00003164 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003165}
3166
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003167/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003168uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003169ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3170 uint64_t ElementCount = 1;
3171 do {
3172 ElementCount *= CA->getSize().getZExtValue();
3173 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3174 } while (CA);
3175 return ElementCount;
3176}
3177
Steve Naroff0af91202007-04-27 21:51:21 +00003178/// getFloatingRank - Return a relative rank for floating point types.
3179/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003180static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003181 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003182 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003183
John McCall9dd450b2009-09-21 23:43:11 +00003184 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3185 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003186 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003187 case BuiltinType::Float: return FloatRank;
3188 case BuiltinType::Double: return DoubleRank;
3189 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003190 }
3191}
3192
Mike Stump11289f42009-09-09 15:08:12 +00003193/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3194/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003195/// 'typeDomain' is a real floating point or complex type.
3196/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003197QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3198 QualType Domain) const {
3199 FloatingRank EltRank = getFloatingRank(Size);
3200 if (Domain->isComplexType()) {
3201 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003202 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003203 case FloatRank: return FloatComplexTy;
3204 case DoubleRank: return DoubleComplexTy;
3205 case LongDoubleRank: return LongDoubleComplexTy;
3206 }
Steve Naroff0af91202007-04-27 21:51:21 +00003207 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003208
3209 assert(Domain->isRealFloatingType() && "Unknown domain!");
3210 switch (EltRank) {
3211 default: assert(0 && "getFloatingRank(): illegal value for rank");
3212 case FloatRank: return FloatTy;
3213 case DoubleRank: return DoubleTy;
3214 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003215 }
Steve Naroffe4718892007-04-27 18:30:00 +00003216}
3217
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003218/// getFloatingTypeOrder - Compare the rank of the two specified floating
3219/// point types, ignoring the domain of the type (i.e. 'double' ==
3220/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003221/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003222int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003223 FloatingRank LHSR = getFloatingRank(LHS);
3224 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003225
Chris Lattnerb90739d2008-04-06 23:38:49 +00003226 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003227 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003228 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003229 return 1;
3230 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003231}
3232
Chris Lattner76a00cf2008-04-06 22:59:24 +00003233/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3234/// routine will assert if passed a built-in type that isn't an integer or enum,
3235/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003236unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003237 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003238 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003239 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003240
Chris Lattnerad3467e2010-12-25 23:25:43 +00003241 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3242 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003243 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3244
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003245 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3246 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3247
3248 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3249 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3250
Chris Lattner76a00cf2008-04-06 22:59:24 +00003251 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003252 default: assert(0 && "getIntegerRank(): not a built-in integer");
3253 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003254 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003255 case BuiltinType::Char_S:
3256 case BuiltinType::Char_U:
3257 case BuiltinType::SChar:
3258 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003259 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003260 case BuiltinType::Short:
3261 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003262 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003263 case BuiltinType::Int:
3264 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003265 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003266 case BuiltinType::Long:
3267 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003268 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003269 case BuiltinType::LongLong:
3270 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003271 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003272 case BuiltinType::Int128:
3273 case BuiltinType::UInt128:
3274 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003275 }
3276}
3277
Eli Friedman629ffb92009-08-20 04:21:42 +00003278/// \brief Whether this is a promotable bitfield reference according
3279/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3280///
3281/// \returns the type this bit-field will promote to, or NULL if no
3282/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003283QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003284 if (E->isTypeDependent() || E->isValueDependent())
3285 return QualType();
3286
Eli Friedman629ffb92009-08-20 04:21:42 +00003287 FieldDecl *Field = E->getBitField();
3288 if (!Field)
3289 return QualType();
3290
3291 QualType FT = Field->getType();
3292
3293 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3294 uint64_t BitWidth = BitWidthAP.getZExtValue();
3295 uint64_t IntSize = getTypeSize(IntTy);
3296 // GCC extension compatibility: if the bit-field size is less than or equal
3297 // to the size of int, it gets promoted no matter what its type is.
3298 // For instance, unsigned long bf : 4 gets promoted to signed int.
3299 if (BitWidth < IntSize)
3300 return IntTy;
3301
3302 if (BitWidth == IntSize)
3303 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3304
3305 // Types bigger than int are not subject to promotions, and therefore act
3306 // like the base type.
3307 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3308 // is ridiculous.
3309 return QualType();
3310}
3311
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003312/// getPromotedIntegerType - Returns the type that Promotable will
3313/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3314/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003315QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003316 assert(!Promotable.isNull());
3317 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003318 if (const EnumType *ET = Promotable->getAs<EnumType>())
3319 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003320 if (Promotable->isSignedIntegerType())
3321 return IntTy;
3322 uint64_t PromotableSize = getTypeSize(Promotable);
3323 uint64_t IntSize = getTypeSize(IntTy);
3324 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3325 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3326}
3327
Mike Stump11289f42009-09-09 15:08:12 +00003328/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003329/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003330/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003331int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003332 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3333 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003334 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003335
Chris Lattner76a00cf2008-04-06 22:59:24 +00003336 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3337 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003338
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003339 unsigned LHSRank = getIntegerRank(LHSC);
3340 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003341
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003342 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3343 if (LHSRank == RHSRank) return 0;
3344 return LHSRank > RHSRank ? 1 : -1;
3345 }
Mike Stump11289f42009-09-09 15:08:12 +00003346
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003347 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3348 if (LHSUnsigned) {
3349 // If the unsigned [LHS] type is larger, return it.
3350 if (LHSRank >= RHSRank)
3351 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003352
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003353 // If the signed type can represent all values of the unsigned type, it
3354 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003355 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003356 return -1;
3357 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003358
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003359 // If the unsigned [RHS] type is larger, return it.
3360 if (RHSRank >= LHSRank)
3361 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003362
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003363 // If the signed type can represent all values of the unsigned type, it
3364 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003365 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003366 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003367}
Anders Carlsson98f07902007-08-17 05:31:46 +00003368
Anders Carlsson6d417272009-11-14 21:45:58 +00003369static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003370CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3371 DeclContext *DC, IdentifierInfo *Id) {
3372 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003373 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003374 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003375 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003376 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003377}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003378
Mike Stump11289f42009-09-09 15:08:12 +00003379// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003380QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003381 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003382 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003383 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003384 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003385 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003386
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003387 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003388
Anders Carlsson98f07902007-08-17 05:31:46 +00003389 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003390 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003391 // int flags;
3392 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003393 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003394 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003395 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003396 FieldTypes[3] = LongTy;
3397
Anders Carlsson98f07902007-08-17 05:31:46 +00003398 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003399 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003400 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003401 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003402 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003403 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003404 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003405 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003406 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003407 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003408 }
3409
Douglas Gregord5058122010-02-11 01:19:42 +00003410 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003411 }
Mike Stump11289f42009-09-09 15:08:12 +00003412
Anders Carlsson98f07902007-08-17 05:31:46 +00003413 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003414}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003415
Douglas Gregor512b0772009-04-23 22:29:11 +00003416void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003417 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003418 assert(Rec && "Invalid CFConstantStringType");
3419 CFConstantStringTypeDecl = Rec->getDecl();
3420}
3421
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003422// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003423QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003424 if (!NSConstantStringTypeDecl) {
3425 NSConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003426 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003427 &Idents.get("__builtin_NSString"));
3428 NSConstantStringTypeDecl->startDefinition();
3429
3430 QualType FieldTypes[3];
3431
3432 // const int *isa;
3433 FieldTypes[0] = getPointerType(IntTy.withConst());
3434 // const char *str;
3435 FieldTypes[1] = getPointerType(CharTy.withConst());
3436 // unsigned int length;
3437 FieldTypes[2] = UnsignedIntTy;
3438
3439 // Create fields
3440 for (unsigned i = 0; i < 3; ++i) {
3441 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003442 SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003443 SourceLocation(), 0,
3444 FieldTypes[i], /*TInfo=*/0,
3445 /*BitWidth=*/0,
3446 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003447 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003448 NSConstantStringTypeDecl->addDecl(Field);
3449 }
3450
3451 NSConstantStringTypeDecl->completeDefinition();
3452 }
3453
3454 return getTagDeclType(NSConstantStringTypeDecl);
3455}
3456
3457void ASTContext::setNSConstantStringType(QualType T) {
3458 const RecordType *Rec = T->getAs<RecordType>();
3459 assert(Rec && "Invalid NSConstantStringType");
3460 NSConstantStringTypeDecl = Rec->getDecl();
3461}
3462
Jay Foad39c79802011-01-12 09:06:06 +00003463QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003464 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003465 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003466 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003467 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003468 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003469
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003470 QualType FieldTypes[] = {
3471 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003472 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003473 getPointerType(UnsignedLongTy),
3474 getConstantArrayType(UnsignedLongTy,
3475 llvm::APInt(32, 5), ArrayType::Normal, 0)
3476 };
Mike Stump11289f42009-09-09 15:08:12 +00003477
Douglas Gregor91f84212008-12-11 16:49:14 +00003478 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003479 FieldDecl *Field = FieldDecl::Create(*this,
3480 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003481 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003482 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003483 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003484 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003485 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003486 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003487 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003488 }
Mike Stump11289f42009-09-09 15:08:12 +00003489
Douglas Gregord5058122010-02-11 01:19:42 +00003490 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003491 }
Mike Stump11289f42009-09-09 15:08:12 +00003492
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003493 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3494}
3495
Jay Foad39c79802011-01-12 09:06:06 +00003496QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003497 if (BlockDescriptorType)
3498 return getTagDeclType(BlockDescriptorType);
3499
3500 RecordDecl *T;
3501 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003502 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003503 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003504 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003505
3506 QualType FieldTypes[] = {
3507 UnsignedLongTy,
3508 UnsignedLongTy,
3509 };
3510
3511 const char *FieldNames[] = {
3512 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003513 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003514 };
3515
3516 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003517 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003518 SourceLocation(),
3519 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003520 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003521 /*BitWidth=*/0,
3522 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003523 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003524 T->addDecl(Field);
3525 }
3526
Douglas Gregord5058122010-02-11 01:19:42 +00003527 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003528
3529 BlockDescriptorType = T;
3530
3531 return getTagDeclType(BlockDescriptorType);
3532}
3533
3534void ASTContext::setBlockDescriptorType(QualType T) {
3535 const RecordType *Rec = T->getAs<RecordType>();
3536 assert(Rec && "Invalid BlockDescriptorType");
3537 BlockDescriptorType = Rec->getDecl();
3538}
3539
Jay Foad39c79802011-01-12 09:06:06 +00003540QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003541 if (BlockDescriptorExtendedType)
3542 return getTagDeclType(BlockDescriptorExtendedType);
3543
3544 RecordDecl *T;
3545 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003546 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003547 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003548 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003549
3550 QualType FieldTypes[] = {
3551 UnsignedLongTy,
3552 UnsignedLongTy,
3553 getPointerType(VoidPtrTy),
3554 getPointerType(VoidPtrTy)
3555 };
3556
3557 const char *FieldNames[] = {
3558 "reserved",
3559 "Size",
3560 "CopyFuncPtr",
3561 "DestroyFuncPtr"
3562 };
3563
3564 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003565 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003566 SourceLocation(),
3567 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003568 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003569 /*BitWidth=*/0,
3570 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003571 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003572 T->addDecl(Field);
3573 }
3574
Douglas Gregord5058122010-02-11 01:19:42 +00003575 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003576
3577 BlockDescriptorExtendedType = T;
3578
3579 return getTagDeclType(BlockDescriptorExtendedType);
3580}
3581
3582void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3583 const RecordType *Rec = T->getAs<RecordType>();
3584 assert(Rec && "Invalid BlockDescriptorType");
3585 BlockDescriptorExtendedType = Rec->getDecl();
3586}
3587
Jay Foad39c79802011-01-12 09:06:06 +00003588bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003589 if (Ty->isBlockPointerType())
3590 return true;
3591 if (isObjCNSObjectType(Ty))
3592 return true;
3593 if (Ty->isObjCObjectPointerType())
3594 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003595 if (getLangOptions().CPlusPlus) {
3596 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3597 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3598 return RD->hasConstCopyConstructor(*this);
3599
3600 }
3601 }
Mike Stump94967902009-10-21 18:16:27 +00003602 return false;
3603}
3604
Jay Foad39c79802011-01-12 09:06:06 +00003605QualType
3606ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003607 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003608 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003609 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003610 // unsigned int __flags;
3611 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003612 // void *__copy_helper; // as needed
3613 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003614 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003615 // } *
3616
Mike Stump94967902009-10-21 18:16:27 +00003617 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3618
3619 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003620 llvm::SmallString<36> Name;
3621 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3622 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003623 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003624 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003625 T->startDefinition();
3626 QualType Int32Ty = IntTy;
3627 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3628 QualType FieldTypes[] = {
3629 getPointerType(VoidPtrTy),
3630 getPointerType(getTagDeclType(T)),
3631 Int32Ty,
3632 Int32Ty,
3633 getPointerType(VoidPtrTy),
3634 getPointerType(VoidPtrTy),
3635 Ty
3636 };
3637
Daniel Dunbar56df9772010-08-17 22:39:59 +00003638 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003639 "__isa",
3640 "__forwarding",
3641 "__flags",
3642 "__size",
3643 "__copy_helper",
3644 "__destroy_helper",
3645 DeclName,
3646 };
3647
3648 for (size_t i = 0; i < 7; ++i) {
3649 if (!HasCopyAndDispose && i >=4 && i <= 5)
3650 continue;
3651 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003652 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003653 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003654 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003655 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003656 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003657 T->addDecl(Field);
3658 }
3659
Douglas Gregord5058122010-02-11 01:19:42 +00003660 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003661
3662 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003663}
3664
Douglas Gregor512b0772009-04-23 22:29:11 +00003665void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003666 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003667 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3668 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3669}
3670
Anders Carlsson18acd442007-10-29 06:33:42 +00003671// This returns true if a type has been typedefed to BOOL:
3672// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003673static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003674 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003675 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3676 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003677
Anders Carlssond8499822007-10-29 05:01:08 +00003678 return false;
3679}
3680
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003681/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003682/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003683CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003684 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003685
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003686 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003687 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003688 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003689 // Treat arrays as pointers, since that's how they're passed in.
3690 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003691 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003692 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003693}
3694
3695static inline
3696std::string charUnitsToString(const CharUnits &CU) {
3697 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003698}
3699
John McCall351762c2011-02-07 10:33:21 +00003700/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003701/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003702std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3703 std::string S;
3704
David Chisnall950a9512009-11-17 19:33:30 +00003705 const BlockDecl *Decl = Expr->getBlockDecl();
3706 QualType BlockTy =
3707 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3708 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003709 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003710 // Compute size of all parameters.
3711 // Start with computing size of a pointer in number of bytes.
3712 // FIXME: There might(should) be a better way of doing this computation!
3713 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003714 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3715 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003716 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003717 E = Decl->param_end(); PI != E; ++PI) {
3718 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003719 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003720 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003721 ParmOffset += sz;
3722 }
3723 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003724 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003725 // Block pointer and offset.
3726 S += "@?0";
3727 ParmOffset = PtrSize;
3728
3729 // Argument types.
3730 ParmOffset = PtrSize;
3731 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3732 Decl->param_end(); PI != E; ++PI) {
3733 ParmVarDecl *PVDecl = *PI;
3734 QualType PType = PVDecl->getOriginalType();
3735 if (const ArrayType *AT =
3736 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3737 // Use array's original type only if it has known number of
3738 // elements.
3739 if (!isa<ConstantArrayType>(AT))
3740 PType = PVDecl->getType();
3741 } else if (PType->isFunctionType())
3742 PType = PVDecl->getType();
3743 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003744 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003745 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003746 }
John McCall351762c2011-02-07 10:33:21 +00003747
3748 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003749}
3750
David Chisnall50e4eba2010-12-30 14:05:53 +00003751void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3752 std::string& S) {
3753 // Encode result type.
3754 getObjCEncodingForType(Decl->getResultType(), S);
3755 CharUnits ParmOffset;
3756 // Compute size of all parameters.
3757 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3758 E = Decl->param_end(); PI != E; ++PI) {
3759 QualType PType = (*PI)->getType();
3760 CharUnits sz = getObjCEncodingTypeSize(PType);
3761 assert (sz.isPositive() &&
3762 "getObjCEncodingForMethodDecl - Incomplete param type");
3763 ParmOffset += sz;
3764 }
3765 S += charUnitsToString(ParmOffset);
3766 ParmOffset = CharUnits::Zero();
3767
3768 // Argument types.
3769 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3770 E = Decl->param_end(); PI != E; ++PI) {
3771 ParmVarDecl *PVDecl = *PI;
3772 QualType PType = PVDecl->getOriginalType();
3773 if (const ArrayType *AT =
3774 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3775 // Use array's original type only if it has known number of
3776 // elements.
3777 if (!isa<ConstantArrayType>(AT))
3778 PType = PVDecl->getType();
3779 } else if (PType->isFunctionType())
3780 PType = PVDecl->getType();
3781 getObjCEncodingForType(PType, S);
3782 S += charUnitsToString(ParmOffset);
3783 ParmOffset += getObjCEncodingTypeSize(PType);
3784 }
3785}
3786
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003787/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003788/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003789void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003790 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003791 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003792 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003793 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003794 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003795 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003796 // Compute size of all parameters.
3797 // Start with computing size of a pointer in number of bytes.
3798 // FIXME: There might(should) be a better way of doing this computation!
3799 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003800 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003801 // The first two arguments (self and _cmd) are pointers; account for
3802 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003803 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003804 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003805 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003806 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003807 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003808 assert (sz.isPositive() &&
3809 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003810 ParmOffset += sz;
3811 }
Ken Dyck40775002010-01-11 17:06:35 +00003812 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003813 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003814 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003815
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003816 // Argument types.
3817 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003818 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003819 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003820 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003821 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003822 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003823 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3824 // Use array's original type only if it has known number of
3825 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003826 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003827 PType = PVDecl->getType();
3828 } else if (PType->isFunctionType())
3829 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003830 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003831 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003832 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003833 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003834 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003835 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003836 }
3837}
3838
Daniel Dunbar4932b362008-08-28 04:38:10 +00003839/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003840/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003841/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3842/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003843/// Property attributes are stored as a comma-delimited C string. The simple
3844/// attributes readonly and bycopy are encoded as single characters. The
3845/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3846/// encoded as single characters, followed by an identifier. Property types
3847/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003848/// these attributes are defined by the following enumeration:
3849/// @code
3850/// enum PropertyAttributes {
3851/// kPropertyReadOnly = 'R', // property is read-only.
3852/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3853/// kPropertyByref = '&', // property is a reference to the value last assigned
3854/// kPropertyDynamic = 'D', // property is dynamic
3855/// kPropertyGetter = 'G', // followed by getter selector name
3856/// kPropertySetter = 'S', // followed by setter selector name
3857/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3858/// kPropertyType = 't' // followed by old-style type encoding.
3859/// kPropertyWeak = 'W' // 'weak' property
3860/// kPropertyStrong = 'P' // property GC'able
3861/// kPropertyNonAtomic = 'N' // property non-atomic
3862/// };
3863/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003864void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003865 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003866 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003867 // Collect information from the property implementation decl(s).
3868 bool Dynamic = false;
3869 ObjCPropertyImplDecl *SynthesizePID = 0;
3870
3871 // FIXME: Duplicated code due to poor abstraction.
3872 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003873 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003874 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3875 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003876 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003877 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003878 ObjCPropertyImplDecl *PID = *i;
3879 if (PID->getPropertyDecl() == PD) {
3880 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3881 Dynamic = true;
3882 } else {
3883 SynthesizePID = PID;
3884 }
3885 }
3886 }
3887 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003888 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003889 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003890 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003891 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003892 ObjCPropertyImplDecl *PID = *i;
3893 if (PID->getPropertyDecl() == PD) {
3894 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3895 Dynamic = true;
3896 } else {
3897 SynthesizePID = PID;
3898 }
3899 }
Mike Stump11289f42009-09-09 15:08:12 +00003900 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003901 }
3902 }
3903
3904 // FIXME: This is not very efficient.
3905 S = "T";
3906
3907 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003908 // GCC has some special rules regarding encoding of properties which
3909 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003910 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003911 true /* outermost type */,
3912 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003913
3914 if (PD->isReadOnly()) {
3915 S += ",R";
3916 } else {
3917 switch (PD->getSetterKind()) {
3918 case ObjCPropertyDecl::Assign: break;
3919 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003920 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003921 }
3922 }
3923
3924 // It really isn't clear at all what this means, since properties
3925 // are "dynamic by default".
3926 if (Dynamic)
3927 S += ",D";
3928
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003929 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3930 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003931
Daniel Dunbar4932b362008-08-28 04:38:10 +00003932 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3933 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003934 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003935 }
3936
3937 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3938 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003939 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003940 }
3941
3942 if (SynthesizePID) {
3943 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3944 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003945 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003946 }
3947
3948 // FIXME: OBJCGC: weak & strong
3949}
3950
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003951/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003952/// Another legacy compatibility encoding: 32-bit longs are encoded as
3953/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003954/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3955///
3956void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003957 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003958 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00003959 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003960 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003961 else
Jay Foad39c79802011-01-12 09:06:06 +00003962 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003963 PointeeTy = IntTy;
3964 }
3965 }
3966}
3967
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003968void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00003969 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003970 // We follow the behavior of gcc, expanding structures which are
3971 // directly pointed to, and expanding embedded structures. Note that
3972 // these rules are sufficient to prevent recursive encoding of the
3973 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003974 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003975 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003976}
3977
David Chisnallb190a2c2010-06-04 01:10:52 +00003978static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3979 switch (T->getAs<BuiltinType>()->getKind()) {
3980 default: assert(0 && "Unhandled builtin type kind");
3981 case BuiltinType::Void: return 'v';
3982 case BuiltinType::Bool: return 'B';
3983 case BuiltinType::Char_U:
3984 case BuiltinType::UChar: return 'C';
3985 case BuiltinType::UShort: return 'S';
3986 case BuiltinType::UInt: return 'I';
3987 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00003988 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003989 case BuiltinType::UInt128: return 'T';
3990 case BuiltinType::ULongLong: return 'Q';
3991 case BuiltinType::Char_S:
3992 case BuiltinType::SChar: return 'c';
3993 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00003994 case BuiltinType::WChar_S:
3995 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00003996 case BuiltinType::Int: return 'i';
3997 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00003998 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003999 case BuiltinType::LongLong: return 'q';
4000 case BuiltinType::Int128: return 't';
4001 case BuiltinType::Float: return 'f';
4002 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004003 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004004 }
4005}
4006
Jay Foad39c79802011-01-12 09:06:06 +00004007static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004008 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004009 const Expr *E = FD->getBitWidth();
4010 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004011 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004012 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4013 // The GNU runtime requires more information; bitfields are encoded as b,
4014 // then the offset (in bits) of the first element, then the type of the
4015 // bitfield, then the size in bits. For example, in this structure:
4016 //
4017 // struct
4018 // {
4019 // int integer;
4020 // int flags:2;
4021 // };
4022 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4023 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4024 // information is not especially sensible, but we're stuck with it for
4025 // compatibility with GCC, although providing it breaks anything that
4026 // actually uses runtime introspection and wants to work on both runtimes...
4027 if (!Ctx->getLangOptions().NeXTRuntime) {
4028 const RecordDecl *RD = FD->getParent();
4029 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4030 // FIXME: This same linear search is also used in ExprConstant - it might
4031 // be better if the FieldDecl stored its offset. We'd be increasing the
4032 // size of the object slightly, but saving some time every time it is used.
4033 unsigned i = 0;
4034 for (RecordDecl::field_iterator Field = RD->field_begin(),
4035 FieldEnd = RD->field_end();
4036 Field != FieldEnd; (void)++Field, ++i) {
4037 if (*Field == FD)
4038 break;
4039 }
4040 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004041 if (T->isEnumeralType())
4042 S += 'i';
4043 else
Jay Foad39c79802011-01-12 09:06:06 +00004044 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004045 }
4046 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004047 S += llvm::utostr(N);
4048}
4049
Daniel Dunbar07d07852009-10-18 21:17:35 +00004050// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004051void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4052 bool ExpandPointedToStructures,
4053 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004054 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004055 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00004056 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004057 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004058 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004059 return EncodeBitField(this, S, T, FD);
4060 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004061 return;
4062 }
Mike Stump11289f42009-09-09 15:08:12 +00004063
John McCall9dd450b2009-09-21 23:43:11 +00004064 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004065 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004066 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004067 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004068 return;
4069 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004070
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004071 // encoding for pointer or r3eference types.
4072 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004073 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004074 if (PT->isObjCSelType()) {
4075 S += ':';
4076 return;
4077 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004078 PointeeTy = PT->getPointeeType();
4079 }
4080 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4081 PointeeTy = RT->getPointeeType();
4082 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004083 bool isReadOnly = false;
4084 // For historical/compatibility reasons, the read-only qualifier of the
4085 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4086 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004087 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004088 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004089 if (OutermostType && T.isConstQualified()) {
4090 isReadOnly = true;
4091 S += 'r';
4092 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004093 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004094 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004095 while (P->getAs<PointerType>())
4096 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004097 if (P.isConstQualified()) {
4098 isReadOnly = true;
4099 S += 'r';
4100 }
4101 }
4102 if (isReadOnly) {
4103 // Another legacy compatibility encoding. Some ObjC qualifier and type
4104 // combinations need to be rearranged.
4105 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004106 if (llvm::StringRef(S).endswith("nr"))
4107 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004108 }
Mike Stump11289f42009-09-09 15:08:12 +00004109
Anders Carlssond8499822007-10-29 05:01:08 +00004110 if (PointeeTy->isCharType()) {
4111 // char pointer types should be encoded as '*' unless it is a
4112 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004113 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004114 S += '*';
4115 return;
4116 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004117 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004118 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4119 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4120 S += '#';
4121 return;
4122 }
4123 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4124 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4125 S += '@';
4126 return;
4127 }
4128 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004129 }
Anders Carlssond8499822007-10-29 05:01:08 +00004130 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004131 getLegacyIntegralTypeEncoding(PointeeTy);
4132
Mike Stump11289f42009-09-09 15:08:12 +00004133 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004134 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004135 return;
4136 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004137
Chris Lattnere7cabb92009-07-13 00:10:46 +00004138 if (const ArrayType *AT =
4139 // Ignore type qualifiers etc.
4140 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004141 if (isa<IncompleteArrayType>(AT)) {
4142 // Incomplete arrays are encoded as a pointer to the array element.
4143 S += '^';
4144
Mike Stump11289f42009-09-09 15:08:12 +00004145 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004146 false, ExpandStructures, FD);
4147 } else {
4148 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004149
Anders Carlssond05f44b2009-02-22 01:38:57 +00004150 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4151 S += llvm::utostr(CAT->getSize().getZExtValue());
4152 else {
4153 //Variable length arrays are encoded as a regular array with 0 elements.
4154 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4155 S += '0';
4156 }
Mike Stump11289f42009-09-09 15:08:12 +00004157
4158 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004159 false, ExpandStructures, FD);
4160 S += ']';
4161 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004162 return;
4163 }
Mike Stump11289f42009-09-09 15:08:12 +00004164
John McCall9dd450b2009-09-21 23:43:11 +00004165 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004166 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004167 return;
4168 }
Mike Stump11289f42009-09-09 15:08:12 +00004169
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004170 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004171 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004172 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004173 // Anonymous structures print as '?'
4174 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4175 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004176 if (ClassTemplateSpecializationDecl *Spec
4177 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4178 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4179 std::string TemplateArgsStr
4180 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004181 TemplateArgs.data(),
4182 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004183 (*this).PrintingPolicy);
4184
4185 S += TemplateArgsStr;
4186 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004187 } else {
4188 S += '?';
4189 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004190 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004191 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004192 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4193 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004194 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004195 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004196 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004197 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004198 S += '"';
4199 }
Mike Stump11289f42009-09-09 15:08:12 +00004200
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004201 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004202 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004203 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004204 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004205 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004206 QualType qt = Field->getType();
4207 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004208 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004209 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004210 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004211 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004212 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004213 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004214 return;
4215 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004216
Chris Lattnere7cabb92009-07-13 00:10:46 +00004217 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004218 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004219 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004220 else
4221 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004222 return;
4223 }
Mike Stump11289f42009-09-09 15:08:12 +00004224
Chris Lattnere7cabb92009-07-13 00:10:46 +00004225 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004226 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004227 return;
4228 }
Mike Stump11289f42009-09-09 15:08:12 +00004229
John McCall8b07ec22010-05-15 11:32:37 +00004230 // Ignore protocol qualifiers when mangling at this level.
4231 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4232 T = OT->getBaseType();
4233
John McCall8ccfcb52009-09-24 19:53:00 +00004234 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004235 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004236 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004237 S += '{';
4238 const IdentifierInfo *II = OI->getIdentifier();
4239 S += II->getName();
4240 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004241 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4242 DeepCollectObjCIvars(OI, true, Ivars);
4243 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4244 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4245 if (Field->isBitField())
4246 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004247 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004248 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004249 }
4250 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004251 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004252 }
Mike Stump11289f42009-09-09 15:08:12 +00004253
John McCall9dd450b2009-09-21 23:43:11 +00004254 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004255 if (OPT->isObjCIdType()) {
4256 S += '@';
4257 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004258 }
Mike Stump11289f42009-09-09 15:08:12 +00004259
Steve Narofff0c86112009-10-28 22:03:49 +00004260 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4261 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4262 // Since this is a binary compatibility issue, need to consult with runtime
4263 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004264 S += '#';
4265 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004266 }
Mike Stump11289f42009-09-09 15:08:12 +00004267
Chris Lattnere7cabb92009-07-13 00:10:46 +00004268 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004269 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004270 ExpandPointedToStructures,
4271 ExpandStructures, FD);
4272 if (FD || EncodingProperty) {
4273 // Note that we do extended encoding of protocol qualifer list
4274 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004275 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004276 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4277 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004278 S += '<';
4279 S += (*I)->getNameAsString();
4280 S += '>';
4281 }
4282 S += '"';
4283 }
4284 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004285 }
Mike Stump11289f42009-09-09 15:08:12 +00004286
Chris Lattnere7cabb92009-07-13 00:10:46 +00004287 QualType PointeeTy = OPT->getPointeeType();
4288 if (!EncodingProperty &&
4289 isa<TypedefType>(PointeeTy.getTypePtr())) {
4290 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004291 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004292 // {...};
4293 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004294 getObjCEncodingForTypeImpl(PointeeTy, S,
4295 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004296 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004297 return;
4298 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004299
4300 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004301 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004302 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004303 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004304 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4305 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004306 S += '<';
4307 S += (*I)->getNameAsString();
4308 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004309 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004310 S += '"';
4311 }
4312 return;
4313 }
Mike Stump11289f42009-09-09 15:08:12 +00004314
John McCalla9e6e8d2010-05-17 23:56:34 +00004315 // gcc just blithely ignores member pointers.
4316 // TODO: maybe there should be a mangling for these
4317 if (T->getAs<MemberPointerType>())
4318 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004319
4320 if (T->isVectorType()) {
4321 // This matches gcc's encoding, even though technically it is
4322 // insufficient.
4323 // FIXME. We should do a better job than gcc.
4324 return;
4325 }
4326
Chris Lattnere7cabb92009-07-13 00:10:46 +00004327 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004328}
4329
Mike Stump11289f42009-09-09 15:08:12 +00004330void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004331 std::string& S) const {
4332 if (QT & Decl::OBJC_TQ_In)
4333 S += 'n';
4334 if (QT & Decl::OBJC_TQ_Inout)
4335 S += 'N';
4336 if (QT & Decl::OBJC_TQ_Out)
4337 S += 'o';
4338 if (QT & Decl::OBJC_TQ_Bycopy)
4339 S += 'O';
4340 if (QT & Decl::OBJC_TQ_Byref)
4341 S += 'R';
4342 if (QT & Decl::OBJC_TQ_Oneway)
4343 S += 'V';
4344}
4345
Chris Lattnere7cabb92009-07-13 00:10:46 +00004346void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004347 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004348
Anders Carlsson87c149b2007-10-11 01:00:40 +00004349 BuiltinVaListType = T;
4350}
4351
Chris Lattnere7cabb92009-07-13 00:10:46 +00004352void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004353 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004354}
4355
Chris Lattnere7cabb92009-07-13 00:10:46 +00004356void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004357 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004358}
4359
Chris Lattnere7cabb92009-07-13 00:10:46 +00004360void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004361 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004362}
4363
Chris Lattnere7cabb92009-07-13 00:10:46 +00004364void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004365 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004366}
4367
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004368void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004369 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004370 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004371
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004372 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004373}
4374
John McCalld28ae272009-12-02 08:04:21 +00004375/// \brief Retrieve the template name that corresponds to a non-empty
4376/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004377TemplateName
4378ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4379 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004380 unsigned size = End - Begin;
4381 assert(size > 1 && "set is not overloaded!");
4382
4383 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4384 size * sizeof(FunctionTemplateDecl*));
4385 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4386
4387 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004388 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004389 NamedDecl *D = *I;
4390 assert(isa<FunctionTemplateDecl>(D) ||
4391 (isa<UsingShadowDecl>(D) &&
4392 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4393 *Storage++ = D;
4394 }
4395
4396 return TemplateName(OT);
4397}
4398
Douglas Gregordc572a32009-03-30 22:58:21 +00004399/// \brief Retrieve the template name that represents a qualified
4400/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004401TemplateName
4402ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4403 bool TemplateKeyword,
4404 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004405 assert(NNS && "Missing nested-name-specifier in qualified template name");
4406
Douglas Gregorc42075a2010-02-04 18:10:26 +00004407 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004408 llvm::FoldingSetNodeID ID;
4409 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4410
4411 void *InsertPos = 0;
4412 QualifiedTemplateName *QTN =
4413 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4414 if (!QTN) {
4415 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4416 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4417 }
4418
4419 return TemplateName(QTN);
4420}
4421
4422/// \brief Retrieve the template name that represents a dependent
4423/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004424TemplateName
4425ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4426 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004427 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004428 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004429
4430 llvm::FoldingSetNodeID ID;
4431 DependentTemplateName::Profile(ID, NNS, Name);
4432
4433 void *InsertPos = 0;
4434 DependentTemplateName *QTN =
4435 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4436
4437 if (QTN)
4438 return TemplateName(QTN);
4439
4440 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4441 if (CanonNNS == NNS) {
4442 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4443 } else {
4444 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4445 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004446 DependentTemplateName *CheckQTN =
4447 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4448 assert(!CheckQTN && "Dependent type name canonicalization broken");
4449 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004450 }
4451
4452 DependentTemplateNames.InsertNode(QTN, InsertPos);
4453 return TemplateName(QTN);
4454}
4455
Douglas Gregor71395fa2009-11-04 00:56:37 +00004456/// \brief Retrieve the template name that represents a dependent
4457/// template name such as \c MetaFun::template operator+.
4458TemplateName
4459ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004460 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004461 assert((!NNS || NNS->isDependent()) &&
4462 "Nested name specifier must be dependent");
4463
4464 llvm::FoldingSetNodeID ID;
4465 DependentTemplateName::Profile(ID, NNS, Operator);
4466
4467 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004468 DependentTemplateName *QTN
4469 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004470
4471 if (QTN)
4472 return TemplateName(QTN);
4473
4474 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4475 if (CanonNNS == NNS) {
4476 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4477 } else {
4478 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4479 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004480
4481 DependentTemplateName *CheckQTN
4482 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4483 assert(!CheckQTN && "Dependent template name canonicalization broken");
4484 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004485 }
4486
4487 DependentTemplateNames.InsertNode(QTN, InsertPos);
4488 return TemplateName(QTN);
4489}
4490
Douglas Gregor5590be02011-01-15 06:45:20 +00004491TemplateName
4492ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4493 const TemplateArgument &ArgPack) const {
4494 ASTContext &Self = const_cast<ASTContext &>(*this);
4495 llvm::FoldingSetNodeID ID;
4496 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4497
4498 void *InsertPos = 0;
4499 SubstTemplateTemplateParmPackStorage *Subst
4500 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4501
4502 if (!Subst) {
4503 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4504 ArgPack.pack_size(),
4505 ArgPack.pack_begin());
4506 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4507 }
4508
4509 return TemplateName(Subst);
4510}
4511
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004512/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004513/// TargetInfo, produce the corresponding type. The unsigned @p Type
4514/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004515CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004516 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004517 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004518 case TargetInfo::SignedShort: return ShortTy;
4519 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4520 case TargetInfo::SignedInt: return IntTy;
4521 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4522 case TargetInfo::SignedLong: return LongTy;
4523 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4524 case TargetInfo::SignedLongLong: return LongLongTy;
4525 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4526 }
4527
4528 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004529 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004530}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004531
4532//===----------------------------------------------------------------------===//
4533// Type Predicates.
4534//===----------------------------------------------------------------------===//
4535
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004536/// isObjCNSObjectType - Return true if this is an NSObject object using
4537/// NSObject attribute on a c-style pointer type.
4538/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004539/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004540///
4541bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCall424cec92011-01-19 06:33:43 +00004542 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004543 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004544 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004545 return true;
4546 }
Mike Stump11289f42009-09-09 15:08:12 +00004547 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004548}
4549
Fariborz Jahanian96207692009-02-18 21:49:28 +00004550/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4551/// garbage collection attribute.
4552///
John McCall553d45a2011-01-12 00:34:59 +00004553Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4554 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4555 return Qualifiers::GCNone;
4556
4557 assert(getLangOptions().ObjC1);
4558 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4559
4560 // Default behaviour under objective-C's gc is for ObjC pointers
4561 // (or pointers to them) be treated as though they were declared
4562 // as __strong.
4563 if (GCAttrs == Qualifiers::GCNone) {
4564 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4565 return Qualifiers::Strong;
4566 else if (Ty->isPointerType())
4567 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4568 } else {
4569 // It's not valid to set GC attributes on anything that isn't a
4570 // pointer.
4571#ifndef NDEBUG
4572 QualType CT = Ty->getCanonicalTypeInternal();
4573 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4574 CT = AT->getElementType();
4575 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4576#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004577 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004578 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004579}
4580
Chris Lattner49af6a42008-04-07 06:51:04 +00004581//===----------------------------------------------------------------------===//
4582// Type Compatibility Testing
4583//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004584
Mike Stump11289f42009-09-09 15:08:12 +00004585/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004586/// compatible.
4587static bool areCompatVectorTypes(const VectorType *LHS,
4588 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004589 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004590 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004591 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004592}
4593
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004594bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4595 QualType SecondVec) {
4596 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4597 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4598
4599 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4600 return true;
4601
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004602 // Treat Neon vector types and most AltiVec vector types as if they are the
4603 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004604 const VectorType *First = FirstVec->getAs<VectorType>();
4605 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004606 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004607 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004608 First->getVectorKind() != VectorType::AltiVecPixel &&
4609 First->getVectorKind() != VectorType::AltiVecBool &&
4610 Second->getVectorKind() != VectorType::AltiVecPixel &&
4611 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004612 return true;
4613
4614 return false;
4615}
4616
Steve Naroff8e6aee52009-07-23 01:01:38 +00004617//===----------------------------------------------------------------------===//
4618// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4619//===----------------------------------------------------------------------===//
4620
4621/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4622/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004623bool
4624ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4625 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004626 if (lProto == rProto)
4627 return true;
4628 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4629 E = rProto->protocol_end(); PI != E; ++PI)
4630 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4631 return true;
4632 return false;
4633}
4634
Steve Naroff8e6aee52009-07-23 01:01:38 +00004635/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4636/// return true if lhs's protocols conform to rhs's protocol; false
4637/// otherwise.
4638bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4639 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4640 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4641 return false;
4642}
4643
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004644/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4645/// Class<p1, ...>.
4646bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4647 QualType rhs) {
4648 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4649 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4650 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4651
4652 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4653 E = lhsQID->qual_end(); I != E; ++I) {
4654 bool match = false;
4655 ObjCProtocolDecl *lhsProto = *I;
4656 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4657 E = rhsOPT->qual_end(); J != E; ++J) {
4658 ObjCProtocolDecl *rhsProto = *J;
4659 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4660 match = true;
4661 break;
4662 }
4663 }
4664 if (!match)
4665 return false;
4666 }
4667 return true;
4668}
4669
Steve Naroff8e6aee52009-07-23 01:01:38 +00004670/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4671/// ObjCQualifiedIDType.
4672bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4673 bool compare) {
4674 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004675 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004676 lhs->isObjCIdType() || lhs->isObjCClassType())
4677 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004678 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004679 rhs->isObjCIdType() || rhs->isObjCClassType())
4680 return true;
4681
4682 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004683 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004684
Steve Naroff8e6aee52009-07-23 01:01:38 +00004685 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004686
Steve Naroff8e6aee52009-07-23 01:01:38 +00004687 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004688 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004689 // make sure we check the class hierarchy.
4690 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4691 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4692 E = lhsQID->qual_end(); I != E; ++I) {
4693 // when comparing an id<P> on lhs with a static type on rhs,
4694 // see if static class implements all of id's protocols, directly or
4695 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004696 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004697 return false;
4698 }
4699 }
4700 // If there are no qualifiers and no interface, we have an 'id'.
4701 return true;
4702 }
Mike Stump11289f42009-09-09 15:08:12 +00004703 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004704 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4705 E = lhsQID->qual_end(); I != E; ++I) {
4706 ObjCProtocolDecl *lhsProto = *I;
4707 bool match = false;
4708
4709 // when comparing an id<P> on lhs with a static type on rhs,
4710 // see if static class implements all of id's protocols, directly or
4711 // through its super class and categories.
4712 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4713 E = rhsOPT->qual_end(); J != E; ++J) {
4714 ObjCProtocolDecl *rhsProto = *J;
4715 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4716 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4717 match = true;
4718 break;
4719 }
4720 }
Mike Stump11289f42009-09-09 15:08:12 +00004721 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004722 // make sure we check the class hierarchy.
4723 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4724 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4725 E = lhsQID->qual_end(); I != E; ++I) {
4726 // when comparing an id<P> on lhs with a static type on rhs,
4727 // see if static class implements all of id's protocols, directly or
4728 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004729 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004730 match = true;
4731 break;
4732 }
4733 }
4734 }
4735 if (!match)
4736 return false;
4737 }
Mike Stump11289f42009-09-09 15:08:12 +00004738
Steve Naroff8e6aee52009-07-23 01:01:38 +00004739 return true;
4740 }
Mike Stump11289f42009-09-09 15:08:12 +00004741
Steve Naroff8e6aee52009-07-23 01:01:38 +00004742 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4743 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4744
Mike Stump11289f42009-09-09 15:08:12 +00004745 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004746 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004747 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004748 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4749 E = lhsOPT->qual_end(); I != E; ++I) {
4750 ObjCProtocolDecl *lhsProto = *I;
4751 bool match = false;
4752
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004753 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004754 // see if static class implements all of id's protocols, directly or
4755 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004756 // First, lhs protocols in the qualifier list must be found, direct
4757 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004758 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4759 E = rhsQID->qual_end(); J != E; ++J) {
4760 ObjCProtocolDecl *rhsProto = *J;
4761 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4762 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4763 match = true;
4764 break;
4765 }
4766 }
4767 if (!match)
4768 return false;
4769 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004770
4771 // Static class's protocols, or its super class or category protocols
4772 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4773 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4774 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4775 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4776 // This is rather dubious but matches gcc's behavior. If lhs has
4777 // no type qualifier and its class has no static protocol(s)
4778 // assume that it is mismatch.
4779 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4780 return false;
4781 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4782 LHSInheritedProtocols.begin(),
4783 E = LHSInheritedProtocols.end(); I != E; ++I) {
4784 bool match = false;
4785 ObjCProtocolDecl *lhsProto = (*I);
4786 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4787 E = rhsQID->qual_end(); J != E; ++J) {
4788 ObjCProtocolDecl *rhsProto = *J;
4789 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4790 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4791 match = true;
4792 break;
4793 }
4794 }
4795 if (!match)
4796 return false;
4797 }
4798 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004799 return true;
4800 }
4801 return false;
4802}
4803
Eli Friedman47f77112008-08-22 00:56:42 +00004804/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004805/// compatible for assignment from RHS to LHS. This handles validation of any
4806/// protocol qualifiers on the LHS or RHS.
4807///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004808bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4809 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004810 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4811 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4812
Steve Naroff1329fa02009-07-15 18:40:39 +00004813 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004814 if (LHS->isObjCUnqualifiedIdOrClass() ||
4815 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004816 return true;
4817
John McCall8b07ec22010-05-15 11:32:37 +00004818 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004819 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4820 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004821 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004822
4823 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4824 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4825 QualType(RHSOPT,0));
4826
John McCall8b07ec22010-05-15 11:32:37 +00004827 // If we have 2 user-defined types, fall into that path.
4828 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004829 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004830
Steve Naroff8e6aee52009-07-23 01:01:38 +00004831 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004832}
4833
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004834/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4835/// for providing type-safty for objective-c pointers used to pass/return
4836/// arguments in block literals. When passed as arguments, passing 'A*' where
4837/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4838/// not OK. For the return type, the opposite is not OK.
4839bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4840 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004841 const ObjCObjectPointerType *RHSOPT,
4842 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004843 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004844 return true;
4845
4846 if (LHSOPT->isObjCBuiltinType()) {
4847 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4848 }
4849
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004850 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004851 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4852 QualType(RHSOPT,0),
4853 false);
4854
4855 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4856 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4857 if (LHS && RHS) { // We have 2 user-defined types.
4858 if (LHS != RHS) {
4859 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004860 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004861 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004862 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004863 }
4864 else
4865 return true;
4866 }
4867 return false;
4868}
4869
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004870/// getIntersectionOfProtocols - This routine finds the intersection of set
4871/// of protocols inherited from two distinct objective-c pointer objects.
4872/// It is used to build composite qualifier list of the composite type of
4873/// the conditional expression involving two objective-c pointer objects.
4874static
4875void getIntersectionOfProtocols(ASTContext &Context,
4876 const ObjCObjectPointerType *LHSOPT,
4877 const ObjCObjectPointerType *RHSOPT,
4878 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4879
John McCall8b07ec22010-05-15 11:32:37 +00004880 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4881 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4882 assert(LHS->getInterface() && "LHS must have an interface base");
4883 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004884
4885 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4886 unsigned LHSNumProtocols = LHS->getNumProtocols();
4887 if (LHSNumProtocols > 0)
4888 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4889 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004890 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004891 Context.CollectInheritedProtocols(LHS->getInterface(),
4892 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004893 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4894 LHSInheritedProtocols.end());
4895 }
4896
4897 unsigned RHSNumProtocols = RHS->getNumProtocols();
4898 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004899 ObjCProtocolDecl **RHSProtocols =
4900 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004901 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4902 if (InheritedProtocolSet.count(RHSProtocols[i]))
4903 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4904 }
4905 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004906 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004907 Context.CollectInheritedProtocols(RHS->getInterface(),
4908 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004909 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4910 RHSInheritedProtocols.begin(),
4911 E = RHSInheritedProtocols.end(); I != E; ++I)
4912 if (InheritedProtocolSet.count((*I)))
4913 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004914 }
4915}
4916
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004917/// areCommonBaseCompatible - Returns common base class of the two classes if
4918/// one found. Note that this is O'2 algorithm. But it will be called as the
4919/// last type comparison in a ?-exp of ObjC pointer types before a
4920/// warning is issued. So, its invokation is extremely rare.
4921QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004922 const ObjCObjectPointerType *Lptr,
4923 const ObjCObjectPointerType *Rptr) {
4924 const ObjCObjectType *LHS = Lptr->getObjectType();
4925 const ObjCObjectType *RHS = Rptr->getObjectType();
4926 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4927 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4928 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004929 return QualType();
4930
John McCall8b07ec22010-05-15 11:32:37 +00004931 while ((LDecl = LDecl->getSuperClass())) {
4932 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004933 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004934 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4935 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4936
4937 QualType Result = QualType(LHS, 0);
4938 if (!Protocols.empty())
4939 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4940 Result = getObjCObjectPointerType(Result);
4941 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004942 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004943 }
4944
4945 return QualType();
4946}
4947
John McCall8b07ec22010-05-15 11:32:37 +00004948bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4949 const ObjCObjectType *RHS) {
4950 assert(LHS->getInterface() && "LHS is not an interface type");
4951 assert(RHS->getInterface() && "RHS is not an interface type");
4952
Chris Lattner49af6a42008-04-07 06:51:04 +00004953 // Verify that the base decls are compatible: the RHS must be a subclass of
4954 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004955 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004956 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004957
Chris Lattner49af6a42008-04-07 06:51:04 +00004958 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4959 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004960 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004961 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004962
Chris Lattner49af6a42008-04-07 06:51:04 +00004963 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4964 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004965 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004966 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004967
John McCall8b07ec22010-05-15 11:32:37 +00004968 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4969 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004970 LHSPI != LHSPE; LHSPI++) {
4971 bool RHSImplementsProtocol = false;
4972
4973 // If the RHS doesn't implement the protocol on the left, the types
4974 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004975 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4976 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004977 RHSPI != RHSPE; RHSPI++) {
4978 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004979 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004980 break;
4981 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004982 }
4983 // FIXME: For better diagnostics, consider passing back the protocol name.
4984 if (!RHSImplementsProtocol)
4985 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004986 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004987 // The RHS implements all protocols listed on the LHS.
4988 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004989}
4990
Steve Naroffb7605152009-02-12 17:52:19 +00004991bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4992 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004993 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4994 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004995
Steve Naroff7cae42b2009-07-10 23:34:53 +00004996 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004997 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004998
4999 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5000 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005001}
5002
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005003bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5004 return canAssignObjCInterfaces(
5005 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5006 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5007}
5008
Mike Stump11289f42009-09-09 15:08:12 +00005009/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005010/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005011/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005012/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005013bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5014 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005015 if (getLangOptions().CPlusPlus)
5016 return hasSameType(LHS, RHS);
5017
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005018 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005019}
5020
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005021bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5022 return !mergeTypes(LHS, RHS, true).isNull();
5023}
5024
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005025/// mergeTransparentUnionType - if T is a transparent union type and a member
5026/// of T is compatible with SubType, return the merged type, else return
5027/// QualType()
5028QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5029 bool OfBlockPointer,
5030 bool Unqualified) {
5031 if (const RecordType *UT = T->getAsUnionType()) {
5032 RecordDecl *UD = UT->getDecl();
5033 if (UD->hasAttr<TransparentUnionAttr>()) {
5034 for (RecordDecl::field_iterator it = UD->field_begin(),
5035 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005036 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005037 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5038 if (!MT.isNull())
5039 return MT;
5040 }
5041 }
5042 }
5043
5044 return QualType();
5045}
5046
5047/// mergeFunctionArgumentTypes - merge two types which appear as function
5048/// argument types
5049QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5050 bool OfBlockPointer,
5051 bool Unqualified) {
5052 // GNU extension: two types are compatible if they appear as a function
5053 // argument, one of the types is a transparent union type and the other
5054 // type is compatible with a union member
5055 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5056 Unqualified);
5057 if (!lmerge.isNull())
5058 return lmerge;
5059
5060 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5061 Unqualified);
5062 if (!rmerge.isNull())
5063 return rmerge;
5064
5065 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5066}
5067
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005068QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005069 bool OfBlockPointer,
5070 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005071 const FunctionType *lbase = lhs->getAs<FunctionType>();
5072 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005073 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5074 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005075 bool allLTypes = true;
5076 bool allRTypes = true;
5077
5078 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005079 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005080 if (OfBlockPointer) {
5081 QualType RHS = rbase->getResultType();
5082 QualType LHS = lbase->getResultType();
5083 bool UnqualifiedResult = Unqualified;
5084 if (!UnqualifiedResult)
5085 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005086 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005087 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005088 else
John McCall8c6b56f2010-12-15 01:06:38 +00005089 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5090 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005091 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005092
5093 if (Unqualified)
5094 retType = retType.getUnqualifiedType();
5095
5096 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5097 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5098 if (Unqualified) {
5099 LRetType = LRetType.getUnqualifiedType();
5100 RRetType = RRetType.getUnqualifiedType();
5101 }
5102
5103 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005104 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005105 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005106 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005107
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005108 // FIXME: double check this
5109 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5110 // rbase->getRegParmAttr() != 0 &&
5111 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005112 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5113 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005114
Douglas Gregor8c940862010-01-18 17:14:39 +00005115 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005116 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005117 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005118
John McCall8c6b56f2010-12-15 01:06:38 +00005119 // Regparm is part of the calling convention.
5120 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5121 return QualType();
5122
5123 // It's noreturn if either type is.
5124 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5125 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5126 if (NoReturn != lbaseInfo.getNoReturn())
5127 allLTypes = false;
5128 if (NoReturn != rbaseInfo.getNoReturn())
5129 allRTypes = false;
5130
5131 FunctionType::ExtInfo einfo(NoReturn,
5132 lbaseInfo.getRegParm(),
5133 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00005134
Eli Friedman47f77112008-08-22 00:56:42 +00005135 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005136 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5137 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005138 unsigned lproto_nargs = lproto->getNumArgs();
5139 unsigned rproto_nargs = rproto->getNumArgs();
5140
5141 // Compatible functions must have the same number of arguments
5142 if (lproto_nargs != rproto_nargs)
5143 return QualType();
5144
5145 // Variadic and non-variadic functions aren't compatible
5146 if (lproto->isVariadic() != rproto->isVariadic())
5147 return QualType();
5148
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005149 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5150 return QualType();
5151
Eli Friedman47f77112008-08-22 00:56:42 +00005152 // Check argument compatibility
5153 llvm::SmallVector<QualType, 10> types;
5154 for (unsigned i = 0; i < lproto_nargs; i++) {
5155 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5156 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005157 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5158 OfBlockPointer,
5159 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005160 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005161
5162 if (Unqualified)
5163 argtype = argtype.getUnqualifiedType();
5164
Eli Friedman47f77112008-08-22 00:56:42 +00005165 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005166 if (Unqualified) {
5167 largtype = largtype.getUnqualifiedType();
5168 rargtype = rargtype.getUnqualifiedType();
5169 }
5170
Chris Lattner465fa322008-10-05 17:34:18 +00005171 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5172 allLTypes = false;
5173 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5174 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005175 }
5176 if (allLTypes) return lhs;
5177 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005178
5179 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5180 EPI.ExtInfo = einfo;
5181 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005182 }
5183
5184 if (lproto) allRTypes = false;
5185 if (rproto) allLTypes = false;
5186
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005187 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005188 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005189 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005190 if (proto->isVariadic()) return QualType();
5191 // Check that the types are compatible with the types that
5192 // would result from default argument promotions (C99 6.7.5.3p15).
5193 // The only types actually affected are promotable integer
5194 // types and floats, which would be passed as a different
5195 // type depending on whether the prototype is visible.
5196 unsigned proto_nargs = proto->getNumArgs();
5197 for (unsigned i = 0; i < proto_nargs; ++i) {
5198 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005199
5200 // Look at the promotion type of enum types, since that is the type used
5201 // to pass enum values.
5202 if (const EnumType *Enum = argTy->getAs<EnumType>())
5203 argTy = Enum->getDecl()->getPromotionType();
5204
Eli Friedman47f77112008-08-22 00:56:42 +00005205 if (argTy->isPromotableIntegerType() ||
5206 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5207 return QualType();
5208 }
5209
5210 if (allLTypes) return lhs;
5211 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005212
5213 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5214 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005215 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005216 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005217 }
5218
5219 if (allLTypes) return lhs;
5220 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005221 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005222}
5223
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005224QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005225 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005226 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005227 // C++ [expr]: If an expression initially has the type "reference to T", the
5228 // type is adjusted to "T" prior to any further analysis, the expression
5229 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005230 // expression is an lvalue unless the reference is an rvalue reference and
5231 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005232 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5233 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005234
5235 if (Unqualified) {
5236 LHS = LHS.getUnqualifiedType();
5237 RHS = RHS.getUnqualifiedType();
5238 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005239
Eli Friedman47f77112008-08-22 00:56:42 +00005240 QualType LHSCan = getCanonicalType(LHS),
5241 RHSCan = getCanonicalType(RHS);
5242
5243 // If two types are identical, they are compatible.
5244 if (LHSCan == RHSCan)
5245 return LHS;
5246
John McCall8ccfcb52009-09-24 19:53:00 +00005247 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005248 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5249 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005250 if (LQuals != RQuals) {
5251 // If any of these qualifiers are different, we have a type
5252 // mismatch.
5253 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5254 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5255 return QualType();
5256
5257 // Exactly one GC qualifier difference is allowed: __strong is
5258 // okay if the other type has no GC qualifier but is an Objective
5259 // C object pointer (i.e. implicitly strong by default). We fix
5260 // this by pretending that the unqualified type was actually
5261 // qualified __strong.
5262 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5263 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5264 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5265
5266 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5267 return QualType();
5268
5269 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5270 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5271 }
5272 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5273 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5274 }
Eli Friedman47f77112008-08-22 00:56:42 +00005275 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005276 }
5277
5278 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005279
Eli Friedmandcca6332009-06-01 01:22:52 +00005280 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5281 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005282
Chris Lattnerfd652912008-01-14 05:45:46 +00005283 // We want to consider the two function types to be the same for these
5284 // comparisons, just force one to the other.
5285 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5286 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005287
5288 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005289 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5290 LHSClass = Type::ConstantArray;
5291 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5292 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005293
John McCall8b07ec22010-05-15 11:32:37 +00005294 // ObjCInterfaces are just specialized ObjCObjects.
5295 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5296 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5297
Nate Begemance4d7fc2008-04-18 23:10:10 +00005298 // Canonicalize ExtVector -> Vector.
5299 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5300 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005301
Chris Lattner95554662008-04-07 05:43:21 +00005302 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005303 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005304 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005305 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005306 // Compatibility is based on the underlying type, not the promotion
5307 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005308 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005309 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5310 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005311 }
John McCall9dd450b2009-09-21 23:43:11 +00005312 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005313 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5314 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005315 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005316
Eli Friedman47f77112008-08-22 00:56:42 +00005317 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005318 }
Eli Friedman47f77112008-08-22 00:56:42 +00005319
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005320 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005321 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005322#define TYPE(Class, Base)
5323#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005324#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005325#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5326#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5327#include "clang/AST/TypeNodes.def"
5328 assert(false && "Non-canonical and dependent types shouldn't get here");
5329 return QualType();
5330
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005331 case Type::LValueReference:
5332 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005333 case Type::MemberPointer:
5334 assert(false && "C++ should never be in mergeTypes");
5335 return QualType();
5336
John McCall8b07ec22010-05-15 11:32:37 +00005337 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005338 case Type::IncompleteArray:
5339 case Type::VariableArray:
5340 case Type::FunctionProto:
5341 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005342 assert(false && "Types are eliminated above");
5343 return QualType();
5344
Chris Lattnerfd652912008-01-14 05:45:46 +00005345 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005346 {
5347 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005348 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5349 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005350 if (Unqualified) {
5351 LHSPointee = LHSPointee.getUnqualifiedType();
5352 RHSPointee = RHSPointee.getUnqualifiedType();
5353 }
5354 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5355 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005356 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005357 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005358 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005359 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005360 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005361 return getPointerType(ResultType);
5362 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005363 case Type::BlockPointer:
5364 {
5365 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005366 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5367 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005368 if (Unqualified) {
5369 LHSPointee = LHSPointee.getUnqualifiedType();
5370 RHSPointee = RHSPointee.getUnqualifiedType();
5371 }
5372 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5373 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005374 if (ResultType.isNull()) return QualType();
5375 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5376 return LHS;
5377 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5378 return RHS;
5379 return getBlockPointerType(ResultType);
5380 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005381 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005382 {
5383 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5384 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5385 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5386 return QualType();
5387
5388 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5389 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005390 if (Unqualified) {
5391 LHSElem = LHSElem.getUnqualifiedType();
5392 RHSElem = RHSElem.getUnqualifiedType();
5393 }
5394
5395 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005396 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005397 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5398 return LHS;
5399 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5400 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005401 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5402 ArrayType::ArraySizeModifier(), 0);
5403 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5404 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005405 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5406 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005407 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5408 return LHS;
5409 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5410 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005411 if (LVAT) {
5412 // FIXME: This isn't correct! But tricky to implement because
5413 // the array's size has to be the size of LHS, but the type
5414 // has to be different.
5415 return LHS;
5416 }
5417 if (RVAT) {
5418 // FIXME: This isn't correct! But tricky to implement because
5419 // the array's size has to be the size of RHS, but the type
5420 // has to be different.
5421 return RHS;
5422 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005423 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5424 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005425 return getIncompleteArrayType(ResultType,
5426 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005427 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005428 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005429 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005430 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005431 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005432 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005433 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005434 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005435 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005436 case Type::Complex:
5437 // Distinct complex types are incompatible.
5438 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005439 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005440 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005441 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5442 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005443 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005444 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005445 case Type::ObjCObject: {
5446 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005447 // FIXME: This should be type compatibility, e.g. whether
5448 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005449 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5450 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5451 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005452 return LHS;
5453
Eli Friedman47f77112008-08-22 00:56:42 +00005454 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005455 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005456 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005457 if (OfBlockPointer) {
5458 if (canAssignObjCInterfacesInBlockPointer(
5459 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005460 RHS->getAs<ObjCObjectPointerType>(),
5461 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005462 return LHS;
5463 return QualType();
5464 }
John McCall9dd450b2009-09-21 23:43:11 +00005465 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5466 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005467 return LHS;
5468
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005469 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005470 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005471 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005472
5473 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005474}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005475
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005476/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5477/// 'RHS' attributes and returns the merged version; including for function
5478/// return types.
5479QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5480 QualType LHSCan = getCanonicalType(LHS),
5481 RHSCan = getCanonicalType(RHS);
5482 // If two types are identical, they are compatible.
5483 if (LHSCan == RHSCan)
5484 return LHS;
5485 if (RHSCan->isFunctionType()) {
5486 if (!LHSCan->isFunctionType())
5487 return QualType();
5488 QualType OldReturnType =
5489 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5490 QualType NewReturnType =
5491 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5492 QualType ResReturnType =
5493 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5494 if (ResReturnType.isNull())
5495 return QualType();
5496 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5497 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5498 // In either case, use OldReturnType to build the new function type.
5499 const FunctionType *F = LHS->getAs<FunctionType>();
5500 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005501 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5502 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005503 QualType ResultType
5504 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005505 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005506 return ResultType;
5507 }
5508 }
5509 return QualType();
5510 }
5511
5512 // If the qualifiers are different, the types can still be merged.
5513 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5514 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5515 if (LQuals != RQuals) {
5516 // If any of these qualifiers are different, we have a type mismatch.
5517 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5518 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5519 return QualType();
5520
5521 // Exactly one GC qualifier difference is allowed: __strong is
5522 // okay if the other type has no GC qualifier but is an Objective
5523 // C object pointer (i.e. implicitly strong by default). We fix
5524 // this by pretending that the unqualified type was actually
5525 // qualified __strong.
5526 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5527 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5528 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5529
5530 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5531 return QualType();
5532
5533 if (GC_L == Qualifiers::Strong)
5534 return LHS;
5535 if (GC_R == Qualifiers::Strong)
5536 return RHS;
5537 return QualType();
5538 }
5539
5540 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5541 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5542 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5543 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5544 if (ResQT == LHSBaseQT)
5545 return LHS;
5546 if (ResQT == RHSBaseQT)
5547 return RHS;
5548 }
5549 return QualType();
5550}
5551
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005552//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005553// Integer Predicates
5554//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005555
Jay Foad39c79802011-01-12 09:06:06 +00005556unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005557 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005558 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005559 if (T->isBooleanType())
5560 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005561 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005562 return (unsigned)getTypeSize(T);
5563}
5564
5565QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005566 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005567
5568 // Turn <4 x signed int> -> <4 x unsigned int>
5569 if (const VectorType *VTy = T->getAs<VectorType>())
5570 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005571 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005572
5573 // For enums, we return the unsigned version of the base type.
5574 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005575 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005576
5577 const BuiltinType *BTy = T->getAs<BuiltinType>();
5578 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005579 switch (BTy->getKind()) {
5580 case BuiltinType::Char_S:
5581 case BuiltinType::SChar:
5582 return UnsignedCharTy;
5583 case BuiltinType::Short:
5584 return UnsignedShortTy;
5585 case BuiltinType::Int:
5586 return UnsignedIntTy;
5587 case BuiltinType::Long:
5588 return UnsignedLongTy;
5589 case BuiltinType::LongLong:
5590 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005591 case BuiltinType::Int128:
5592 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005593 default:
5594 assert(0 && "Unexpected signed integer type");
5595 return QualType();
5596 }
5597}
5598
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005599ASTMutationListener::~ASTMutationListener() { }
5600
Chris Lattnerecd79c62009-06-14 00:45:47 +00005601
5602//===----------------------------------------------------------------------===//
5603// Builtin Type Computation
5604//===----------------------------------------------------------------------===//
5605
5606/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005607/// pointer over the consumed characters. This returns the resultant type. If
5608/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5609/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5610/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005611///
5612/// RequiresICE is filled in on return to indicate whether the value is required
5613/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005614static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005615 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005616 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005617 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005618 // Modifiers.
5619 int HowLong = 0;
5620 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005621 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005622
Chris Lattnerdc226c22010-10-01 22:42:38 +00005623 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005624 bool Done = false;
5625 while (!Done) {
5626 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005627 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005628 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005629 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005630 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005631 case 'S':
5632 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5633 assert(!Signed && "Can't use 'S' modifier multiple times!");
5634 Signed = true;
5635 break;
5636 case 'U':
5637 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5638 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5639 Unsigned = true;
5640 break;
5641 case 'L':
5642 assert(HowLong <= 2 && "Can't have LLLL modifier");
5643 ++HowLong;
5644 break;
5645 }
5646 }
5647
5648 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005649
Chris Lattnerecd79c62009-06-14 00:45:47 +00005650 // Read the base type.
5651 switch (*Str++) {
5652 default: assert(0 && "Unknown builtin type letter!");
5653 case 'v':
5654 assert(HowLong == 0 && !Signed && !Unsigned &&
5655 "Bad modifiers used with 'v'!");
5656 Type = Context.VoidTy;
5657 break;
5658 case 'f':
5659 assert(HowLong == 0 && !Signed && !Unsigned &&
5660 "Bad modifiers used with 'f'!");
5661 Type = Context.FloatTy;
5662 break;
5663 case 'd':
5664 assert(HowLong < 2 && !Signed && !Unsigned &&
5665 "Bad modifiers used with 'd'!");
5666 if (HowLong)
5667 Type = Context.LongDoubleTy;
5668 else
5669 Type = Context.DoubleTy;
5670 break;
5671 case 's':
5672 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5673 if (Unsigned)
5674 Type = Context.UnsignedShortTy;
5675 else
5676 Type = Context.ShortTy;
5677 break;
5678 case 'i':
5679 if (HowLong == 3)
5680 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5681 else if (HowLong == 2)
5682 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5683 else if (HowLong == 1)
5684 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5685 else
5686 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5687 break;
5688 case 'c':
5689 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5690 if (Signed)
5691 Type = Context.SignedCharTy;
5692 else if (Unsigned)
5693 Type = Context.UnsignedCharTy;
5694 else
5695 Type = Context.CharTy;
5696 break;
5697 case 'b': // boolean
5698 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5699 Type = Context.BoolTy;
5700 break;
5701 case 'z': // size_t.
5702 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5703 Type = Context.getSizeType();
5704 break;
5705 case 'F':
5706 Type = Context.getCFConstantStringType();
5707 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005708 case 'G':
5709 Type = Context.getObjCIdType();
5710 break;
5711 case 'H':
5712 Type = Context.getObjCSelType();
5713 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005714 case 'a':
5715 Type = Context.getBuiltinVaListType();
5716 assert(!Type.isNull() && "builtin va list type not initialized!");
5717 break;
5718 case 'A':
5719 // This is a "reference" to a va_list; however, what exactly
5720 // this means depends on how va_list is defined. There are two
5721 // different kinds of va_list: ones passed by value, and ones
5722 // passed by reference. An example of a by-value va_list is
5723 // x86, where va_list is a char*. An example of by-ref va_list
5724 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5725 // we want this argument to be a char*&; for x86-64, we want
5726 // it to be a __va_list_tag*.
5727 Type = Context.getBuiltinVaListType();
5728 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005729 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005730 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005731 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005732 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005733 break;
5734 case 'V': {
5735 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005736 unsigned NumElements = strtoul(Str, &End, 10);
5737 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005738 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005739
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005740 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5741 RequiresICE, false);
5742 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005743
5744 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005745 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005746 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005747 break;
5748 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005749 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005750 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5751 false);
5752 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005753 Type = Context.getComplexType(ElementType);
5754 break;
5755 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005756 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005757 Type = Context.getFILEType();
5758 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005759 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005760 return QualType();
5761 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005762 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005763 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005764 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005765 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005766 else
5767 Type = Context.getjmp_bufType();
5768
Mike Stump2adb4da2009-07-28 23:47:15 +00005769 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005770 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005771 return QualType();
5772 }
5773 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005774 }
Mike Stump11289f42009-09-09 15:08:12 +00005775
Chris Lattnerdc226c22010-10-01 22:42:38 +00005776 // If there are modifiers and if we're allowed to parse them, go for it.
5777 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005778 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005779 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005780 default: Done = true; --Str; break;
5781 case '*':
5782 case '&': {
5783 // Both pointers and references can have their pointee types
5784 // qualified with an address space.
5785 char *End;
5786 unsigned AddrSpace = strtoul(Str, &End, 10);
5787 if (End != Str && AddrSpace != 0) {
5788 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5789 Str = End;
5790 }
5791 if (c == '*')
5792 Type = Context.getPointerType(Type);
5793 else
5794 Type = Context.getLValueReferenceType(Type);
5795 break;
5796 }
5797 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5798 case 'C':
5799 Type = Type.withConst();
5800 break;
5801 case 'D':
5802 Type = Context.getVolatileType(Type);
5803 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005804 }
5805 }
Chris Lattner84733392010-10-01 07:13:18 +00005806
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005807 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005808 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005809
Chris Lattnerecd79c62009-06-14 00:45:47 +00005810 return Type;
5811}
5812
5813/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005814QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005815 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005816 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005817 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005818
Chris Lattnerecd79c62009-06-14 00:45:47 +00005819 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005820
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005821 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005822 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005823 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5824 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005825 if (Error != GE_None)
5826 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005827
5828 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5829
Chris Lattnerecd79c62009-06-14 00:45:47 +00005830 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005831 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005832 if (Error != GE_None)
5833 return QualType();
5834
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005835 // If this argument is required to be an IntegerConstantExpression and the
5836 // caller cares, fill in the bitmask we return.
5837 if (RequiresICE && IntegerConstantArgs)
5838 *IntegerConstantArgs |= 1 << ArgTypes.size();
5839
Chris Lattnerecd79c62009-06-14 00:45:47 +00005840 // Do array -> pointer decay. The builtin should use the decayed type.
5841 if (Ty->isArrayType())
5842 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005843
Chris Lattnerecd79c62009-06-14 00:45:47 +00005844 ArgTypes.push_back(Ty);
5845 }
5846
5847 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5848 "'.' should only occur at end of builtin type list!");
5849
John McCall991eb4b2010-12-21 00:44:39 +00005850 FunctionType::ExtInfo EI;
5851 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5852
5853 bool Variadic = (TypeStr[0] == '.');
5854
5855 // We really shouldn't be making a no-proto type here, especially in C++.
5856 if (ArgTypes.empty() && Variadic)
5857 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005858
John McCalldb40c7f2010-12-14 08:05:40 +00005859 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005860 EPI.ExtInfo = EI;
5861 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00005862
5863 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005864}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005865
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005866GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5867 GVALinkage External = GVA_StrongExternal;
5868
5869 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005870 switch (L) {
5871 case NoLinkage:
5872 case InternalLinkage:
5873 case UniqueExternalLinkage:
5874 return GVA_Internal;
5875
5876 case ExternalLinkage:
5877 switch (FD->getTemplateSpecializationKind()) {
5878 case TSK_Undeclared:
5879 case TSK_ExplicitSpecialization:
5880 External = GVA_StrongExternal;
5881 break;
5882
5883 case TSK_ExplicitInstantiationDefinition:
5884 return GVA_ExplicitTemplateInstantiation;
5885
5886 case TSK_ExplicitInstantiationDeclaration:
5887 case TSK_ImplicitInstantiation:
5888 External = GVA_TemplateInstantiation;
5889 break;
5890 }
5891 }
5892
5893 if (!FD->isInlined())
5894 return External;
5895
5896 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5897 // GNU or C99 inline semantics. Determine whether this symbol should be
5898 // externally visible.
5899 if (FD->isInlineDefinitionExternallyVisible())
5900 return External;
5901
5902 // C99 inline semantics, where the symbol is not externally visible.
5903 return GVA_C99Inline;
5904 }
5905
5906 // C++0x [temp.explicit]p9:
5907 // [ Note: The intent is that an inline function that is the subject of
5908 // an explicit instantiation declaration will still be implicitly
5909 // instantiated when used so that the body can be considered for
5910 // inlining, but that no out-of-line copy of the inline function would be
5911 // generated in the translation unit. -- end note ]
5912 if (FD->getTemplateSpecializationKind()
5913 == TSK_ExplicitInstantiationDeclaration)
5914 return GVA_C99Inline;
5915
5916 return GVA_CXXInline;
5917}
5918
5919GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5920 // If this is a static data member, compute the kind of template
5921 // specialization. Otherwise, this variable is not part of a
5922 // template.
5923 TemplateSpecializationKind TSK = TSK_Undeclared;
5924 if (VD->isStaticDataMember())
5925 TSK = VD->getTemplateSpecializationKind();
5926
5927 Linkage L = VD->getLinkage();
5928 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5929 VD->getType()->getLinkage() == UniqueExternalLinkage)
5930 L = UniqueExternalLinkage;
5931
5932 switch (L) {
5933 case NoLinkage:
5934 case InternalLinkage:
5935 case UniqueExternalLinkage:
5936 return GVA_Internal;
5937
5938 case ExternalLinkage:
5939 switch (TSK) {
5940 case TSK_Undeclared:
5941 case TSK_ExplicitSpecialization:
5942 return GVA_StrongExternal;
5943
5944 case TSK_ExplicitInstantiationDeclaration:
5945 llvm_unreachable("Variable should not be instantiated");
5946 // Fall through to treat this like any other instantiation.
5947
5948 case TSK_ExplicitInstantiationDefinition:
5949 return GVA_ExplicitTemplateInstantiation;
5950
5951 case TSK_ImplicitInstantiation:
5952 return GVA_TemplateInstantiation;
5953 }
5954 }
5955
5956 return GVA_StrongExternal;
5957}
5958
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005959bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005960 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5961 if (!VD->isFileVarDecl())
5962 return false;
5963 } else if (!isa<FunctionDecl>(D))
5964 return false;
5965
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005966 // Weak references don't produce any output by themselves.
5967 if (D->hasAttr<WeakRefAttr>())
5968 return false;
5969
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005970 // Aliases and used decls are required.
5971 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5972 return true;
5973
5974 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5975 // Forward declarations aren't required.
5976 if (!FD->isThisDeclarationADefinition())
5977 return false;
5978
5979 // Constructors and destructors are required.
5980 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5981 return true;
5982
5983 // The key function for a class is required.
5984 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5985 const CXXRecordDecl *RD = MD->getParent();
5986 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5987 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5988 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5989 return true;
5990 }
5991 }
5992
5993 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5994
5995 // static, static inline, always_inline, and extern inline functions can
5996 // always be deferred. Normal inline functions can be deferred in C99/C++.
5997 // Implicit template instantiations can also be deferred in C++.
5998 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5999 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6000 return false;
6001 return true;
6002 }
6003
6004 const VarDecl *VD = cast<VarDecl>(D);
6005 assert(VD->isFileVarDecl() && "Expected file scoped var");
6006
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006007 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6008 return false;
6009
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006010 // Structs that have non-trivial constructors or destructors are required.
6011
6012 // FIXME: Handle references.
6013 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6014 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006015 if (RD->hasDefinition() &&
6016 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006017 return true;
6018 }
6019 }
6020
6021 GVALinkage L = GetGVALinkageForVariable(VD);
6022 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6023 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6024 return false;
6025 }
6026
6027 return true;
6028}
Charles Davis53c59df2010-08-16 03:33:14 +00006029
Charles Davis99202b32010-11-09 18:04:24 +00006030CallingConv ASTContext::getDefaultMethodCallConv() {
6031 // Pass through to the C++ ABI object
6032 return ABI->getDefaultMethodCallConv();
6033}
6034
Jay Foad39c79802011-01-12 09:06:06 +00006035bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006036 // Pass through to the C++ ABI object
6037 return ABI->isNearlyEmpty(RD);
6038}
6039
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006040MangleContext *ASTContext::createMangleContext() {
6041 switch (Target.getCXXABI()) {
6042 case CXXABI_ARM:
6043 case CXXABI_Itanium:
6044 return createItaniumMangleContext(*this, getDiagnostics());
6045 case CXXABI_Microsoft:
6046 return createMicrosoftMangleContext(*this, getDiagnostics());
6047 }
6048 assert(0 && "Unsupported ABI");
6049 return 0;
6050}
6051
Charles Davis53c59df2010-08-16 03:33:14 +00006052CXXABI::~CXXABI() {}