blob: 5335a8b0c88edf52f918abffba576223923ca7fc [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000033#include "CXXABI.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000034
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
36
Douglas Gregor18274032010-07-03 00:47:00 +000037unsigned ASTContext::NumImplicitDefaultConstructors;
38unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000039unsigned ASTContext::NumImplicitCopyConstructors;
40unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000041unsigned ASTContext::NumImplicitCopyAssignmentOperators;
42unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000043unsigned ASTContext::NumImplicitDestructors;
44unsigned ASTContext::NumImplicitDestructorsDeclared;
45
Reid Spencer5f016e22007-07-11 17:01:13 +000046enum FloatingRank {
47 FloatRank, DoubleRank, LongDoubleRank
48};
49
Douglas Gregor3e1274f2010-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 Gregor61c4d282011-01-05 15:48:55 +000055 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-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 Gregor61c4d282011-01-05 15:48:55 +000070 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000071 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-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 Gregor3e1274f2010-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 Foad4ba2a172011-01-12 09:06:06 +000090 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000091 // Check if we already have a canonical template template parameter.
92 llvm::FoldingSetNodeID ID;
93 CanonicalTemplateTemplateParm::Profile(ID, TTP);
94 void *InsertPos = 0;
95 CanonicalTemplateTemplateParm *Canonical
96 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
97 if (Canonical)
98 return Canonical->getParam();
99
100 // Build a canonical template parameter list.
101 TemplateParameterList *Params = TTP->getTemplateParameters();
102 llvm::SmallVector<NamedDecl *, 4> CanonParams;
103 CanonParams.reserve(Params->size());
104 for (TemplateParameterList::const_iterator P = Params->begin(),
105 PEnd = Params->end();
106 P != PEnd; ++P) {
107 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
108 CanonParams.push_back(
109 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
110 SourceLocation(), TTP->getDepth(),
111 TTP->getIndex(), 0, false,
112 TTP->isParameterPack()));
113 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000114 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
115 QualType T = getCanonicalType(NTTP->getType());
116 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
117 NonTypeTemplateParmDecl *Param;
118 if (NTTP->isExpandedParameterPack()) {
119 llvm::SmallVector<QualType, 2> ExpandedTypes;
120 llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
121 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
122 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
123 ExpandedTInfos.push_back(
124 getTrivialTypeSourceInfo(ExpandedTypes.back()));
125 }
126
127 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
128 SourceLocation(),
129 NTTP->getDepth(),
130 NTTP->getPosition(), 0,
131 T,
132 TInfo,
133 ExpandedTypes.data(),
134 ExpandedTypes.size(),
135 ExpandedTInfos.data());
136 } else {
137 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
138 SourceLocation(),
139 NTTP->getDepth(),
140 NTTP->getPosition(), 0,
141 T,
142 NTTP->isParameterPack(),
143 TInfo);
144 }
145 CanonParams.push_back(Param);
146
147 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000148 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
149 cast<TemplateTemplateParmDecl>(*P)));
150 }
151
152 TemplateTemplateParmDecl *CanonTTP
153 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
154 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000155 TTP->getPosition(),
156 TTP->isParameterPack(),
157 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000158 TemplateParameterList::Create(*this, SourceLocation(),
159 SourceLocation(),
160 CanonParams.data(),
161 CanonParams.size(),
162 SourceLocation()));
163
164 // Get the new insert position for the node we care about.
165 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
166 assert(Canonical == 0 && "Shouldn't be in the map!");
167 (void)Canonical;
168
169 // Create the canonical template template parameter entry.
170 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
171 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
172 return CanonTTP;
173}
174
Charles Davis071cc7d2010-08-16 03:33:14 +0000175CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000176 if (!LangOpts.CPlusPlus) return 0;
177
Charles Davis20cf7172010-08-19 02:18:14 +0000178 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000179 case CXXABI_ARM:
180 return CreateARMCXXABI(*this);
181 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000182 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000183 case CXXABI_Microsoft:
184 return CreateMicrosoftCXXABI(*this);
185 }
John McCallee79a4c2010-08-21 22:46:04 +0000186 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000187}
188
Chris Lattner61710852008-10-05 17:34:18 +0000189ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000190 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000191 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000192 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000193 unsigned size_reserve) :
John McCallef990012010-06-11 11:07:21 +0000194 TemplateSpecializationTypes(this_()),
195 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000196 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
197 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000198 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000199 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Peter Collingbourne14b6ba72011-02-09 21:04:32 +0000200 cudaConfigureCallDecl(0),
John McCallbf1a0282010-06-04 23:28:52 +0000201 NullTypeSourceInfo(QualType()),
Charles Davis071cc7d2010-08-16 03:33:14 +0000202 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000203 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000204 BuiltinInfo(builtins),
205 DeclarationNames(*this),
Argyrios Kyrtzidis9a44b5f2010-10-28 09:29:35 +0000206 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000207 LastSDM(0, 0),
John McCall8178df32011-02-22 22:38:33 +0000208 UniqueBlockByRefTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000209 ObjCIdRedefinitionType = QualType();
210 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000211 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000212 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000213 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000214 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000215}
216
Reid Spencer5f016e22007-07-11 17:01:13 +0000217ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000218 // Release the DenseMaps associated with DeclContext objects.
219 // FIXME: Is this the ideal solution?
220 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000221
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000222 // Call all of the deallocation functions.
223 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
224 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000225
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000226 // Release all of the memory associated with overridden C++ methods.
227 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
228 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
229 OM != OMEnd; ++OM)
230 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000231
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000232 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000233 // because they can contain DenseMaps.
234 for (llvm::DenseMap<const ObjCContainerDecl*,
235 const ASTRecordLayout*>::iterator
236 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
237 // Increment in loop to prevent using deallocated memory.
238 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
239 R->Destroy(*this);
240
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000241 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
242 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
243 // Increment in loop to prevent using deallocated memory.
244 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
245 R->Destroy(*this);
246 }
Douglas Gregor63200642010-08-30 16:49:28 +0000247
248 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
249 AEnd = DeclAttrs.end();
250 A != AEnd; ++A)
251 A->second->~AttrVec();
252}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000253
Douglas Gregor00545312010-05-23 18:26:36 +0000254void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
255 Deallocations.push_back(std::make_pair(Callback, Data));
256}
257
Mike Stump1eb44332009-09-09 15:08:12 +0000258void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000259ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
260 ExternalSource.reset(Source.take());
261}
262
Reid Spencer5f016e22007-07-11 17:01:13 +0000263void ASTContext::PrintStats() const {
264 fprintf(stderr, "*** AST Context Stats:\n");
265 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000266
Douglas Gregordbe833d2009-05-26 14:40:08 +0000267 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000268#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000269#define ABSTRACT_TYPE(Name, Parent)
270#include "clang/AST/TypeNodes.def"
271 0 // Extra
272 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000273
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
275 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000276 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 }
278
Douglas Gregordbe833d2009-05-26 14:40:08 +0000279 unsigned Idx = 0;
280 unsigned TotalBytes = 0;
281#define TYPE(Name, Parent) \
282 if (counts[Idx]) \
283 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
284 TotalBytes += counts[Idx] * sizeof(Name##Type); \
285 ++Idx;
286#define ABSTRACT_TYPE(Name, Parent)
287#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000288
Douglas Gregordbe833d2009-05-26 14:40:08 +0000289 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000290
Douglas Gregor4923aa22010-07-02 20:37:36 +0000291 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000292 fprintf(stderr, " %u/%u implicit default constructors created\n",
293 NumImplicitDefaultConstructorsDeclared,
294 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000295 fprintf(stderr, " %u/%u implicit copy constructors created\n",
296 NumImplicitCopyConstructorsDeclared,
297 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000298 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
299 NumImplicitCopyAssignmentOperatorsDeclared,
300 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000301 fprintf(stderr, " %u/%u implicit destructors created\n",
302 NumImplicitDestructorsDeclared, NumImplicitDestructors);
303
Douglas Gregor2cf26342009-04-09 22:27:44 +0000304 if (ExternalSource.get()) {
305 fprintf(stderr, "\n");
306 ExternalSource->PrintStats();
307 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000308
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000309 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000310}
311
312
John McCalle27ec8a2009-10-23 23:03:21 +0000313void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000314 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000315 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000316 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000317}
318
Reid Spencer5f016e22007-07-11 17:01:13 +0000319void ASTContext::InitBuiltinTypes() {
320 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Reid Spencer5f016e22007-07-11 17:01:13 +0000322 // C99 6.2.5p19.
323 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 // C99 6.2.5p2.
326 InitBuiltinType(BoolTy, BuiltinType::Bool);
327 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000328 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 InitBuiltinType(CharTy, BuiltinType::Char_S);
330 else
331 InitBuiltinType(CharTy, BuiltinType::Char_U);
332 // C99 6.2.5p4.
333 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
334 InitBuiltinType(ShortTy, BuiltinType::Short);
335 InitBuiltinType(IntTy, BuiltinType::Int);
336 InitBuiltinType(LongTy, BuiltinType::Long);
337 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Reid Spencer5f016e22007-07-11 17:01:13 +0000339 // C99 6.2.5p6.
340 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
341 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
342 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
343 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
344 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 // C99 6.2.5p10.
347 InitBuiltinType(FloatTy, BuiltinType::Float);
348 InitBuiltinType(DoubleTy, BuiltinType::Double);
349 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000350
Chris Lattner2df9ced2009-04-30 02:43:43 +0000351 // GNU extension, 128-bit integers.
352 InitBuiltinType(Int128Ty, BuiltinType::Int128);
353 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
354
Chris Lattner3f59c972010-12-25 23:25:43 +0000355 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
356 if (!LangOpts.ShortWChar)
357 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
358 else // -fshort-wchar makes wchar_t be unsigned.
359 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
360 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000361 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000362
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000363 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
364 InitBuiltinType(Char16Ty, BuiltinType::Char16);
365 else // C99
366 Char16Ty = getFromTargetType(Target.getChar16Type());
367
368 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
369 InitBuiltinType(Char32Ty, BuiltinType::Char32);
370 else // C99
371 Char32Ty = getFromTargetType(Target.getChar32Type());
372
Douglas Gregor898574e2008-12-05 23:32:09 +0000373 // Placeholder type for type-dependent expressions whose type is
374 // completely unknown. No code should ever check a type against
375 // DependentTy and users should never see it; however, it is here to
376 // help diagnose failures to properly check for type-dependent
377 // expressions.
378 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000379
John McCall2a984ca2010-10-12 00:20:44 +0000380 // Placeholder type for functions.
381 InitBuiltinType(OverloadTy, BuiltinType::Overload);
382
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 // C99 6.2.5p11.
384 FloatComplexTy = getComplexType(FloatTy);
385 DoubleComplexTy = getComplexType(DoubleTy);
386 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000387
Steve Naroff7e219e42007-10-15 14:41:52 +0000388 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Steve Naroffde2e22d2009-07-15 18:40:39 +0000390 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
391 ObjCIdTypedefType = QualType();
392 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000393 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000395 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000396 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
397 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000398 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000399
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000400 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000402 // void * type
403 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000404
405 // nullptr type (C++0x 2.14.7)
406 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000407}
408
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000409Diagnostic &ASTContext::getDiagnostics() const {
410 return SourceMgr.getDiagnostics();
411}
412
Douglas Gregor63200642010-08-30 16:49:28 +0000413AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
414 AttrVec *&Result = DeclAttrs[D];
415 if (!Result) {
416 void *Mem = Allocate(sizeof(AttrVec));
417 Result = new (Mem) AttrVec;
418 }
419
420 return *Result;
421}
422
423/// \brief Erase the attributes corresponding to the given declaration.
424void ASTContext::eraseDeclAttrs(const Decl *D) {
425 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
426 if (Pos != DeclAttrs.end()) {
427 Pos->second->~AttrVec();
428 DeclAttrs.erase(Pos);
429 }
430}
431
432
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000433MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000434ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000435 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000436 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000437 = InstantiatedFromStaticDataMember.find(Var);
438 if (Pos == InstantiatedFromStaticDataMember.end())
439 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Douglas Gregor7caa6822009-07-24 20:34:43 +0000441 return Pos->second;
442}
443
Mike Stump1eb44332009-09-09 15:08:12 +0000444void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000445ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000446 TemplateSpecializationKind TSK,
447 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000448 assert(Inst->isStaticDataMember() && "Not a static data member");
449 assert(Tmpl->isStaticDataMember() && "Not a static data member");
450 assert(!InstantiatedFromStaticDataMember[Inst] &&
451 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000452 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000453 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000454}
455
John McCall7ba107a2009-11-18 02:36:19 +0000456NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000457ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000458 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000459 = InstantiatedFromUsingDecl.find(UUD);
460 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000461 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Anders Carlsson0d8df782009-08-29 19:37:28 +0000463 return Pos->second;
464}
465
466void
John McCalled976492009-12-04 22:46:56 +0000467ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
468 assert((isa<UsingDecl>(Pattern) ||
469 isa<UnresolvedUsingValueDecl>(Pattern) ||
470 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
471 "pattern decl is not a using decl");
472 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
473 InstantiatedFromUsingDecl[Inst] = Pattern;
474}
475
476UsingShadowDecl *
477ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
478 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
479 = InstantiatedFromUsingShadowDecl.find(Inst);
480 if (Pos == InstantiatedFromUsingShadowDecl.end())
481 return 0;
482
483 return Pos->second;
484}
485
486void
487ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
488 UsingShadowDecl *Pattern) {
489 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
490 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000491}
492
Anders Carlssond8b285f2009-09-01 04:26:58 +0000493FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
494 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
495 = InstantiatedFromUnnamedFieldDecl.find(Field);
496 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
497 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Anders Carlssond8b285f2009-09-01 04:26:58 +0000499 return Pos->second;
500}
501
502void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
503 FieldDecl *Tmpl) {
504 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
505 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
506 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
507 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Anders Carlssond8b285f2009-09-01 04:26:58 +0000509 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
510}
511
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000512ASTContext::overridden_cxx_method_iterator
513ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
514 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
515 = OverriddenMethods.find(Method);
516 if (Pos == OverriddenMethods.end())
517 return 0;
518
519 return Pos->second.begin();
520}
521
522ASTContext::overridden_cxx_method_iterator
523ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
524 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
525 = OverriddenMethods.find(Method);
526 if (Pos == OverriddenMethods.end())
527 return 0;
528
529 return Pos->second.end();
530}
531
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000532unsigned
533ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
534 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
535 = OverriddenMethods.find(Method);
536 if (Pos == OverriddenMethods.end())
537 return 0;
538
539 return Pos->second.size();
540}
541
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000542void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
543 const CXXMethodDecl *Overridden) {
544 OverriddenMethods[Method].push_back(Overridden);
545}
546
Chris Lattner464175b2007-07-18 17:52:12 +0000547//===----------------------------------------------------------------------===//
548// Type Sizing and Analysis
549//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000550
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000551/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
552/// scalar floating point type.
553const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000554 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000555 assert(BT && "Not a floating point type!");
556 switch (BT->getKind()) {
557 default: assert(0 && "Not a floating point type!");
558 case BuiltinType::Float: return Target.getFloatFormat();
559 case BuiltinType::Double: return Target.getDoubleFormat();
560 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
561 }
562}
563
Ken Dyck8b752f12010-01-27 17:10:57 +0000564/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000565/// specified decl. Note that bitfields do not have a valid alignment, so
566/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000567/// If @p RefAsPointee, references are treated like their underlying type
568/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000569CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000570 unsigned Align = Target.getCharWidth();
571
John McCall4081a5c2010-10-08 18:24:19 +0000572 bool UseAlignAttrOnly = false;
573 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
574 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000575
John McCall4081a5c2010-10-08 18:24:19 +0000576 // __attribute__((aligned)) can increase or decrease alignment
577 // *except* on a struct or struct member, where it only increases
578 // alignment unless 'packed' is also specified.
579 //
580 // It is an error for [[align]] to decrease alignment, so we can
581 // ignore that possibility; Sema should diagnose it.
582 if (isa<FieldDecl>(D)) {
583 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
584 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
585 } else {
586 UseAlignAttrOnly = true;
587 }
588 }
589
John McCallba4f5d52011-01-20 07:57:12 +0000590 // If we're using the align attribute only, just ignore everything
591 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000592 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000593 // do nothing
594
John McCall4081a5c2010-10-08 18:24:19 +0000595 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000596 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000597 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000598 if (RefAsPointee)
599 T = RT->getPointeeType();
600 else
601 T = getPointerType(RT->getPointeeType());
602 }
603 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000604 // Adjust alignments of declarations with array type by the
605 // large-array alignment on the target.
Rafael Espindola6deecb02010-06-04 23:15:27 +0000606 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000607 const ArrayType *arrayType;
608 if (MinWidth && (arrayType = getAsArrayType(T))) {
609 if (isa<VariableArrayType>(arrayType))
610 Align = std::max(Align, Target.getLargeArrayAlign());
611 else if (isa<ConstantArrayType>(arrayType) &&
612 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
613 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000614
John McCall3b657512011-01-19 10:06:00 +0000615 // Walk through any array types while we're at it.
616 T = getBaseElementType(arrayType);
617 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000618 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
619 }
John McCallba4f5d52011-01-20 07:57:12 +0000620
621 // Fields can be subject to extra alignment constraints, like if
622 // the field is packed, the struct is packed, or the struct has a
623 // a max-field-alignment constraint (#pragma pack). So calculate
624 // the actual alignment of the field within the struct, and then
625 // (as we're expected to) constrain that by the alignment of the type.
626 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
627 // So calculate the alignment of the field.
628 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
629
630 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000631 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000632
633 // Use the GCD of that and the offset within the record.
634 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
635 if (offset > 0) {
636 // Alignment is always a power of 2, so the GCD will be a power of 2,
637 // which means we get to do this crazy thing instead of Euclid's.
638 uint64_t lowBitOfOffset = offset & (~offset + 1);
639 if (lowBitOfOffset < fieldAlign)
640 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
641 }
642
643 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000644 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000645 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000646
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000647 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000648}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000649
John McCallea1471e2010-05-20 01:18:31 +0000650std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000651ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000652 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000653 return std::make_pair(toCharUnitsFromBits(Info.first),
654 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000655}
656
657std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000658ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000659 return getTypeInfoInChars(T.getTypePtr());
660}
661
Chris Lattnera7674d82007-07-13 22:13:22 +0000662/// getTypeSize - Return the size of the specified type, in bits. This method
663/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000664///
665/// FIXME: Pointers into different addr spaces could have different sizes and
666/// alignment requirements: getPointerInfo should take an AddrSpace, this
667/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000668std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000669ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000670 uint64_t Width=0;
671 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000672 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000673#define TYPE(Class, Base)
674#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000675#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000676#define DEPENDENT_TYPE(Class, Base) case Type::Class:
677#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000678 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000679 break;
680
Chris Lattner692233e2007-07-13 22:27:08 +0000681 case Type::FunctionNoProto:
682 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000683 // GCC extension: alignof(function) = 32 bits
684 Width = 0;
685 Align = 32;
686 break;
687
Douglas Gregor72564e72009-02-26 23:50:07 +0000688 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000689 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000690 Width = 0;
691 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
692 break;
693
Steve Narofffb22d962007-08-30 01:06:46 +0000694 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000695 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Chris Lattner98be4942008-03-05 18:54:05 +0000697 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000698 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000699 Align = EltInfo.second;
700 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000701 }
Nate Begeman213541a2008-04-18 23:10:10 +0000702 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000703 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000704 const VectorType *VT = cast<VectorType>(T);
705 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
706 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000707 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000708 // If the alignment is not a power of 2, round up to the next power of 2.
709 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000710 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000711 Align = llvm::NextPowerOf2(Align);
712 Width = llvm::RoundUpToAlignment(Width, Align);
713 }
Chris Lattner030d8842007-07-19 22:06:24 +0000714 break;
715 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000716
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000717 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000718 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000719 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000720 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000721 // GCC extension: alignof(void) = 8 bits.
722 Width = 0;
723 Align = 8;
724 break;
725
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000726 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000727 Width = Target.getBoolWidth();
728 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000729 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000730 case BuiltinType::Char_S:
731 case BuiltinType::Char_U:
732 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000733 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000734 Width = Target.getCharWidth();
735 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000736 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000737 case BuiltinType::WChar_S:
738 case BuiltinType::WChar_U:
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000739 Width = Target.getWCharWidth();
740 Align = Target.getWCharAlign();
741 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000742 case BuiltinType::Char16:
743 Width = Target.getChar16Width();
744 Align = Target.getChar16Align();
745 break;
746 case BuiltinType::Char32:
747 Width = Target.getChar32Width();
748 Align = Target.getChar32Align();
749 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000750 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000751 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000752 Width = Target.getShortWidth();
753 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000754 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000755 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000756 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000757 Width = Target.getIntWidth();
758 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000759 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000760 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000761 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000762 Width = Target.getLongWidth();
763 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000764 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000765 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000766 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000767 Width = Target.getLongLongWidth();
768 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000769 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000770 case BuiltinType::Int128:
771 case BuiltinType::UInt128:
772 Width = 128;
773 Align = 128; // int128_t is 128-bit aligned on all targets.
774 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000775 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000776 Width = Target.getFloatWidth();
777 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000778 break;
779 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000780 Width = Target.getDoubleWidth();
781 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000782 break;
783 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000784 Width = Target.getLongDoubleWidth();
785 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000786 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000787 case BuiltinType::NullPtr:
788 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
789 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000790 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000791 case BuiltinType::ObjCId:
792 case BuiltinType::ObjCClass:
793 case BuiltinType::ObjCSel:
794 Width = Target.getPointerWidth(0);
795 Align = Target.getPointerAlign(0);
796 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000797 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000798 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000799 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000800 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000801 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000802 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000803 case Type::BlockPointer: {
804 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
805 Width = Target.getPointerWidth(AS);
806 Align = Target.getPointerAlign(AS);
807 break;
808 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000809 case Type::LValueReference:
810 case Type::RValueReference: {
811 // alignof and sizeof should never enter this code path here, so we go
812 // the pointer route.
813 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
814 Width = Target.getPointerWidth(AS);
815 Align = Target.getPointerAlign(AS);
816 break;
817 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000818 case Type::Pointer: {
819 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000820 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000821 Align = Target.getPointerAlign(AS);
822 break;
823 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000824 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000825 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000826 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000827 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000828 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000829 Align = PtrDiffInfo.second;
830 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000831 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000832 case Type::Complex: {
833 // Complex types have the same alignment as their elements, but twice the
834 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000835 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000836 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000837 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000838 Align = EltInfo.second;
839 break;
840 }
John McCallc12c5bb2010-05-15 11:32:37 +0000841 case Type::ObjCObject:
842 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000843 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000844 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000845 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000846 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000847 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +0000848 break;
849 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000850 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000851 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000852 const TagType *TT = cast<TagType>(T);
853
854 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000855 Width = 1;
856 Align = 1;
857 break;
858 }
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Daniel Dunbar1d751182008-11-08 05:48:37 +0000860 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000861 return getTypeInfo(ET->getDecl()->getIntegerType());
862
Daniel Dunbar1d751182008-11-08 05:48:37 +0000863 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000864 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000865 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000866 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000867 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000868 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000869
Chris Lattner9fcfe922009-10-22 05:17:15 +0000870 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000871 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
872 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000873
Richard Smith34b41d92011-02-20 03:19:35 +0000874 case Type::Auto: {
875 const AutoType *A = cast<AutoType>(T);
876 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +0000877 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +0000878 }
879
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000880 case Type::Paren:
881 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
882
Douglas Gregor18857642009-04-30 17:32:17 +0000883 case Type::Typedef: {
884 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000885 std::pair<uint64_t, unsigned> Info
886 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +0000887 // If the typedef has an aligned attribute on it, it overrides any computed
888 // alignment we have. This violates the GCC documentation (which says that
889 // attribute(aligned) can only round up) but matches its implementation.
890 if (unsigned AttrAlign = Typedef->getMaxAlignment())
891 Align = AttrAlign;
892 else
893 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +0000894 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000895 break;
Chris Lattner71763312008-04-06 22:05:18 +0000896 }
Douglas Gregor18857642009-04-30 17:32:17 +0000897
898 case Type::TypeOfExpr:
899 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
900 .getTypePtr());
901
902 case Type::TypeOf:
903 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
904
Anders Carlsson395b4752009-06-24 19:06:50 +0000905 case Type::Decltype:
906 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
907 .getTypePtr());
908
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000909 case Type::Elaborated:
910 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000911
John McCall9d156a72011-01-06 01:58:22 +0000912 case Type::Attributed:
913 return getTypeInfo(
914 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
915
Douglas Gregor18857642009-04-30 17:32:17 +0000916 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000917 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000918 "Cannot request the size of a dependent type");
919 // FIXME: this is likely to be wrong once we support template
920 // aliases, since a template alias could refer to a typedef that
921 // has an __aligned__ attribute on it.
922 return getTypeInfo(getCanonicalType(T));
923 }
Mike Stump1eb44332009-09-09 15:08:12 +0000924
Chris Lattner464175b2007-07-18 17:52:12 +0000925 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000926 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000927}
928
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000929/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
930CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
931 return CharUnits::fromQuantity(BitSize / getCharWidth());
932}
933
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000934/// toBits - Convert a size in characters to a size in characters.
935int64_t ASTContext::toBits(CharUnits CharSize) const {
936 return CharSize.getQuantity() * getCharWidth();
937}
938
Ken Dyckbdc601b2009-12-22 14:23:30 +0000939/// getTypeSizeInChars - Return the size of the specified type, in characters.
940/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +0000941CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000942 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +0000943}
Jay Foad4ba2a172011-01-12 09:06:06 +0000944CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000945 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +0000946}
947
Ken Dyck16e20cc2010-01-26 17:25:18 +0000948/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000949/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +0000950CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000951 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +0000952}
Jay Foad4ba2a172011-01-12 09:06:06 +0000953CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000954 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +0000955}
956
Chris Lattner34ebde42009-01-27 18:08:34 +0000957/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
958/// type for the current target in bits. This can be different than the ABI
959/// alignment in cases where it is beneficial for performance to overalign
960/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +0000961unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +0000962 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000963
964 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000965 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000966 T = CT->getElementType().getTypePtr();
967 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
968 T->isSpecificBuiltinType(BuiltinType::LongLong))
969 return std::max(ABIAlign, (unsigned)getTypeSize(T));
970
Chris Lattner34ebde42009-01-27 18:08:34 +0000971 return ABIAlign;
972}
973
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000974/// ShallowCollectObjCIvars -
975/// Collect all ivars, including those synthesized, in the current class.
976///
977void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad4ba2a172011-01-12 09:06:06 +0000978 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000979 // FIXME. This need be removed but there are two many places which
980 // assume const-ness of ObjCInterfaceDecl
981 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
982 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
983 Iv= Iv->getNextIvar())
984 Ivars.push_back(Iv);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000985}
986
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000987/// DeepCollectObjCIvars -
988/// This routine first collects all declared, but not synthesized, ivars in
989/// super class and then collects all ivars, including those synthesized for
990/// current class. This routine is used for implementation of current class
991/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000992///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000993void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
994 bool leafClass,
Jay Foad4ba2a172011-01-12 09:06:06 +0000995 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000996 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
997 DeepCollectObjCIvars(SuperClass, false, Ivars);
998 if (!leafClass) {
999 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1000 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001001 Ivars.push_back(*I);
1002 }
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001003 else
1004 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian98200742009-05-12 18:14:29 +00001005}
1006
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001007/// CollectInheritedProtocols - Collect all protocols in current class and
1008/// those inherited by it.
1009void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001010 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001011 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001012 // We can use protocol_iterator here instead of
1013 // all_referenced_protocol_iterator since we are walking all categories.
1014 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1015 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001016 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001017 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001018 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001019 PE = Proto->protocol_end(); P != PE; ++P) {
1020 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001021 CollectInheritedProtocols(*P, Protocols);
1022 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001023 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001024
1025 // Categories of this Interface.
1026 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1027 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1028 CollectInheritedProtocols(CDeclChain, Protocols);
1029 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1030 while (SD) {
1031 CollectInheritedProtocols(SD, Protocols);
1032 SD = SD->getSuperClass();
1033 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001034 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001035 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001036 PE = OC->protocol_end(); P != PE; ++P) {
1037 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001038 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001039 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1040 PE = Proto->protocol_end(); P != PE; ++P)
1041 CollectInheritedProtocols(*P, Protocols);
1042 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001043 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001044 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1045 PE = OP->protocol_end(); P != PE; ++P) {
1046 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001047 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001048 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1049 PE = Proto->protocol_end(); P != PE; ++P)
1050 CollectInheritedProtocols(*P, Protocols);
1051 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001052 }
1053}
1054
Jay Foad4ba2a172011-01-12 09:06:06 +00001055unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001056 unsigned count = 0;
1057 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001058 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1059 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001060 count += CDecl->ivar_size();
1061
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001062 // Count ivar defined in this class's implementation. This
1063 // includes synthesized ivars.
1064 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001065 count += ImplDecl->ivar_size();
1066
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001067 return count;
1068}
1069
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001070/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1071ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1072 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1073 I = ObjCImpls.find(D);
1074 if (I != ObjCImpls.end())
1075 return cast<ObjCImplementationDecl>(I->second);
1076 return 0;
1077}
1078/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1079ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1080 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1081 I = ObjCImpls.find(D);
1082 if (I != ObjCImpls.end())
1083 return cast<ObjCCategoryImplDecl>(I->second);
1084 return 0;
1085}
1086
1087/// \brief Set the implementation of ObjCInterfaceDecl.
1088void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1089 ObjCImplementationDecl *ImplD) {
1090 assert(IFaceD && ImplD && "Passed null params");
1091 ObjCImpls[IFaceD] = ImplD;
1092}
1093/// \brief Set the implementation of ObjCCategoryDecl.
1094void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1095 ObjCCategoryImplDecl *ImplD) {
1096 assert(CatD && ImplD && "Passed null params");
1097 ObjCImpls[CatD] = ImplD;
1098}
1099
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001100/// \brief Get the copy initialization expression of VarDecl,or NULL if
1101/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001102Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001103 assert(VD && "Passed null params");
1104 assert(VD->hasAttr<BlocksAttr>() &&
1105 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001106 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001107 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001108 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1109}
1110
1111/// \brief Set the copy inialization expression of a block var decl.
1112void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1113 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001114 assert(VD->hasAttr<BlocksAttr>() &&
1115 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001116 BlockVarCopyInits[VD] = Init;
1117}
1118
John McCalla93c9342009-12-07 02:54:59 +00001119/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001120///
John McCalla93c9342009-12-07 02:54:59 +00001121/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001122/// the TypeLoc wrappers.
1123///
1124/// \param T the type that will be the basis for type source info. This type
1125/// should refer to how the declarator was written in source code, not to
1126/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001127TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001128 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001129 if (!DataSize)
1130 DataSize = TypeLoc::getFullDataSizeForType(T);
1131 else
1132 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001133 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001134
John McCalla93c9342009-12-07 02:54:59 +00001135 TypeSourceInfo *TInfo =
1136 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1137 new (TInfo) TypeSourceInfo(T);
1138 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001139}
1140
John McCalla93c9342009-12-07 02:54:59 +00001141TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001142 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001143 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001144 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001145 return DI;
1146}
1147
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001148const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001149ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001150 return getObjCLayout(D, 0);
1151}
1152
1153const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001154ASTContext::getASTObjCImplementationLayout(
1155 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001156 return getObjCLayout(D->getClassInterface(), D);
1157}
1158
Chris Lattnera7674d82007-07-13 22:13:22 +00001159//===----------------------------------------------------------------------===//
1160// Type creation/memoization methods
1161//===----------------------------------------------------------------------===//
1162
Jay Foad4ba2a172011-01-12 09:06:06 +00001163QualType
John McCall3b657512011-01-19 10:06:00 +00001164ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1165 unsigned fastQuals = quals.getFastQualifiers();
1166 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001167
1168 // Check if we've already instantiated this type.
1169 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001170 ExtQuals::Profile(ID, baseType, quals);
1171 void *insertPos = 0;
1172 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1173 assert(eq->getQualifiers() == quals);
1174 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001175 }
1176
John McCall3b657512011-01-19 10:06:00 +00001177 // If the base type is not canonical, make the appropriate canonical type.
1178 QualType canon;
1179 if (!baseType->isCanonicalUnqualified()) {
1180 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1181 canonSplit.second.addConsistentQualifiers(quals);
1182 canon = getExtQualType(canonSplit.first, canonSplit.second);
1183
1184 // Re-find the insert position.
1185 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1186 }
1187
1188 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1189 ExtQualNodes.InsertNode(eq, insertPos);
1190 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001191}
1192
Jay Foad4ba2a172011-01-12 09:06:06 +00001193QualType
1194ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001195 QualType CanT = getCanonicalType(T);
1196 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001197 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001198
John McCall0953e762009-09-24 19:53:00 +00001199 // If we are composing extended qualifiers together, merge together
1200 // into one ExtQuals node.
1201 QualifierCollector Quals;
1202 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001203
John McCall0953e762009-09-24 19:53:00 +00001204 // If this type already has an address space specified, it cannot get
1205 // another one.
1206 assert(!Quals.hasAddressSpace() &&
1207 "Type cannot be in multiple addr spaces!");
1208 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001209
John McCall0953e762009-09-24 19:53:00 +00001210 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001211}
1212
Chris Lattnerb7d25532009-02-18 22:53:11 +00001213QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001214 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001215 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001216 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001217 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001218
John McCall7f040a92010-12-24 02:08:15 +00001219 if (const PointerType *ptr = T->getAs<PointerType>()) {
1220 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001221 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001222 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1223 return getPointerType(ResultType);
1224 }
1225 }
Mike Stump1eb44332009-09-09 15:08:12 +00001226
John McCall0953e762009-09-24 19:53:00 +00001227 // If we are composing extended qualifiers together, merge together
1228 // into one ExtQuals node.
1229 QualifierCollector Quals;
1230 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001231
John McCall0953e762009-09-24 19:53:00 +00001232 // If this type already has an ObjCGC specified, it cannot get
1233 // another one.
1234 assert(!Quals.hasObjCGCAttr() &&
1235 "Type cannot have multiple ObjCGCs!");
1236 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001237
John McCall0953e762009-09-24 19:53:00 +00001238 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001239}
Chris Lattnera7674d82007-07-13 22:13:22 +00001240
John McCalle6a365d2010-12-19 02:44:49 +00001241const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1242 FunctionType::ExtInfo Info) {
1243 if (T->getExtInfo() == Info)
1244 return T;
1245
1246 QualType Result;
1247 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1248 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1249 } else {
1250 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1251 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1252 EPI.ExtInfo = Info;
1253 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1254 FPT->getNumArgs(), EPI);
1255 }
1256
1257 return cast<FunctionType>(Result.getTypePtr());
1258}
1259
Reid Spencer5f016e22007-07-11 17:01:13 +00001260/// getComplexType - Return the uniqued reference to the type for a complex
1261/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001262QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 // Unique pointers, to guarantee there is only one pointer of a particular
1264 // structure.
1265 llvm::FoldingSetNodeID ID;
1266 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Reid Spencer5f016e22007-07-11 17:01:13 +00001268 void *InsertPos = 0;
1269 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1270 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 // If the pointee type isn't canonical, this won't be a canonical type either,
1273 // so fill in the canonical type field.
1274 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001275 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001276 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 // Get the new insert position for the node we care about.
1279 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001280 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001281 }
John McCall6b304a02009-09-24 23:30:46 +00001282 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 Types.push_back(New);
1284 ComplexTypes.InsertNode(New, InsertPos);
1285 return QualType(New, 0);
1286}
1287
Reid Spencer5f016e22007-07-11 17:01:13 +00001288/// getPointerType - Return the uniqued reference to the type for a pointer to
1289/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001290QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 // Unique pointers, to guarantee there is only one pointer of a particular
1292 // structure.
1293 llvm::FoldingSetNodeID ID;
1294 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 void *InsertPos = 0;
1297 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1298 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001299
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 // If the pointee type isn't canonical, this won't be a canonical type either,
1301 // so fill in the canonical type field.
1302 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001303 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001304 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 // Get the new insert position for the node we care about.
1307 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001308 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001309 }
John McCall6b304a02009-09-24 23:30:46 +00001310 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001311 Types.push_back(New);
1312 PointerTypes.InsertNode(New, InsertPos);
1313 return QualType(New, 0);
1314}
1315
Mike Stump1eb44332009-09-09 15:08:12 +00001316/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001317/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001318QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001319 assert(T->isFunctionType() && "block of function types only");
1320 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001321 // structure.
1322 llvm::FoldingSetNodeID ID;
1323 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001324
Steve Naroff5618bd42008-08-27 16:04:49 +00001325 void *InsertPos = 0;
1326 if (BlockPointerType *PT =
1327 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1328 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001329
1330 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001331 // type either so fill in the canonical type field.
1332 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001333 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001334 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001335
Steve Naroff5618bd42008-08-27 16:04:49 +00001336 // Get the new insert position for the node we care about.
1337 BlockPointerType *NewIP =
1338 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001339 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001340 }
John McCall6b304a02009-09-24 23:30:46 +00001341 BlockPointerType *New
1342 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001343 Types.push_back(New);
1344 BlockPointerTypes.InsertNode(New, InsertPos);
1345 return QualType(New, 0);
1346}
1347
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001348/// getLValueReferenceType - Return the uniqued reference to the type for an
1349/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001350QualType
1351ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001352 // Unique pointers, to guarantee there is only one pointer of a particular
1353 // structure.
1354 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001355 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001356
1357 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001358 if (LValueReferenceType *RT =
1359 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001361
John McCall54e14c42009-10-22 22:37:11 +00001362 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1363
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 // If the referencee type isn't canonical, this won't be a canonical type
1365 // either, so fill in the canonical type field.
1366 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001367 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1368 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1369 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001370
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001372 LValueReferenceType *NewIP =
1373 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001374 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 }
1376
John McCall6b304a02009-09-24 23:30:46 +00001377 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001378 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1379 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001381 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001382
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001383 return QualType(New, 0);
1384}
1385
1386/// getRValueReferenceType - Return the uniqued reference to the type for an
1387/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001388QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001389 // Unique pointers, to guarantee there is only one pointer of a particular
1390 // structure.
1391 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001392 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001393
1394 void *InsertPos = 0;
1395 if (RValueReferenceType *RT =
1396 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1397 return QualType(RT, 0);
1398
John McCall54e14c42009-10-22 22:37:11 +00001399 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1400
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001401 // If the referencee type isn't canonical, this won't be a canonical type
1402 // either, so fill in the canonical type field.
1403 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001404 if (InnerRef || !T.isCanonical()) {
1405 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1406 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001407
1408 // Get the new insert position for the node we care about.
1409 RValueReferenceType *NewIP =
1410 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001411 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001412 }
1413
John McCall6b304a02009-09-24 23:30:46 +00001414 RValueReferenceType *New
1415 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001416 Types.push_back(New);
1417 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 return QualType(New, 0);
1419}
1420
Sebastian Redlf30208a2009-01-24 21:16:55 +00001421/// getMemberPointerType - Return the uniqued reference to the type for a
1422/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001423QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001424 // Unique pointers, to guarantee there is only one pointer of a particular
1425 // structure.
1426 llvm::FoldingSetNodeID ID;
1427 MemberPointerType::Profile(ID, T, Cls);
1428
1429 void *InsertPos = 0;
1430 if (MemberPointerType *PT =
1431 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1432 return QualType(PT, 0);
1433
1434 // If the pointee or class type isn't canonical, this won't be a canonical
1435 // type either, so fill in the canonical type field.
1436 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001437 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001438 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1439
1440 // Get the new insert position for the node we care about.
1441 MemberPointerType *NewIP =
1442 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001443 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001444 }
John McCall6b304a02009-09-24 23:30:46 +00001445 MemberPointerType *New
1446 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001447 Types.push_back(New);
1448 MemberPointerTypes.InsertNode(New, InsertPos);
1449 return QualType(New, 0);
1450}
1451
Mike Stump1eb44332009-09-09 15:08:12 +00001452/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001453/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001454QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001455 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001456 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001457 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001458 assert((EltTy->isDependentType() ||
1459 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001460 "Constant array of VLAs is illegal!");
1461
Chris Lattner38aeec72009-05-13 04:12:56 +00001462 // Convert the array size into a canonical width matching the pointer size for
1463 // the target.
1464 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001465 ArySize =
1466 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Reid Spencer5f016e22007-07-11 17:01:13 +00001468 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001469 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Reid Spencer5f016e22007-07-11 17:01:13 +00001471 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001472 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001473 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001474 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001475
John McCall3b657512011-01-19 10:06:00 +00001476 // If the element type isn't canonical or has qualifiers, this won't
1477 // be a canonical type either, so fill in the canonical type field.
1478 QualType Canon;
1479 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1480 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1481 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001482 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001483 Canon = getQualifiedType(Canon, canonSplit.second);
1484
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001486 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001487 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001488 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 }
Mike Stump1eb44332009-09-09 15:08:12 +00001490
John McCall6b304a02009-09-24 23:30:46 +00001491 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001492 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001493 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 Types.push_back(New);
1495 return QualType(New, 0);
1496}
1497
John McCallce889032011-01-18 08:40:38 +00001498/// getVariableArrayDecayedType - Turns the given type, which may be
1499/// variably-modified, into the corresponding type with all the known
1500/// sizes replaced with [*].
1501QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1502 // Vastly most common case.
1503 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001504
John McCallce889032011-01-18 08:40:38 +00001505 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001506
John McCallce889032011-01-18 08:40:38 +00001507 SplitQualType split = type.getSplitDesugaredType();
1508 const Type *ty = split.first;
1509 switch (ty->getTypeClass()) {
1510#define TYPE(Class, Base)
1511#define ABSTRACT_TYPE(Class, Base)
1512#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1513#include "clang/AST/TypeNodes.def"
1514 llvm_unreachable("didn't desugar past all non-canonical types?");
1515
1516 // These types should never be variably-modified.
1517 case Type::Builtin:
1518 case Type::Complex:
1519 case Type::Vector:
1520 case Type::ExtVector:
1521 case Type::DependentSizedExtVector:
1522 case Type::ObjCObject:
1523 case Type::ObjCInterface:
1524 case Type::ObjCObjectPointer:
1525 case Type::Record:
1526 case Type::Enum:
1527 case Type::UnresolvedUsing:
1528 case Type::TypeOfExpr:
1529 case Type::TypeOf:
1530 case Type::Decltype:
1531 case Type::DependentName:
1532 case Type::InjectedClassName:
1533 case Type::TemplateSpecialization:
1534 case Type::DependentTemplateSpecialization:
1535 case Type::TemplateTypeParm:
1536 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001537 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001538 case Type::PackExpansion:
1539 llvm_unreachable("type should never be variably-modified");
1540
1541 // These types can be variably-modified but should never need to
1542 // further decay.
1543 case Type::FunctionNoProto:
1544 case Type::FunctionProto:
1545 case Type::BlockPointer:
1546 case Type::MemberPointer:
1547 return type;
1548
1549 // These types can be variably-modified. All these modifications
1550 // preserve structure except as noted by comments.
1551 // TODO: if we ever care about optimizing VLAs, there are no-op
1552 // optimizations available here.
1553 case Type::Pointer:
1554 result = getPointerType(getVariableArrayDecayedType(
1555 cast<PointerType>(ty)->getPointeeType()));
1556 break;
1557
1558 case Type::LValueReference: {
1559 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1560 result = getLValueReferenceType(
1561 getVariableArrayDecayedType(lv->getPointeeType()),
1562 lv->isSpelledAsLValue());
1563 break;
1564 }
1565
1566 case Type::RValueReference: {
1567 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1568 result = getRValueReferenceType(
1569 getVariableArrayDecayedType(lv->getPointeeType()));
1570 break;
1571 }
1572
1573 case Type::ConstantArray: {
1574 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1575 result = getConstantArrayType(
1576 getVariableArrayDecayedType(cat->getElementType()),
1577 cat->getSize(),
1578 cat->getSizeModifier(),
1579 cat->getIndexTypeCVRQualifiers());
1580 break;
1581 }
1582
1583 case Type::DependentSizedArray: {
1584 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1585 result = getDependentSizedArrayType(
1586 getVariableArrayDecayedType(dat->getElementType()),
1587 dat->getSizeExpr(),
1588 dat->getSizeModifier(),
1589 dat->getIndexTypeCVRQualifiers(),
1590 dat->getBracketsRange());
1591 break;
1592 }
1593
1594 // Turn incomplete types into [*] types.
1595 case Type::IncompleteArray: {
1596 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1597 result = getVariableArrayType(
1598 getVariableArrayDecayedType(iat->getElementType()),
1599 /*size*/ 0,
1600 ArrayType::Normal,
1601 iat->getIndexTypeCVRQualifiers(),
1602 SourceRange());
1603 break;
1604 }
1605
1606 // Turn VLA types into [*] types.
1607 case Type::VariableArray: {
1608 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1609 result = getVariableArrayType(
1610 getVariableArrayDecayedType(vat->getElementType()),
1611 /*size*/ 0,
1612 ArrayType::Star,
1613 vat->getIndexTypeCVRQualifiers(),
1614 vat->getBracketsRange());
1615 break;
1616 }
1617 }
1618
1619 // Apply the top-level qualifiers from the original.
1620 return getQualifiedType(result, split.second);
1621}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001622
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001623/// getVariableArrayType - Returns a non-unique reference to the type for a
1624/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001625QualType ASTContext::getVariableArrayType(QualType EltTy,
1626 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001627 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001628 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001629 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001630 // Since we don't unique expressions, it isn't possible to unique VLA's
1631 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001632 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001633
John McCall3b657512011-01-19 10:06:00 +00001634 // Be sure to pull qualifiers off the element type.
1635 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1636 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1637 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001638 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001639 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001640 }
1641
John McCall6b304a02009-09-24 23:30:46 +00001642 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001643 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001644
1645 VariableArrayTypes.push_back(New);
1646 Types.push_back(New);
1647 return QualType(New, 0);
1648}
1649
Douglas Gregor898574e2008-12-05 23:32:09 +00001650/// getDependentSizedArrayType - Returns a non-unique reference to
1651/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001652/// type.
John McCall3b657512011-01-19 10:06:00 +00001653QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1654 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001655 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001656 unsigned elementTypeQuals,
1657 SourceRange brackets) const {
1658 assert((!numElements || numElements->isTypeDependent() ||
1659 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001660 "Size must be type- or value-dependent!");
1661
John McCall3b657512011-01-19 10:06:00 +00001662 // Dependently-sized array types that do not have a specified number
1663 // of elements will have their sizes deduced from a dependent
1664 // initializer. We do no canonicalization here at all, which is okay
1665 // because they can't be used in most locations.
1666 if (!numElements) {
1667 DependentSizedArrayType *newType
1668 = new (*this, TypeAlignment)
1669 DependentSizedArrayType(*this, elementType, QualType(),
1670 numElements, ASM, elementTypeQuals,
1671 brackets);
1672 Types.push_back(newType);
1673 return QualType(newType, 0);
1674 }
1675
1676 // Otherwise, we actually build a new type every time, but we
1677 // also build a canonical type.
1678
1679 SplitQualType canonElementType = getCanonicalType(elementType).split();
1680
1681 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001682 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001683 DependentSizedArrayType::Profile(ID, *this,
1684 QualType(canonElementType.first, 0),
1685 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001686
John McCall3b657512011-01-19 10:06:00 +00001687 // Look for an existing type with these properties.
1688 DependentSizedArrayType *canonTy =
1689 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001690
John McCall3b657512011-01-19 10:06:00 +00001691 // If we don't have one, build one.
1692 if (!canonTy) {
1693 canonTy = new (*this, TypeAlignment)
1694 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1695 QualType(), numElements, ASM, elementTypeQuals,
1696 brackets);
1697 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1698 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001699 }
1700
John McCall3b657512011-01-19 10:06:00 +00001701 // Apply qualifiers from the element type to the array.
1702 QualType canon = getQualifiedType(QualType(canonTy,0),
1703 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001704
John McCall3b657512011-01-19 10:06:00 +00001705 // If we didn't need extra canonicalization for the element type,
1706 // then just use that as our result.
1707 if (QualType(canonElementType.first, 0) == elementType)
1708 return canon;
1709
1710 // Otherwise, we need to build a type which follows the spelling
1711 // of the element type.
1712 DependentSizedArrayType *sugaredType
1713 = new (*this, TypeAlignment)
1714 DependentSizedArrayType(*this, elementType, canon, numElements,
1715 ASM, elementTypeQuals, brackets);
1716 Types.push_back(sugaredType);
1717 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001718}
1719
John McCall3b657512011-01-19 10:06:00 +00001720QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001721 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001722 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001723 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001724 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001725
John McCall3b657512011-01-19 10:06:00 +00001726 void *insertPos = 0;
1727 if (IncompleteArrayType *iat =
1728 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1729 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001730
1731 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001732 // either, so fill in the canonical type field. We also have to pull
1733 // qualifiers off the element type.
1734 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001735
John McCall3b657512011-01-19 10:06:00 +00001736 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1737 SplitQualType canonSplit = getCanonicalType(elementType).split();
1738 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1739 ASM, elementTypeQuals);
1740 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001741
1742 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001743 IncompleteArrayType *existing =
1744 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1745 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001746 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001747
John McCall3b657512011-01-19 10:06:00 +00001748 IncompleteArrayType *newType = new (*this, TypeAlignment)
1749 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001750
John McCall3b657512011-01-19 10:06:00 +00001751 IncompleteArrayTypes.InsertNode(newType, insertPos);
1752 Types.push_back(newType);
1753 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001754}
1755
Steve Naroff73322922007-07-18 18:00:27 +00001756/// getVectorType - Return the unique reference to a vector type of
1757/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001758QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001759 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001760 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Reid Spencer5f016e22007-07-11 17:01:13 +00001762 // Check if we've already instantiated a vector of this type.
1763 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001764 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001765
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 void *InsertPos = 0;
1767 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1768 return QualType(VTP, 0);
1769
1770 // If the element type isn't canonical, this won't be a canonical type either,
1771 // so fill in the canonical type field.
1772 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001773 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001774 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 // Get the new insert position for the node we care about.
1777 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001778 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 }
John McCall6b304a02009-09-24 23:30:46 +00001780 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001781 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 VectorTypes.InsertNode(New, InsertPos);
1783 Types.push_back(New);
1784 return QualType(New, 0);
1785}
1786
Nate Begeman213541a2008-04-18 23:10:10 +00001787/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001788/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001789QualType
1790ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall3b657512011-01-19 10:06:00 +00001791 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Steve Naroff73322922007-07-18 18:00:27 +00001793 // Check if we've already instantiated a vector of this type.
1794 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001795 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001796 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001797 void *InsertPos = 0;
1798 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1799 return QualType(VTP, 0);
1800
1801 // If the element type isn't canonical, this won't be a canonical type either,
1802 // so fill in the canonical type field.
1803 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001804 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001805 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001806
Steve Naroff73322922007-07-18 18:00:27 +00001807 // Get the new insert position for the node we care about.
1808 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001809 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001810 }
John McCall6b304a02009-09-24 23:30:46 +00001811 ExtVectorType *New = new (*this, TypeAlignment)
1812 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001813 VectorTypes.InsertNode(New, InsertPos);
1814 Types.push_back(New);
1815 return QualType(New, 0);
1816}
1817
Jay Foad4ba2a172011-01-12 09:06:06 +00001818QualType
1819ASTContext::getDependentSizedExtVectorType(QualType vecType,
1820 Expr *SizeExpr,
1821 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001822 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001823 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001824 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001826 void *InsertPos = 0;
1827 DependentSizedExtVectorType *Canon
1828 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1829 DependentSizedExtVectorType *New;
1830 if (Canon) {
1831 // We already have a canonical version of this array type; use it as
1832 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001833 New = new (*this, TypeAlignment)
1834 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1835 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001836 } else {
1837 QualType CanonVecTy = getCanonicalType(vecType);
1838 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001839 New = new (*this, TypeAlignment)
1840 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1841 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001842
1843 DependentSizedExtVectorType *CanonCheck
1844 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1845 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1846 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001847 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1848 } else {
1849 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1850 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001851 New = new (*this, TypeAlignment)
1852 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001853 }
1854 }
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001856 Types.push_back(New);
1857 return QualType(New, 0);
1858}
1859
Douglas Gregor72564e72009-02-26 23:50:07 +00001860/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001861///
Jay Foad4ba2a172011-01-12 09:06:06 +00001862QualType
1863ASTContext::getFunctionNoProtoType(QualType ResultTy,
1864 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00001865 const CallingConv DefaultCC = Info.getCC();
1866 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1867 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 // Unique functions, to guarantee there is only one function of a particular
1869 // structure.
1870 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001871 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001874 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001875 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Reid Spencer5f016e22007-07-11 17:01:13 +00001878 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001879 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001880 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001881 Canonical =
1882 getFunctionNoProtoType(getCanonicalType(ResultTy),
1883 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001886 FunctionNoProtoType *NewIP =
1887 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001888 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001889 }
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Roman Divackycfe9af22011-03-01 17:40:53 +00001891 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00001892 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00001893 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00001894 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001895 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001896 return QualType(New, 0);
1897}
1898
1899/// getFunctionType - Return a normal function type with a typed argument
1900/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00001901QualType
1902ASTContext::getFunctionType(QualType ResultTy,
1903 const QualType *ArgArray, unsigned NumArgs,
1904 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001905 // Unique functions, to guarantee there is only one function of a particular
1906 // structure.
1907 llvm::FoldingSetNodeID ID;
John McCalle23cf432010-12-14 08:05:40 +00001908 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00001909
1910 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001911 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001912 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001914
1915 // Determine whether the type being created is already canonical or not.
John McCalle23cf432010-12-14 08:05:40 +00001916 bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001917 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001918 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 isCanonical = false;
1920
Roman Divackycfe9af22011-03-01 17:40:53 +00001921 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
1922 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1923 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00001924
Reid Spencer5f016e22007-07-11 17:01:13 +00001925 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001926 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001927 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001928 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001929 llvm::SmallVector<QualType, 16> CanonicalArgs;
1930 CanonicalArgs.reserve(NumArgs);
1931 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001932 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001933
John McCalle23cf432010-12-14 08:05:40 +00001934 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1935 if (CanonicalEPI.HasExceptionSpec) {
1936 CanonicalEPI.HasExceptionSpec = false;
1937 CanonicalEPI.HasAnyExceptionSpec = false;
1938 CanonicalEPI.NumExceptions = 0;
1939 }
1940 CanonicalEPI.ExtInfo
1941 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1942
Chris Lattnerf52ab252008-04-06 22:59:24 +00001943 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001944 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00001945 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00001946
Reid Spencer5f016e22007-07-11 17:01:13 +00001947 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001948 FunctionProtoType *NewIP =
1949 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001950 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001951 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001952
Douglas Gregor72564e72009-02-26 23:50:07 +00001953 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001954 // for two variable size arrays (for parameter and exception types) at the
1955 // end of them.
John McCalle23cf432010-12-14 08:05:40 +00001956 size_t Size = sizeof(FunctionProtoType) +
1957 NumArgs * sizeof(QualType) +
1958 EPI.NumExceptions * sizeof(QualType);
1959 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00001960 FunctionProtoType::ExtProtoInfo newEPI = EPI;
1961 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
1962 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00001963 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001964 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001965 return QualType(FTP, 0);
1966}
1967
John McCall3cb0ebd2010-03-10 03:28:59 +00001968#ifndef NDEBUG
1969static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1970 if (!isa<CXXRecordDecl>(D)) return false;
1971 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1972 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1973 return true;
1974 if (RD->getDescribedClassTemplate() &&
1975 !isa<ClassTemplateSpecializationDecl>(RD))
1976 return true;
1977 return false;
1978}
1979#endif
1980
1981/// getInjectedClassNameType - Return the unique reference to the
1982/// injected class name type for the specified templated declaration.
1983QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00001984 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00001985 assert(NeedsInjectedClassNameType(Decl));
1986 if (Decl->TypeForDecl) {
1987 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001988 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001989 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1990 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1991 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1992 } else {
John McCallf4c73712011-01-19 06:33:43 +00001993 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00001994 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00001995 Decl->TypeForDecl = newType;
1996 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00001997 }
1998 return QualType(Decl->TypeForDecl, 0);
1999}
2000
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002001/// getTypeDeclType - Return the unique reference to the type for the
2002/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002003QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002004 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002005 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002006
John McCall19c85762010-02-16 03:57:14 +00002007 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002008 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002009
John McCallbecb8d52010-03-10 06:48:02 +00002010 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2011 "Template type parameter types are always available.");
2012
John McCall19c85762010-02-16 03:57:14 +00002013 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002014 assert(!Record->getPreviousDeclaration() &&
2015 "struct/union has previous declaration");
2016 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002017 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002018 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002019 assert(!Enum->getPreviousDeclaration() &&
2020 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002021 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002022 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002023 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002024 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2025 Decl->TypeForDecl = newType;
2026 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002027 } else
John McCallbecb8d52010-03-10 06:48:02 +00002028 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002029
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002030 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002031}
2032
Reid Spencer5f016e22007-07-11 17:01:13 +00002033/// getTypedefType - Return the unique reference to the type for the
2034/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002035QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002036ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002037 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002039 if (Canonical.isNull())
2040 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002041 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002042 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002043 Decl->TypeForDecl = newType;
2044 Types.push_back(newType);
2045 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002046}
2047
Jay Foad4ba2a172011-01-12 09:06:06 +00002048QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002049 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2050
2051 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2052 if (PrevDecl->TypeForDecl)
2053 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2054
John McCallf4c73712011-01-19 06:33:43 +00002055 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2056 Decl->TypeForDecl = newType;
2057 Types.push_back(newType);
2058 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002059}
2060
Jay Foad4ba2a172011-01-12 09:06:06 +00002061QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002062 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2063
2064 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2065 if (PrevDecl->TypeForDecl)
2066 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2067
John McCallf4c73712011-01-19 06:33:43 +00002068 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2069 Decl->TypeForDecl = newType;
2070 Types.push_back(newType);
2071 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002072}
2073
John McCall9d156a72011-01-06 01:58:22 +00002074QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2075 QualType modifiedType,
2076 QualType equivalentType) {
2077 llvm::FoldingSetNodeID id;
2078 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2079
2080 void *insertPos = 0;
2081 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2082 if (type) return QualType(type, 0);
2083
2084 QualType canon = getCanonicalType(equivalentType);
2085 type = new (*this, TypeAlignment)
2086 AttributedType(canon, attrKind, modifiedType, equivalentType);
2087
2088 Types.push_back(type);
2089 AttributedTypes.InsertNode(type, insertPos);
2090
2091 return QualType(type, 0);
2092}
2093
2094
John McCall49a832b2009-10-18 09:09:24 +00002095/// \brief Retrieve a substitution-result type.
2096QualType
2097ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002098 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002099 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002100 && "replacement types must always be canonical");
2101
2102 llvm::FoldingSetNodeID ID;
2103 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2104 void *InsertPos = 0;
2105 SubstTemplateTypeParmType *SubstParm
2106 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2107
2108 if (!SubstParm) {
2109 SubstParm = new (*this, TypeAlignment)
2110 SubstTemplateTypeParmType(Parm, Replacement);
2111 Types.push_back(SubstParm);
2112 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2113 }
2114
2115 return QualType(SubstParm, 0);
2116}
2117
Douglas Gregorc3069d62011-01-14 02:55:32 +00002118/// \brief Retrieve a
2119QualType ASTContext::getSubstTemplateTypeParmPackType(
2120 const TemplateTypeParmType *Parm,
2121 const TemplateArgument &ArgPack) {
2122#ifndef NDEBUG
2123 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2124 PEnd = ArgPack.pack_end();
2125 P != PEnd; ++P) {
2126 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2127 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2128 }
2129#endif
2130
2131 llvm::FoldingSetNodeID ID;
2132 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2133 void *InsertPos = 0;
2134 if (SubstTemplateTypeParmPackType *SubstParm
2135 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2136 return QualType(SubstParm, 0);
2137
2138 QualType Canon;
2139 if (!Parm->isCanonicalUnqualified()) {
2140 Canon = getCanonicalType(QualType(Parm, 0));
2141 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2142 ArgPack);
2143 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2144 }
2145
2146 SubstTemplateTypeParmPackType *SubstParm
2147 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2148 ArgPack);
2149 Types.push_back(SubstParm);
2150 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2151 return QualType(SubstParm, 0);
2152}
2153
Douglas Gregorfab9d672009-02-05 23:33:38 +00002154/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002155/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002156/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002157QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002158 bool ParameterPack,
Jay Foad4ba2a172011-01-12 09:06:06 +00002159 IdentifierInfo *Name) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002160 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00002161 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002162 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002163 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002164 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2165
2166 if (TypeParm)
2167 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Douglas Gregorefed5c82010-06-16 15:23:05 +00002169 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002170 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00002171 TypeParm = new (*this, TypeAlignment)
2172 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002173
2174 TemplateTypeParmType *TypeCheck
2175 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2176 assert(!TypeCheck && "Template type parameter canonical type broken");
2177 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002178 } else
John McCall6b304a02009-09-24 23:30:46 +00002179 TypeParm = new (*this, TypeAlignment)
2180 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002181
2182 Types.push_back(TypeParm);
2183 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2184
2185 return QualType(TypeParm, 0);
2186}
2187
John McCall3cb0ebd2010-03-10 03:28:59 +00002188TypeSourceInfo *
2189ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2190 SourceLocation NameLoc,
2191 const TemplateArgumentListInfo &Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002192 QualType CanonType) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002193 assert(!Name.getAsDependentTemplateName() &&
2194 "No dependent template names here!");
John McCall3cb0ebd2010-03-10 03:28:59 +00002195 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2196
2197 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2198 TemplateSpecializationTypeLoc TL
2199 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2200 TL.setTemplateNameLoc(NameLoc);
2201 TL.setLAngleLoc(Args.getLAngleLoc());
2202 TL.setRAngleLoc(Args.getRAngleLoc());
2203 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2204 TL.setArgLocInfo(i, Args[i].getLocInfo());
2205 return DI;
2206}
2207
Mike Stump1eb44332009-09-09 15:08:12 +00002208QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002209ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002210 const TemplateArgumentListInfo &Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002211 QualType Canon) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002212 assert(!Template.getAsDependentTemplateName() &&
2213 "No dependent template names here!");
2214
John McCalld5532b62009-11-23 01:53:49 +00002215 unsigned NumArgs = Args.size();
2216
John McCall833ca992009-10-29 08:12:44 +00002217 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2218 ArgVec.reserve(NumArgs);
2219 for (unsigned i = 0; i != NumArgs; ++i)
2220 ArgVec.push_back(Args[i].getArgument());
2221
John McCall31f17ec2010-04-27 00:57:59 +00002222 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00002223 Canon);
John McCall833ca992009-10-29 08:12:44 +00002224}
2225
2226QualType
2227ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002228 const TemplateArgument *Args,
2229 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002230 QualType Canon) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002231 assert(!Template.getAsDependentTemplateName() &&
2232 "No dependent template names here!");
2233
Douglas Gregorb88e8882009-07-30 17:40:51 +00002234 if (!Canon.isNull())
2235 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002236 else
2237 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00002238
Douglas Gregor1275ae02009-07-28 23:00:59 +00002239 // Allocate the (non-canonical) template specialization type, but don't
2240 // try to unique it: these types typically have location information that
2241 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00002242 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00002243 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00002244 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002245 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002246 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002247 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00002248 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Douglas Gregor55f6b142009-02-09 18:46:07 +00002250 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002251 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002252}
2253
Mike Stump1eb44332009-09-09 15:08:12 +00002254QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002255ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2256 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002257 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002258 assert(!Template.getAsDependentTemplateName() &&
2259 "No dependent template names here!");
2260
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002261 // Build the canonical template specialization type.
2262 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2263 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2264 CanonArgs.reserve(NumArgs);
2265 for (unsigned I = 0; I != NumArgs; ++I)
2266 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2267
2268 // Determine whether this canonical template specialization type already
2269 // exists.
2270 llvm::FoldingSetNodeID ID;
2271 TemplateSpecializationType::Profile(ID, CanonTemplate,
2272 CanonArgs.data(), NumArgs, *this);
2273
2274 void *InsertPos = 0;
2275 TemplateSpecializationType *Spec
2276 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2277
2278 if (!Spec) {
2279 // Allocate a new canonical template specialization type.
2280 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2281 sizeof(TemplateArgument) * NumArgs),
2282 TypeAlignment);
2283 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2284 CanonArgs.data(), NumArgs,
2285 QualType());
2286 Types.push_back(Spec);
2287 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2288 }
2289
2290 assert(Spec->isDependentType() &&
2291 "Non-dependent template-id type must have a canonical type");
2292 return QualType(Spec, 0);
2293}
2294
2295QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002296ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2297 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002298 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002299 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002300 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002301
2302 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002303 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002304 if (T)
2305 return QualType(T, 0);
2306
Douglas Gregor789b1f62010-02-04 18:10:26 +00002307 QualType Canon = NamedType;
2308 if (!Canon.isCanonical()) {
2309 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002310 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2311 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002312 (void)CheckT;
2313 }
2314
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002315 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002316 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002317 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002318 return QualType(T, 0);
2319}
2320
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002321QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002322ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002323 llvm::FoldingSetNodeID ID;
2324 ParenType::Profile(ID, InnerType);
2325
2326 void *InsertPos = 0;
2327 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2328 if (T)
2329 return QualType(T, 0);
2330
2331 QualType Canon = InnerType;
2332 if (!Canon.isCanonical()) {
2333 Canon = getCanonicalType(InnerType);
2334 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2335 assert(!CheckT && "Paren canonical type broken");
2336 (void)CheckT;
2337 }
2338
2339 T = new (*this) ParenType(InnerType, Canon);
2340 Types.push_back(T);
2341 ParenTypes.InsertNode(T, InsertPos);
2342 return QualType(T, 0);
2343}
2344
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002345QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2346 NestedNameSpecifier *NNS,
2347 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002348 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002349 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2350
2351 if (Canon.isNull()) {
2352 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002353 ElaboratedTypeKeyword CanonKeyword = Keyword;
2354 if (Keyword == ETK_None)
2355 CanonKeyword = ETK_Typename;
2356
2357 if (CanonNNS != NNS || CanonKeyword != Keyword)
2358 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002359 }
2360
2361 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002362 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002363
2364 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002365 DependentNameType *T
2366 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002367 if (T)
2368 return QualType(T, 0);
2369
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002370 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002371 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002372 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002373 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002374}
2375
Mike Stump1eb44332009-09-09 15:08:12 +00002376QualType
John McCall33500952010-06-11 00:33:02 +00002377ASTContext::getDependentTemplateSpecializationType(
2378 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002379 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002380 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002381 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002382 // TODO: avoid this copy
2383 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2384 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2385 ArgCopy.push_back(Args[I].getArgument());
2386 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2387 ArgCopy.size(),
2388 ArgCopy.data());
2389}
2390
2391QualType
2392ASTContext::getDependentTemplateSpecializationType(
2393 ElaboratedTypeKeyword Keyword,
2394 NestedNameSpecifier *NNS,
2395 const IdentifierInfo *Name,
2396 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002397 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002398 assert((!NNS || NNS->isDependent()) &&
2399 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002400
Douglas Gregor789b1f62010-02-04 18:10:26 +00002401 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002402 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2403 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002404
2405 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002406 DependentTemplateSpecializationType *T
2407 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002408 if (T)
2409 return QualType(T, 0);
2410
John McCall33500952010-06-11 00:33:02 +00002411 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002412
John McCall33500952010-06-11 00:33:02 +00002413 ElaboratedTypeKeyword CanonKeyword = Keyword;
2414 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2415
2416 bool AnyNonCanonArgs = false;
2417 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2418 for (unsigned I = 0; I != NumArgs; ++I) {
2419 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2420 if (!CanonArgs[I].structurallyEquals(Args[I]))
2421 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002422 }
2423
John McCall33500952010-06-11 00:33:02 +00002424 QualType Canon;
2425 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2426 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2427 Name, NumArgs,
2428 CanonArgs.data());
2429
2430 // Find the insert position again.
2431 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2432 }
2433
2434 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2435 sizeof(TemplateArgument) * NumArgs),
2436 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002437 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002438 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002439 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002440 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002441 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002442}
2443
Douglas Gregorcded4f62011-01-14 17:04:44 +00002444QualType ASTContext::getPackExpansionType(QualType Pattern,
2445 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002446 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002447 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002448
2449 assert(Pattern->containsUnexpandedParameterPack() &&
2450 "Pack expansions must expand one or more parameter packs");
2451 void *InsertPos = 0;
2452 PackExpansionType *T
2453 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2454 if (T)
2455 return QualType(T, 0);
2456
2457 QualType Canon;
2458 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002459 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002460
2461 // Find the insert position again.
2462 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2463 }
2464
Douglas Gregorcded4f62011-01-14 17:04:44 +00002465 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002466 Types.push_back(T);
2467 PackExpansionTypes.InsertNode(T, InsertPos);
2468 return QualType(T, 0);
2469}
2470
Chris Lattner88cb27a2008-04-07 04:56:42 +00002471/// CmpProtocolNames - Comparison predicate for sorting protocols
2472/// alphabetically.
2473static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2474 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002475 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002476}
2477
John McCallc12c5bb2010-05-15 11:32:37 +00002478static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002479 unsigned NumProtocols) {
2480 if (NumProtocols == 0) return true;
2481
2482 for (unsigned i = 1; i != NumProtocols; ++i)
2483 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2484 return false;
2485 return true;
2486}
2487
2488static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002489 unsigned &NumProtocols) {
2490 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Chris Lattner88cb27a2008-04-07 04:56:42 +00002492 // Sort protocols, keyed by name.
2493 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2494
2495 // Remove duplicates.
2496 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2497 NumProtocols = ProtocolsEnd-Protocols;
2498}
2499
John McCallc12c5bb2010-05-15 11:32:37 +00002500QualType ASTContext::getObjCObjectType(QualType BaseType,
2501 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002502 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002503 // If the base type is an interface and there aren't any protocols
2504 // to add, then the interface type will do just fine.
2505 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2506 return BaseType;
2507
2508 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002509 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002510 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002511 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002512 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2513 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002514
John McCallc12c5bb2010-05-15 11:32:37 +00002515 // Build the canonical type, which has the canonical base type and
2516 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002517 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002518 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2519 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2520 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002521 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2522 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002523 unsigned UniqueCount = NumProtocols;
2524
John McCall54e14c42009-10-22 22:37:11 +00002525 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002526 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2527 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002528 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002529 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2530 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002531 }
2532
2533 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002534 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2535 }
2536
2537 unsigned Size = sizeof(ObjCObjectTypeImpl);
2538 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2539 void *Mem = Allocate(Size, TypeAlignment);
2540 ObjCObjectTypeImpl *T =
2541 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2542
2543 Types.push_back(T);
2544 ObjCObjectTypes.InsertNode(T, InsertPos);
2545 return QualType(T, 0);
2546}
2547
2548/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2549/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002550QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002551 llvm::FoldingSetNodeID ID;
2552 ObjCObjectPointerType::Profile(ID, ObjectT);
2553
2554 void *InsertPos = 0;
2555 if (ObjCObjectPointerType *QT =
2556 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2557 return QualType(QT, 0);
2558
2559 // Find the canonical object type.
2560 QualType Canonical;
2561 if (!ObjectT.isCanonical()) {
2562 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2563
2564 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002565 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2566 }
2567
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002568 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002569 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2570 ObjCObjectPointerType *QType =
2571 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002572
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002573 Types.push_back(QType);
2574 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002575 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002576}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002577
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002578/// getObjCInterfaceType - Return the unique reference to the type for the
2579/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002580QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002581 if (Decl->TypeForDecl)
2582 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002583
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002584 // FIXME: redeclarations?
2585 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2586 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2587 Decl->TypeForDecl = T;
2588 Types.push_back(T);
2589 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002590}
2591
Douglas Gregor72564e72009-02-26 23:50:07 +00002592/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2593/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002594/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002595/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002596/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002597QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002598 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002599 if (tofExpr->isTypeDependent()) {
2600 llvm::FoldingSetNodeID ID;
2601 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002602
Douglas Gregorb1975722009-07-30 23:18:24 +00002603 void *InsertPos = 0;
2604 DependentTypeOfExprType *Canon
2605 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2606 if (Canon) {
2607 // We already have a "canonical" version of an identical, dependent
2608 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002609 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002610 QualType((TypeOfExprType*)Canon, 0));
2611 }
2612 else {
2613 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002614 Canon
2615 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002616 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2617 toe = Canon;
2618 }
2619 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002620 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002621 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002622 }
Steve Naroff9752f252007-08-01 18:02:17 +00002623 Types.push_back(toe);
2624 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002625}
2626
Steve Naroff9752f252007-08-01 18:02:17 +00002627/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2628/// TypeOfType AST's. The only motivation to unique these nodes would be
2629/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002630/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002631/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002632QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002633 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002634 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002635 Types.push_back(tot);
2636 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002637}
2638
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002639/// getDecltypeForExpr - Given an expr, will return the decltype for that
2640/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002641static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002642 if (e->isTypeDependent())
2643 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002644
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002645 // If e is an id expression or a class member access, decltype(e) is defined
2646 // as the type of the entity named by e.
2647 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2648 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2649 return VD->getType();
2650 }
2651 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2652 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2653 return FD->getType();
2654 }
2655 // If e is a function call or an invocation of an overloaded operator,
2656 // (parentheses around e are ignored), decltype(e) is defined as the
2657 // return type of that function.
2658 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2659 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002661 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002662
2663 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002664 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002665 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002666 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002667
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002668 return T;
2669}
2670
Anders Carlsson395b4752009-06-24 19:06:50 +00002671/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2672/// DecltypeType AST's. The only motivation to unique these nodes would be
2673/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002674/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002675/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002676QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002677 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002678 if (e->isTypeDependent()) {
2679 llvm::FoldingSetNodeID ID;
2680 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002681
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002682 void *InsertPos = 0;
2683 DependentDecltypeType *Canon
2684 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2685 if (Canon) {
2686 // We already have a "canonical" version of an equivalent, dependent
2687 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002688 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002689 QualType((DecltypeType*)Canon, 0));
2690 }
2691 else {
2692 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002693 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002694 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2695 dt = Canon;
2696 }
2697 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002698 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002699 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002700 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002701 Types.push_back(dt);
2702 return QualType(dt, 0);
2703}
2704
Richard Smith483b9f32011-02-21 20:05:19 +00002705/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002706QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002707 void *InsertPos = 0;
2708 if (!DeducedType.isNull()) {
2709 // Look in the folding set for an existing type.
2710 llvm::FoldingSetNodeID ID;
2711 AutoType::Profile(ID, DeducedType);
2712 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2713 return QualType(AT, 0);
2714 }
2715
2716 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2717 Types.push_back(AT);
2718 if (InsertPos)
2719 AutoTypes.InsertNode(AT, InsertPos);
2720 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002721}
2722
Reid Spencer5f016e22007-07-11 17:01:13 +00002723/// getTagDeclType - Return the unique reference to the type for the
2724/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00002725QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00002726 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002727 // FIXME: What is the design on getTagDeclType when it requires casting
2728 // away const? mutable?
2729 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002730}
2731
Mike Stump1eb44332009-09-09 15:08:12 +00002732/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2733/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2734/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002735CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002736 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002737}
2738
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002739/// getSignedWCharType - Return the type of "signed wchar_t".
2740/// Used when in C++, as a GCC extension.
2741QualType ASTContext::getSignedWCharType() const {
2742 // FIXME: derive from "Target" ?
2743 return WCharTy;
2744}
2745
2746/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2747/// Used when in C++, as a GCC extension.
2748QualType ASTContext::getUnsignedWCharType() const {
2749 // FIXME: derive from "Target" ?
2750 return UnsignedIntTy;
2751}
2752
Chris Lattner8b9023b2007-07-13 03:05:23 +00002753/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2754/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2755QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002756 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002757}
2758
Chris Lattnere6327742008-04-02 05:18:44 +00002759//===----------------------------------------------------------------------===//
2760// Type Operators
2761//===----------------------------------------------------------------------===//
2762
Jay Foad4ba2a172011-01-12 09:06:06 +00002763CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00002764 // Push qualifiers into arrays, and then discard any remaining
2765 // qualifiers.
2766 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002767 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002768 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002769 QualType Result;
2770 if (isa<ArrayType>(Ty)) {
2771 Result = getArrayDecayedType(QualType(Ty,0));
2772 } else if (isa<FunctionType>(Ty)) {
2773 Result = getPointerType(QualType(Ty, 0));
2774 } else {
2775 Result = QualType(Ty, 0);
2776 }
2777
2778 return CanQualType::CreateUnsafe(Result);
2779}
2780
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002781
John McCall62c28c82011-01-18 07:41:22 +00002782QualType ASTContext::getUnqualifiedArrayType(QualType type,
2783 Qualifiers &quals) {
2784 SplitQualType splitType = type.getSplitUnqualifiedType();
2785
2786 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2787 // the unqualified desugared type and then drops it on the floor.
2788 // We then have to strip that sugar back off with
2789 // getUnqualifiedDesugaredType(), which is silly.
2790 const ArrayType *AT =
2791 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2792
2793 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00002794 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00002795 quals = splitType.second;
2796 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002797 }
2798
John McCall62c28c82011-01-18 07:41:22 +00002799 // Otherwise, recurse on the array's element type.
2800 QualType elementType = AT->getElementType();
2801 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2802
2803 // If that didn't change the element type, AT has no qualifiers, so we
2804 // can just use the results in splitType.
2805 if (elementType == unqualElementType) {
2806 assert(quals.empty()); // from the recursive call
2807 quals = splitType.second;
2808 return QualType(splitType.first, 0);
2809 }
2810
2811 // Otherwise, add in the qualifiers from the outermost type, then
2812 // build the type back up.
2813 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002814
Douglas Gregor9dadd942010-05-17 18:45:21 +00002815 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002816 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002817 CAT->getSizeModifier(), 0);
2818 }
2819
Douglas Gregor9dadd942010-05-17 18:45:21 +00002820 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002821 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002822 }
2823
Douglas Gregor9dadd942010-05-17 18:45:21 +00002824 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002825 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00002826 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00002827 VAT->getSizeModifier(),
2828 VAT->getIndexTypeCVRQualifiers(),
2829 VAT->getBracketsRange());
2830 }
2831
2832 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00002833 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002834 DSAT->getSizeModifier(), 0,
2835 SourceRange());
2836}
2837
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002838/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2839/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2840/// they point to and return true. If T1 and T2 aren't pointer types
2841/// or pointer-to-member types, or if they are not similar at this
2842/// level, returns false and leaves T1 and T2 unchanged. Top-level
2843/// qualifiers on T1 and T2 are ignored. This function will typically
2844/// be called in a loop that successively "unwraps" pointer and
2845/// pointer-to-member types to compare them at each level.
2846bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2847 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2848 *T2PtrType = T2->getAs<PointerType>();
2849 if (T1PtrType && T2PtrType) {
2850 T1 = T1PtrType->getPointeeType();
2851 T2 = T2PtrType->getPointeeType();
2852 return true;
2853 }
2854
2855 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2856 *T2MPType = T2->getAs<MemberPointerType>();
2857 if (T1MPType && T2MPType &&
2858 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2859 QualType(T2MPType->getClass(), 0))) {
2860 T1 = T1MPType->getPointeeType();
2861 T2 = T2MPType->getPointeeType();
2862 return true;
2863 }
2864
2865 if (getLangOptions().ObjC1) {
2866 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2867 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2868 if (T1OPType && T2OPType) {
2869 T1 = T1OPType->getPointeeType();
2870 T2 = T2OPType->getPointeeType();
2871 return true;
2872 }
2873 }
2874
2875 // FIXME: Block pointers, too?
2876
2877 return false;
2878}
2879
Jay Foad4ba2a172011-01-12 09:06:06 +00002880DeclarationNameInfo
2881ASTContext::getNameForTemplate(TemplateName Name,
2882 SourceLocation NameLoc) const {
John McCall80ad16f2009-11-24 18:42:40 +00002883 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002884 // DNInfo work in progress: CHECKME: what about DNLoc?
2885 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2886
John McCall80ad16f2009-11-24 18:42:40 +00002887 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002888 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002889 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002890 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2891 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002892 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00002893 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2894 // DNInfo work in progress: FIXME: source locations?
2895 DeclarationNameLoc DNLoc;
2896 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2897 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2898 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002899 }
2900 }
2901
John McCall0bd6feb2009-12-02 08:04:21 +00002902 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2903 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002904 // DNInfo work in progress: CHECKME: what about DNLoc?
2905 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002906}
2907
Jay Foad4ba2a172011-01-12 09:06:06 +00002908TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002909 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2910 if (TemplateTemplateParmDecl *TTP
2911 = dyn_cast<TemplateTemplateParmDecl>(Template))
2912 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2913
2914 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002915 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002916 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002917
Douglas Gregor1aee05d2011-01-15 06:45:20 +00002918 if (SubstTemplateTemplateParmPackStorage *SubstPack
2919 = Name.getAsSubstTemplateTemplateParmPack()) {
2920 TemplateTemplateParmDecl *CanonParam
2921 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2922 TemplateArgument CanonArgPack
2923 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2924 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2925 }
2926
John McCall0bd6feb2009-12-02 08:04:21 +00002927 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002928
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002929 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2930 assert(DTN && "Non-dependent template names must refer to template decls.");
2931 return DTN->CanonicalTemplateName;
2932}
2933
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002934bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2935 X = getCanonicalTemplateName(X);
2936 Y = getCanonicalTemplateName(Y);
2937 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2938}
2939
Mike Stump1eb44332009-09-09 15:08:12 +00002940TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00002941ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00002942 switch (Arg.getKind()) {
2943 case TemplateArgument::Null:
2944 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002945
Douglas Gregor1275ae02009-07-28 23:00:59 +00002946 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002947 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002948
Douglas Gregor1275ae02009-07-28 23:00:59 +00002949 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002950 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002951
Douglas Gregor788cd062009-11-11 01:00:40 +00002952 case TemplateArgument::Template:
2953 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00002954
2955 case TemplateArgument::TemplateExpansion:
2956 return TemplateArgument(getCanonicalTemplateName(
2957 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00002958 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00002959
Douglas Gregor1275ae02009-07-28 23:00:59 +00002960 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002961 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002962 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002963
Douglas Gregor1275ae02009-07-28 23:00:59 +00002964 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002965 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Douglas Gregor1275ae02009-07-28 23:00:59 +00002967 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00002968 if (Arg.pack_size() == 0)
2969 return Arg;
2970
Douglas Gregor910f8002010-11-07 23:05:16 +00002971 TemplateArgument *CanonArgs
2972 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00002973 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002974 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002975 AEnd = Arg.pack_end();
2976 A != AEnd; (void)++A, ++Idx)
2977 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002978
Douglas Gregor910f8002010-11-07 23:05:16 +00002979 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00002980 }
2981 }
2982
2983 // Silence GCC warning
2984 assert(false && "Unhandled template argument kind");
2985 return TemplateArgument();
2986}
2987
Douglas Gregord57959a2009-03-27 23:10:48 +00002988NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00002989ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00002990 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002991 return 0;
2992
2993 switch (NNS->getKind()) {
2994 case NestedNameSpecifier::Identifier:
2995 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002996 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002997 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2998 NNS->getAsIdentifier());
2999
3000 case NestedNameSpecifier::Namespace:
3001 // A namespace is canonical; build a nested-name-specifier with
3002 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003003 return NestedNameSpecifier::Create(*this, 0,
3004 NNS->getAsNamespace()->getOriginalNamespace());
3005
3006 case NestedNameSpecifier::NamespaceAlias:
3007 // A namespace is canonical; build a nested-name-specifier with
3008 // this namespace and no prefix.
3009 return NestedNameSpecifier::Create(*this, 0,
3010 NNS->getAsNamespaceAlias()->getNamespace()
3011 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003012
3013 case NestedNameSpecifier::TypeSpec:
3014 case NestedNameSpecifier::TypeSpecWithTemplate: {
3015 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003016
3017 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3018 // break it apart into its prefix and identifier, then reconsititute those
3019 // as the canonical nested-name-specifier. This is required to canonicalize
3020 // a dependent nested-name-specifier involving typedefs of dependent-name
3021 // types, e.g.,
3022 // typedef typename T::type T1;
3023 // typedef typename T1::type T2;
3024 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3025 NestedNameSpecifier *Prefix
3026 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3027 return NestedNameSpecifier::Create(*this, Prefix,
3028 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3029 }
3030
Douglas Gregor643f8432010-11-04 00:14:23 +00003031 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003032 if (const DependentTemplateSpecializationType *DTST
3033 = T->getAs<DependentTemplateSpecializationType>()) {
3034 NestedNameSpecifier *Prefix
3035 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003036
3037 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3038 Prefix, DTST->getIdentifier(),
3039 DTST->getNumArgs(),
3040 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003041 T = getCanonicalType(T);
3042 }
3043
John McCall3b657512011-01-19 10:06:00 +00003044 return NestedNameSpecifier::Create(*this, 0, false,
3045 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003046 }
3047
3048 case NestedNameSpecifier::Global:
3049 // The global specifier is canonical and unique.
3050 return NNS;
3051 }
3052
3053 // Required to silence a GCC warning
3054 return 0;
3055}
3056
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003057
Jay Foad4ba2a172011-01-12 09:06:06 +00003058const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003059 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003060 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003061 // Handle the common positive case fast.
3062 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3063 return AT;
3064 }
Mike Stump1eb44332009-09-09 15:08:12 +00003065
John McCall0953e762009-09-24 19:53:00 +00003066 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003067 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003068 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003069
John McCall0953e762009-09-24 19:53:00 +00003070 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003071 // implements C99 6.7.3p8: "If the specification of an array type includes
3072 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003073
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003074 // If we get here, we either have type qualifiers on the type, or we have
3075 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003076 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003077
John McCall3b657512011-01-19 10:06:00 +00003078 SplitQualType split = T.getSplitDesugaredType();
3079 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003080
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003081 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003082 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3083 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003084 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003085
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003086 // Otherwise, we have an array and we have qualifiers on it. Push the
3087 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003088 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003089
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003090 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3091 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3092 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003093 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003094 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3095 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3096 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003097 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003098
Mike Stump1eb44332009-09-09 15:08:12 +00003099 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003100 = dyn_cast<DependentSizedArrayType>(ATy))
3101 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003102 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003103 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003104 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003105 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003106 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003107
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003108 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003109 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003110 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003111 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003112 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003113 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003114}
3115
Chris Lattnere6327742008-04-02 05:18:44 +00003116/// getArrayDecayedType - Return the properly qualified result of decaying the
3117/// specified array type to a pointer. This operation is non-trivial when
3118/// handling typedefs etc. The canonical type of "T" must be an array type,
3119/// this returns a pointer to a properly qualified element of the array.
3120///
3121/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003122QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003123 // Get the element type with 'getAsArrayType' so that we don't lose any
3124 // typedefs in the element type of the array. This also handles propagation
3125 // of type qualifiers from the array type into the element type if present
3126 // (C99 6.7.3p8).
3127 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3128 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003129
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003130 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003131
3132 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003133 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003134}
3135
John McCall3b657512011-01-19 10:06:00 +00003136QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3137 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003138}
3139
John McCall3b657512011-01-19 10:06:00 +00003140QualType ASTContext::getBaseElementType(QualType type) const {
3141 Qualifiers qs;
3142 while (true) {
3143 SplitQualType split = type.getSplitDesugaredType();
3144 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3145 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003146
John McCall3b657512011-01-19 10:06:00 +00003147 type = array->getElementType();
3148 qs.addConsistentQualifiers(split.second);
3149 }
Mike Stump1eb44332009-09-09 15:08:12 +00003150
John McCall3b657512011-01-19 10:06:00 +00003151 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003152}
3153
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003154/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003155uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003156ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3157 uint64_t ElementCount = 1;
3158 do {
3159 ElementCount *= CA->getSize().getZExtValue();
3160 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3161 } while (CA);
3162 return ElementCount;
3163}
3164
Reid Spencer5f016e22007-07-11 17:01:13 +00003165/// getFloatingRank - Return a relative rank for floating point types.
3166/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003167static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003168 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003169 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003170
John McCall183700f2009-09-21 23:43:11 +00003171 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3172 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00003173 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003174 case BuiltinType::Float: return FloatRank;
3175 case BuiltinType::Double: return DoubleRank;
3176 case BuiltinType::LongDouble: return LongDoubleRank;
3177 }
3178}
3179
Mike Stump1eb44332009-09-09 15:08:12 +00003180/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3181/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003182/// 'typeDomain' is a real floating point or complex type.
3183/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003184QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3185 QualType Domain) const {
3186 FloatingRank EltRank = getFloatingRank(Size);
3187 if (Domain->isComplexType()) {
3188 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00003189 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003190 case FloatRank: return FloatComplexTy;
3191 case DoubleRank: return DoubleComplexTy;
3192 case LongDoubleRank: return LongDoubleComplexTy;
3193 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003194 }
Chris Lattner1361b112008-04-06 23:58:54 +00003195
3196 assert(Domain->isRealFloatingType() && "Unknown domain!");
3197 switch (EltRank) {
3198 default: assert(0 && "getFloatingRank(): illegal value for rank");
3199 case FloatRank: return FloatTy;
3200 case DoubleRank: return DoubleTy;
3201 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003202 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003203}
3204
Chris Lattner7cfeb082008-04-06 23:55:33 +00003205/// getFloatingTypeOrder - Compare the rank of the two specified floating
3206/// point types, ignoring the domain of the type (i.e. 'double' ==
3207/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003208/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003209int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003210 FloatingRank LHSR = getFloatingRank(LHS);
3211 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003212
Chris Lattnera75cea32008-04-06 23:38:49 +00003213 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003214 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003215 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003216 return 1;
3217 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003218}
3219
Chris Lattnerf52ab252008-04-06 22:59:24 +00003220/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3221/// routine will assert if passed a built-in type that isn't an integer or enum,
3222/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003223unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003224 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCallf4c73712011-01-19 06:33:43 +00003225 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00003226 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00003227
Chris Lattner3f59c972010-12-25 23:25:43 +00003228 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3229 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmana3426752009-07-05 23:44:27 +00003230 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3231
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003232 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3233 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3234
3235 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3236 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3237
Chris Lattnerf52ab252008-04-06 22:59:24 +00003238 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00003239 default: assert(0 && "getIntegerRank(): not a built-in integer");
3240 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003241 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003242 case BuiltinType::Char_S:
3243 case BuiltinType::Char_U:
3244 case BuiltinType::SChar:
3245 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003246 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003247 case BuiltinType::Short:
3248 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003249 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003250 case BuiltinType::Int:
3251 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003252 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003253 case BuiltinType::Long:
3254 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003255 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003256 case BuiltinType::LongLong:
3257 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003258 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003259 case BuiltinType::Int128:
3260 case BuiltinType::UInt128:
3261 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003262 }
3263}
3264
Eli Friedman04e83572009-08-20 04:21:42 +00003265/// \brief Whether this is a promotable bitfield reference according
3266/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3267///
3268/// \returns the type this bit-field will promote to, or NULL if no
3269/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003270QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003271 if (E->isTypeDependent() || E->isValueDependent())
3272 return QualType();
3273
Eli Friedman04e83572009-08-20 04:21:42 +00003274 FieldDecl *Field = E->getBitField();
3275 if (!Field)
3276 return QualType();
3277
3278 QualType FT = Field->getType();
3279
3280 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3281 uint64_t BitWidth = BitWidthAP.getZExtValue();
3282 uint64_t IntSize = getTypeSize(IntTy);
3283 // GCC extension compatibility: if the bit-field size is less than or equal
3284 // to the size of int, it gets promoted no matter what its type is.
3285 // For instance, unsigned long bf : 4 gets promoted to signed int.
3286 if (BitWidth < IntSize)
3287 return IntTy;
3288
3289 if (BitWidth == IntSize)
3290 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3291
3292 // Types bigger than int are not subject to promotions, and therefore act
3293 // like the base type.
3294 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3295 // is ridiculous.
3296 return QualType();
3297}
3298
Eli Friedmana95d7572009-08-19 07:44:53 +00003299/// getPromotedIntegerType - Returns the type that Promotable will
3300/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3301/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003302QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003303 assert(!Promotable.isNull());
3304 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003305 if (const EnumType *ET = Promotable->getAs<EnumType>())
3306 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003307 if (Promotable->isSignedIntegerType())
3308 return IntTy;
3309 uint64_t PromotableSize = getTypeSize(Promotable);
3310 uint64_t IntSize = getTypeSize(IntTy);
3311 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3312 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3313}
3314
Mike Stump1eb44332009-09-09 15:08:12 +00003315/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003316/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003317/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003318int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003319 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3320 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003321 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003322
Chris Lattnerf52ab252008-04-06 22:59:24 +00003323 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3324 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003325
Chris Lattner7cfeb082008-04-06 23:55:33 +00003326 unsigned LHSRank = getIntegerRank(LHSC);
3327 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003328
Chris Lattner7cfeb082008-04-06 23:55:33 +00003329 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3330 if (LHSRank == RHSRank) return 0;
3331 return LHSRank > RHSRank ? 1 : -1;
3332 }
Mike Stump1eb44332009-09-09 15:08:12 +00003333
Chris Lattner7cfeb082008-04-06 23:55:33 +00003334 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3335 if (LHSUnsigned) {
3336 // If the unsigned [LHS] type is larger, return it.
3337 if (LHSRank >= RHSRank)
3338 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003339
Chris Lattner7cfeb082008-04-06 23:55:33 +00003340 // If the signed type can represent all values of the unsigned type, it
3341 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003342 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003343 return -1;
3344 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003345
Chris Lattner7cfeb082008-04-06 23:55:33 +00003346 // If the unsigned [RHS] type is larger, return it.
3347 if (RHSRank >= LHSRank)
3348 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003349
Chris Lattner7cfeb082008-04-06 23:55:33 +00003350 // If the signed type can represent all values of the unsigned type, it
3351 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003352 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003353 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003354}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003355
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003356static RecordDecl *
Jay Foad4ba2a172011-01-12 09:06:06 +00003357CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003358 SourceLocation L, IdentifierInfo *Id) {
3359 if (Ctx.getLangOptions().CPlusPlus)
3360 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3361 else
3362 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3363}
3364
Mike Stump1eb44332009-09-09 15:08:12 +00003365// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003366QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003367 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003368 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003369 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003370 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003371 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003372
Anders Carlssonf06273f2007-11-19 00:25:30 +00003373 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003374
Anders Carlsson71993dd2007-08-17 05:31:46 +00003375 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003376 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003377 // int flags;
3378 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003379 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003380 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003381 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003382 FieldTypes[3] = LongTy;
3383
Anders Carlsson71993dd2007-08-17 05:31:46 +00003384 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003385 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003386 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003387 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003388 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003389 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003390 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003391 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003392 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003393 }
3394
Douglas Gregor838db382010-02-11 01:19:42 +00003395 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003396 }
Mike Stump1eb44332009-09-09 15:08:12 +00003397
Anders Carlsson71993dd2007-08-17 05:31:46 +00003398 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003399}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003400
Douglas Gregor319ac892009-04-23 22:29:11 +00003401void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003402 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003403 assert(Rec && "Invalid CFConstantStringType");
3404 CFConstantStringTypeDecl = Rec->getDecl();
3405}
3406
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003407// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003408QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003409 if (!NSConstantStringTypeDecl) {
3410 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003411 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003412 &Idents.get("__builtin_NSString"));
3413 NSConstantStringTypeDecl->startDefinition();
3414
3415 QualType FieldTypes[3];
3416
3417 // const int *isa;
3418 FieldTypes[0] = getPointerType(IntTy.withConst());
3419 // const char *str;
3420 FieldTypes[1] = getPointerType(CharTy.withConst());
3421 // unsigned int length;
3422 FieldTypes[2] = UnsignedIntTy;
3423
3424 // Create fields
3425 for (unsigned i = 0; i < 3; ++i) {
3426 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3427 SourceLocation(), 0,
3428 FieldTypes[i], /*TInfo=*/0,
3429 /*BitWidth=*/0,
3430 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003431 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003432 NSConstantStringTypeDecl->addDecl(Field);
3433 }
3434
3435 NSConstantStringTypeDecl->completeDefinition();
3436 }
3437
3438 return getTagDeclType(NSConstantStringTypeDecl);
3439}
3440
3441void ASTContext::setNSConstantStringType(QualType T) {
3442 const RecordType *Rec = T->getAs<RecordType>();
3443 assert(Rec && "Invalid NSConstantStringType");
3444 NSConstantStringTypeDecl = Rec->getDecl();
3445}
3446
Jay Foad4ba2a172011-01-12 09:06:06 +00003447QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003448 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003449 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003450 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003451 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003452 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003453
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003454 QualType FieldTypes[] = {
3455 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003456 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003457 getPointerType(UnsignedLongTy),
3458 getConstantArrayType(UnsignedLongTy,
3459 llvm::APInt(32, 5), ArrayType::Normal, 0)
3460 };
Mike Stump1eb44332009-09-09 15:08:12 +00003461
Douglas Gregor44b43212008-12-11 16:49:14 +00003462 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003463 FieldDecl *Field = FieldDecl::Create(*this,
3464 ObjCFastEnumerationStateTypeDecl,
3465 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003466 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003467 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003468 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003469 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003470 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003471 }
Mike Stump1eb44332009-09-09 15:08:12 +00003472
Douglas Gregor838db382010-02-11 01:19:42 +00003473 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003474 }
Mike Stump1eb44332009-09-09 15:08:12 +00003475
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003476 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3477}
3478
Jay Foad4ba2a172011-01-12 09:06:06 +00003479QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003480 if (BlockDescriptorType)
3481 return getTagDeclType(BlockDescriptorType);
3482
3483 RecordDecl *T;
3484 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003485 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003486 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003487 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003488
3489 QualType FieldTypes[] = {
3490 UnsignedLongTy,
3491 UnsignedLongTy,
3492 };
3493
3494 const char *FieldNames[] = {
3495 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003496 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003497 };
3498
3499 for (size_t i = 0; i < 2; ++i) {
3500 FieldDecl *Field = FieldDecl::Create(*this,
3501 T,
3502 SourceLocation(),
3503 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003504 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003505 /*BitWidth=*/0,
3506 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003507 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003508 T->addDecl(Field);
3509 }
3510
Douglas Gregor838db382010-02-11 01:19:42 +00003511 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003512
3513 BlockDescriptorType = T;
3514
3515 return getTagDeclType(BlockDescriptorType);
3516}
3517
3518void ASTContext::setBlockDescriptorType(QualType T) {
3519 const RecordType *Rec = T->getAs<RecordType>();
3520 assert(Rec && "Invalid BlockDescriptorType");
3521 BlockDescriptorType = Rec->getDecl();
3522}
3523
Jay Foad4ba2a172011-01-12 09:06:06 +00003524QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003525 if (BlockDescriptorExtendedType)
3526 return getTagDeclType(BlockDescriptorExtendedType);
3527
3528 RecordDecl *T;
3529 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003530 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003531 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003532 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003533
3534 QualType FieldTypes[] = {
3535 UnsignedLongTy,
3536 UnsignedLongTy,
3537 getPointerType(VoidPtrTy),
3538 getPointerType(VoidPtrTy)
3539 };
3540
3541 const char *FieldNames[] = {
3542 "reserved",
3543 "Size",
3544 "CopyFuncPtr",
3545 "DestroyFuncPtr"
3546 };
3547
3548 for (size_t i = 0; i < 4; ++i) {
3549 FieldDecl *Field = FieldDecl::Create(*this,
3550 T,
3551 SourceLocation(),
3552 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003553 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003554 /*BitWidth=*/0,
3555 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003556 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003557 T->addDecl(Field);
3558 }
3559
Douglas Gregor838db382010-02-11 01:19:42 +00003560 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003561
3562 BlockDescriptorExtendedType = T;
3563
3564 return getTagDeclType(BlockDescriptorExtendedType);
3565}
3566
3567void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3568 const RecordType *Rec = T->getAs<RecordType>();
3569 assert(Rec && "Invalid BlockDescriptorType");
3570 BlockDescriptorExtendedType = Rec->getDecl();
3571}
3572
Jay Foad4ba2a172011-01-12 09:06:06 +00003573bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003574 if (Ty->isBlockPointerType())
3575 return true;
3576 if (isObjCNSObjectType(Ty))
3577 return true;
3578 if (Ty->isObjCObjectPointerType())
3579 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003580 if (getLangOptions().CPlusPlus) {
3581 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3582 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3583 return RD->hasConstCopyConstructor(*this);
3584
3585 }
3586 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003587 return false;
3588}
3589
Jay Foad4ba2a172011-01-12 09:06:06 +00003590QualType
3591ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003592 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003593 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003594 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003595 // unsigned int __flags;
3596 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003597 // void *__copy_helper; // as needed
3598 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003599 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003600 // } *
3601
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003602 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3603
3604 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003605 llvm::SmallString<36> Name;
3606 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3607 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003608 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003609 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003610 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003611 T->startDefinition();
3612 QualType Int32Ty = IntTy;
3613 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3614 QualType FieldTypes[] = {
3615 getPointerType(VoidPtrTy),
3616 getPointerType(getTagDeclType(T)),
3617 Int32Ty,
3618 Int32Ty,
3619 getPointerType(VoidPtrTy),
3620 getPointerType(VoidPtrTy),
3621 Ty
3622 };
3623
Daniel Dunbar4087f272010-08-17 22:39:59 +00003624 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003625 "__isa",
3626 "__forwarding",
3627 "__flags",
3628 "__size",
3629 "__copy_helper",
3630 "__destroy_helper",
3631 DeclName,
3632 };
3633
3634 for (size_t i = 0; i < 7; ++i) {
3635 if (!HasCopyAndDispose && i >=4 && i <= 5)
3636 continue;
3637 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3638 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003639 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003640 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003641 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003642 T->addDecl(Field);
3643 }
3644
Douglas Gregor838db382010-02-11 01:19:42 +00003645 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003646
3647 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003648}
3649
Douglas Gregor319ac892009-04-23 22:29:11 +00003650void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003651 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003652 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3653 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3654}
3655
Anders Carlssone8c49532007-10-29 06:33:42 +00003656// This returns true if a type has been typedefed to BOOL:
3657// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003658static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003659 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003660 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3661 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003662
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003663 return false;
3664}
3665
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003666/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003667/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003668CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck199c3d62010-01-11 17:06:35 +00003669 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003670
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003671 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003672 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003673 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003674 // Treat arrays as pointers, since that's how they're passed in.
3675 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003676 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003677 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003678}
3679
3680static inline
3681std::string charUnitsToString(const CharUnits &CU) {
3682 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003683}
3684
John McCall6b5a61b2011-02-07 10:33:21 +00003685/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003686/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00003687std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3688 std::string S;
3689
David Chisnall5e530af2009-11-17 19:33:30 +00003690 const BlockDecl *Decl = Expr->getBlockDecl();
3691 QualType BlockTy =
3692 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3693 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003694 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003695 // Compute size of all parameters.
3696 // Start with computing size of a pointer in number of bytes.
3697 // FIXME: There might(should) be a better way of doing this computation!
3698 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003699 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3700 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003701 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003702 E = Decl->param_end(); PI != E; ++PI) {
3703 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003704 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003705 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003706 ParmOffset += sz;
3707 }
3708 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003709 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003710 // Block pointer and offset.
3711 S += "@?0";
3712 ParmOffset = PtrSize;
3713
3714 // Argument types.
3715 ParmOffset = PtrSize;
3716 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3717 Decl->param_end(); PI != E; ++PI) {
3718 ParmVarDecl *PVDecl = *PI;
3719 QualType PType = PVDecl->getOriginalType();
3720 if (const ArrayType *AT =
3721 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3722 // Use array's original type only if it has known number of
3723 // elements.
3724 if (!isa<ConstantArrayType>(AT))
3725 PType = PVDecl->getType();
3726 } else if (PType->isFunctionType())
3727 PType = PVDecl->getType();
3728 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003729 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003730 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003731 }
John McCall6b5a61b2011-02-07 10:33:21 +00003732
3733 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00003734}
3735
David Chisnall5389f482010-12-30 14:05:53 +00003736void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3737 std::string& S) {
3738 // Encode result type.
3739 getObjCEncodingForType(Decl->getResultType(), S);
3740 CharUnits ParmOffset;
3741 // Compute size of all parameters.
3742 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3743 E = Decl->param_end(); PI != E; ++PI) {
3744 QualType PType = (*PI)->getType();
3745 CharUnits sz = getObjCEncodingTypeSize(PType);
3746 assert (sz.isPositive() &&
3747 "getObjCEncodingForMethodDecl - Incomplete param type");
3748 ParmOffset += sz;
3749 }
3750 S += charUnitsToString(ParmOffset);
3751 ParmOffset = CharUnits::Zero();
3752
3753 // Argument types.
3754 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3755 E = Decl->param_end(); PI != E; ++PI) {
3756 ParmVarDecl *PVDecl = *PI;
3757 QualType PType = PVDecl->getOriginalType();
3758 if (const ArrayType *AT =
3759 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3760 // Use array's original type only if it has known number of
3761 // elements.
3762 if (!isa<ConstantArrayType>(AT))
3763 PType = PVDecl->getType();
3764 } else if (PType->isFunctionType())
3765 PType = PVDecl->getType();
3766 getObjCEncodingForType(PType, S);
3767 S += charUnitsToString(ParmOffset);
3768 ParmOffset += getObjCEncodingTypeSize(PType);
3769 }
3770}
3771
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003772/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003773/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003774void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00003775 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003776 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003777 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003778 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003779 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003780 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003781 // Compute size of all parameters.
3782 // Start with computing size of a pointer in number of bytes.
3783 // FIXME: There might(should) be a better way of doing this computation!
3784 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003785 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003786 // The first two arguments (self and _cmd) are pointers; account for
3787 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003788 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003789 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003790 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003791 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003792 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003793 assert (sz.isPositive() &&
3794 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003795 ParmOffset += sz;
3796 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003797 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003798 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003799 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003800
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003801 // Argument types.
3802 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003803 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003804 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003805 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003806 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003807 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003808 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3809 // Use array's original type only if it has known number of
3810 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003811 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003812 PType = PVDecl->getType();
3813 } else if (PType->isFunctionType())
3814 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003815 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003816 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003817 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003818 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003819 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003820 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003821 }
3822}
3823
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003824/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003825/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003826/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3827/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003828/// Property attributes are stored as a comma-delimited C string. The simple
3829/// attributes readonly and bycopy are encoded as single characters. The
3830/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3831/// encoded as single characters, followed by an identifier. Property types
3832/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003833/// these attributes are defined by the following enumeration:
3834/// @code
3835/// enum PropertyAttributes {
3836/// kPropertyReadOnly = 'R', // property is read-only.
3837/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3838/// kPropertyByref = '&', // property is a reference to the value last assigned
3839/// kPropertyDynamic = 'D', // property is dynamic
3840/// kPropertyGetter = 'G', // followed by getter selector name
3841/// kPropertySetter = 'S', // followed by setter selector name
3842/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3843/// kPropertyType = 't' // followed by old-style type encoding.
3844/// kPropertyWeak = 'W' // 'weak' property
3845/// kPropertyStrong = 'P' // property GC'able
3846/// kPropertyNonAtomic = 'N' // property non-atomic
3847/// };
3848/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003849void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003850 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00003851 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003852 // Collect information from the property implementation decl(s).
3853 bool Dynamic = false;
3854 ObjCPropertyImplDecl *SynthesizePID = 0;
3855
3856 // FIXME: Duplicated code due to poor abstraction.
3857 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003858 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003859 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3860 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003861 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003862 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003863 ObjCPropertyImplDecl *PID = *i;
3864 if (PID->getPropertyDecl() == PD) {
3865 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3866 Dynamic = true;
3867 } else {
3868 SynthesizePID = PID;
3869 }
3870 }
3871 }
3872 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003873 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003874 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003875 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003876 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003877 ObjCPropertyImplDecl *PID = *i;
3878 if (PID->getPropertyDecl() == PD) {
3879 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3880 Dynamic = true;
3881 } else {
3882 SynthesizePID = PID;
3883 }
3884 }
Mike Stump1eb44332009-09-09 15:08:12 +00003885 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003886 }
3887 }
3888
3889 // FIXME: This is not very efficient.
3890 S = "T";
3891
3892 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003893 // GCC has some special rules regarding encoding of properties which
3894 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003895 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003896 true /* outermost type */,
3897 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003898
3899 if (PD->isReadOnly()) {
3900 S += ",R";
3901 } else {
3902 switch (PD->getSetterKind()) {
3903 case ObjCPropertyDecl::Assign: break;
3904 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003905 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003906 }
3907 }
3908
3909 // It really isn't clear at all what this means, since properties
3910 // are "dynamic by default".
3911 if (Dynamic)
3912 S += ",D";
3913
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003914 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3915 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003916
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003917 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3918 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003919 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003920 }
3921
3922 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3923 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003924 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003925 }
3926
3927 if (SynthesizePID) {
3928 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3929 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003930 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003931 }
3932
3933 // FIXME: OBJCGC: weak & strong
3934}
3935
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003936/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003937/// Another legacy compatibility encoding: 32-bit longs are encoded as
3938/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003939/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3940///
3941void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003942 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003943 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00003944 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003945 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003946 else
Jay Foad4ba2a172011-01-12 09:06:06 +00003947 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003948 PointeeTy = IntTy;
3949 }
3950 }
3951}
3952
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003953void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00003954 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003955 // We follow the behavior of gcc, expanding structures which are
3956 // directly pointed to, and expanding embedded structures. Note that
3957 // these rules are sufficient to prevent recursive encoding of the
3958 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003959 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003960 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003961}
3962
David Chisnall64fd7e82010-06-04 01:10:52 +00003963static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3964 switch (T->getAs<BuiltinType>()->getKind()) {
3965 default: assert(0 && "Unhandled builtin type kind");
3966 case BuiltinType::Void: return 'v';
3967 case BuiltinType::Bool: return 'B';
3968 case BuiltinType::Char_U:
3969 case BuiltinType::UChar: return 'C';
3970 case BuiltinType::UShort: return 'S';
3971 case BuiltinType::UInt: return 'I';
3972 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00003973 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00003974 case BuiltinType::UInt128: return 'T';
3975 case BuiltinType::ULongLong: return 'Q';
3976 case BuiltinType::Char_S:
3977 case BuiltinType::SChar: return 'c';
3978 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00003979 case BuiltinType::WChar_S:
3980 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00003981 case BuiltinType::Int: return 'i';
3982 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00003983 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00003984 case BuiltinType::LongLong: return 'q';
3985 case BuiltinType::Int128: return 't';
3986 case BuiltinType::Float: return 'f';
3987 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00003988 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00003989 }
3990}
3991
Jay Foad4ba2a172011-01-12 09:06:06 +00003992static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003993 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003994 const Expr *E = FD->getBitWidth();
3995 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003996 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003997 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3998 // The GNU runtime requires more information; bitfields are encoded as b,
3999 // then the offset (in bits) of the first element, then the type of the
4000 // bitfield, then the size in bits. For example, in this structure:
4001 //
4002 // struct
4003 // {
4004 // int integer;
4005 // int flags:2;
4006 // };
4007 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4008 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4009 // information is not especially sensible, but we're stuck with it for
4010 // compatibility with GCC, although providing it breaks anything that
4011 // actually uses runtime introspection and wants to work on both runtimes...
4012 if (!Ctx->getLangOptions().NeXTRuntime) {
4013 const RecordDecl *RD = FD->getParent();
4014 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4015 // FIXME: This same linear search is also used in ExprConstant - it might
4016 // be better if the FieldDecl stored its offset. We'd be increasing the
4017 // size of the object slightly, but saving some time every time it is used.
4018 unsigned i = 0;
4019 for (RecordDecl::field_iterator Field = RD->field_begin(),
4020 FieldEnd = RD->field_end();
4021 Field != FieldEnd; (void)++Field, ++i) {
4022 if (*Field == FD)
4023 break;
4024 }
4025 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnallc7ff82c2010-12-26 20:12:30 +00004026 if (T->isEnumeralType())
4027 S += 'i';
4028 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004029 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004030 }
4031 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004032 S += llvm::utostr(N);
4033}
4034
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004035// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004036void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4037 bool ExpandPointedToStructures,
4038 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004039 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004040 bool OutermostType,
Jay Foad4ba2a172011-01-12 09:06:06 +00004041 bool EncodingProperty) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004042 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004043 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004044 return EncodeBitField(this, S, T, FD);
4045 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004046 return;
4047 }
Mike Stump1eb44332009-09-09 15:08:12 +00004048
John McCall183700f2009-09-21 23:43:11 +00004049 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004050 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004051 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004052 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004053 return;
4054 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004055
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004056 // encoding for pointer or r3eference types.
4057 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004058 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004059 if (PT->isObjCSelType()) {
4060 S += ':';
4061 return;
4062 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004063 PointeeTy = PT->getPointeeType();
4064 }
4065 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4066 PointeeTy = RT->getPointeeType();
4067 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004068 bool isReadOnly = false;
4069 // For historical/compatibility reasons, the read-only qualifier of the
4070 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4071 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004072 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004073 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004074 if (OutermostType && T.isConstQualified()) {
4075 isReadOnly = true;
4076 S += 'r';
4077 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004078 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004079 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004080 while (P->getAs<PointerType>())
4081 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004082 if (P.isConstQualified()) {
4083 isReadOnly = true;
4084 S += 'r';
4085 }
4086 }
4087 if (isReadOnly) {
4088 // Another legacy compatibility encoding. Some ObjC qualifier and type
4089 // combinations need to be rearranged.
4090 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00004091 if (llvm::StringRef(S).endswith("nr"))
4092 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004093 }
Mike Stump1eb44332009-09-09 15:08:12 +00004094
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004095 if (PointeeTy->isCharType()) {
4096 // char pointer types should be encoded as '*' unless it is a
4097 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004098 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004099 S += '*';
4100 return;
4101 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004102 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004103 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4104 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4105 S += '#';
4106 return;
4107 }
4108 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4109 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4110 S += '@';
4111 return;
4112 }
4113 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004114 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004115 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004116 getLegacyIntegralTypeEncoding(PointeeTy);
4117
Mike Stump1eb44332009-09-09 15:08:12 +00004118 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004119 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004120 return;
4121 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004122
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004123 if (const ArrayType *AT =
4124 // Ignore type qualifiers etc.
4125 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004126 if (isa<IncompleteArrayType>(AT)) {
4127 // Incomplete arrays are encoded as a pointer to the array element.
4128 S += '^';
4129
Mike Stump1eb44332009-09-09 15:08:12 +00004130 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004131 false, ExpandStructures, FD);
4132 } else {
4133 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004134
Anders Carlsson559a8332009-02-22 01:38:57 +00004135 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4136 S += llvm::utostr(CAT->getSize().getZExtValue());
4137 else {
4138 //Variable length arrays are encoded as a regular array with 0 elements.
4139 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4140 S += '0';
4141 }
Mike Stump1eb44332009-09-09 15:08:12 +00004142
4143 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004144 false, ExpandStructures, FD);
4145 S += ']';
4146 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004147 return;
4148 }
Mike Stump1eb44332009-09-09 15:08:12 +00004149
John McCall183700f2009-09-21 23:43:11 +00004150 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004151 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004152 return;
4153 }
Mike Stump1eb44332009-09-09 15:08:12 +00004154
Ted Kremenek6217b802009-07-29 21:53:49 +00004155 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004156 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004157 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004158 // Anonymous structures print as '?'
4159 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4160 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004161 if (ClassTemplateSpecializationDecl *Spec
4162 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4163 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4164 std::string TemplateArgsStr
4165 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004166 TemplateArgs.data(),
4167 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004168 (*this).PrintingPolicy);
4169
4170 S += TemplateArgsStr;
4171 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004172 } else {
4173 S += '?';
4174 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004175 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004176 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004177 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4178 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00004179 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004180 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004181 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00004182 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004183 S += '"';
4184 }
Mike Stump1eb44332009-09-09 15:08:12 +00004185
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004186 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004187 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004188 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004189 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004190 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004191 QualType qt = Field->getType();
4192 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00004193 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004194 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004195 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004196 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004197 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004198 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004199 return;
4200 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004201
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004202 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004203 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004204 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004205 else
4206 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004207 return;
4208 }
Mike Stump1eb44332009-09-09 15:08:12 +00004209
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004210 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004211 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004212 return;
4213 }
Mike Stump1eb44332009-09-09 15:08:12 +00004214
John McCallc12c5bb2010-05-15 11:32:37 +00004215 // Ignore protocol qualifiers when mangling at this level.
4216 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4217 T = OT->getBaseType();
4218
John McCall0953e762009-09-24 19:53:00 +00004219 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004220 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004221 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004222 S += '{';
4223 const IdentifierInfo *II = OI->getIdentifier();
4224 S += II->getName();
4225 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004226 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4227 DeepCollectObjCIvars(OI, true, Ivars);
4228 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4229 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4230 if (Field->isBitField())
4231 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004232 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004233 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004234 }
4235 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004236 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004237 }
Mike Stump1eb44332009-09-09 15:08:12 +00004238
John McCall183700f2009-09-21 23:43:11 +00004239 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004240 if (OPT->isObjCIdType()) {
4241 S += '@';
4242 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004243 }
Mike Stump1eb44332009-09-09 15:08:12 +00004244
Steve Naroff27d20a22009-10-28 22:03:49 +00004245 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4246 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4247 // Since this is a binary compatibility issue, need to consult with runtime
4248 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004249 S += '#';
4250 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004251 }
Mike Stump1eb44332009-09-09 15:08:12 +00004252
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004253 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004254 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004255 ExpandPointedToStructures,
4256 ExpandStructures, FD);
4257 if (FD || EncodingProperty) {
4258 // Note that we do extended encoding of protocol qualifer list
4259 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004260 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004261 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4262 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004263 S += '<';
4264 S += (*I)->getNameAsString();
4265 S += '>';
4266 }
4267 S += '"';
4268 }
4269 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004270 }
Mike Stump1eb44332009-09-09 15:08:12 +00004271
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004272 QualType PointeeTy = OPT->getPointeeType();
4273 if (!EncodingProperty &&
4274 isa<TypedefType>(PointeeTy.getTypePtr())) {
4275 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004276 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004277 // {...};
4278 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004279 getObjCEncodingForTypeImpl(PointeeTy, S,
4280 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004281 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004282 return;
4283 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004284
4285 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004286 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004287 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004288 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004289 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4290 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004291 S += '<';
4292 S += (*I)->getNameAsString();
4293 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004294 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004295 S += '"';
4296 }
4297 return;
4298 }
Mike Stump1eb44332009-09-09 15:08:12 +00004299
John McCall532ec7b2010-05-17 23:56:34 +00004300 // gcc just blithely ignores member pointers.
4301 // TODO: maybe there should be a mangling for these
4302 if (T->getAs<MemberPointerType>())
4303 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004304
4305 if (T->isVectorType()) {
4306 // This matches gcc's encoding, even though technically it is
4307 // insufficient.
4308 // FIXME. We should do a better job than gcc.
4309 return;
4310 }
4311
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004312 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004313}
4314
Mike Stump1eb44332009-09-09 15:08:12 +00004315void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004316 std::string& S) const {
4317 if (QT & Decl::OBJC_TQ_In)
4318 S += 'n';
4319 if (QT & Decl::OBJC_TQ_Inout)
4320 S += 'N';
4321 if (QT & Decl::OBJC_TQ_Out)
4322 S += 'o';
4323 if (QT & Decl::OBJC_TQ_Bycopy)
4324 S += 'O';
4325 if (QT & Decl::OBJC_TQ_Byref)
4326 S += 'R';
4327 if (QT & Decl::OBJC_TQ_Oneway)
4328 S += 'V';
4329}
4330
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004331void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004332 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004333
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004334 BuiltinVaListType = T;
4335}
4336
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004337void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004338 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00004339}
4340
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004341void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004342 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004343}
4344
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004345void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004346 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004347}
4348
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004349void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004350 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004351}
4352
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004353void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004354 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004355 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004356
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004357 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004358}
4359
John McCall0bd6feb2009-12-02 08:04:21 +00004360/// \brief Retrieve the template name that corresponds to a non-empty
4361/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004362TemplateName
4363ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4364 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004365 unsigned size = End - Begin;
4366 assert(size > 1 && "set is not overloaded!");
4367
4368 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4369 size * sizeof(FunctionTemplateDecl*));
4370 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4371
4372 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004373 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004374 NamedDecl *D = *I;
4375 assert(isa<FunctionTemplateDecl>(D) ||
4376 (isa<UsingShadowDecl>(D) &&
4377 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4378 *Storage++ = D;
4379 }
4380
4381 return TemplateName(OT);
4382}
4383
Douglas Gregor7532dc62009-03-30 22:58:21 +00004384/// \brief Retrieve the template name that represents a qualified
4385/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004386TemplateName
4387ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4388 bool TemplateKeyword,
4389 TemplateDecl *Template) const {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004390 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004391 llvm::FoldingSetNodeID ID;
4392 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4393
4394 void *InsertPos = 0;
4395 QualifiedTemplateName *QTN =
4396 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4397 if (!QTN) {
4398 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4399 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4400 }
4401
4402 return TemplateName(QTN);
4403}
4404
4405/// \brief Retrieve the template name that represents a dependent
4406/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004407TemplateName
4408ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4409 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004410 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004411 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004412
4413 llvm::FoldingSetNodeID ID;
4414 DependentTemplateName::Profile(ID, NNS, Name);
4415
4416 void *InsertPos = 0;
4417 DependentTemplateName *QTN =
4418 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4419
4420 if (QTN)
4421 return TemplateName(QTN);
4422
4423 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4424 if (CanonNNS == NNS) {
4425 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4426 } else {
4427 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4428 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004429 DependentTemplateName *CheckQTN =
4430 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4431 assert(!CheckQTN && "Dependent type name canonicalization broken");
4432 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004433 }
4434
4435 DependentTemplateNames.InsertNode(QTN, InsertPos);
4436 return TemplateName(QTN);
4437}
4438
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004439/// \brief Retrieve the template name that represents a dependent
4440/// template name such as \c MetaFun::template operator+.
4441TemplateName
4442ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004443 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004444 assert((!NNS || NNS->isDependent()) &&
4445 "Nested name specifier must be dependent");
4446
4447 llvm::FoldingSetNodeID ID;
4448 DependentTemplateName::Profile(ID, NNS, Operator);
4449
4450 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004451 DependentTemplateName *QTN
4452 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004453
4454 if (QTN)
4455 return TemplateName(QTN);
4456
4457 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4458 if (CanonNNS == NNS) {
4459 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4460 } else {
4461 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4462 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004463
4464 DependentTemplateName *CheckQTN
4465 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4466 assert(!CheckQTN && "Dependent template name canonicalization broken");
4467 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004468 }
4469
4470 DependentTemplateNames.InsertNode(QTN, InsertPos);
4471 return TemplateName(QTN);
4472}
4473
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004474TemplateName
4475ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4476 const TemplateArgument &ArgPack) const {
4477 ASTContext &Self = const_cast<ASTContext &>(*this);
4478 llvm::FoldingSetNodeID ID;
4479 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4480
4481 void *InsertPos = 0;
4482 SubstTemplateTemplateParmPackStorage *Subst
4483 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4484
4485 if (!Subst) {
4486 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4487 ArgPack.pack_size(),
4488 ArgPack.pack_begin());
4489 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4490 }
4491
4492 return TemplateName(Subst);
4493}
4494
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004495/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004496/// TargetInfo, produce the corresponding type. The unsigned @p Type
4497/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004498CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004499 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004500 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004501 case TargetInfo::SignedShort: return ShortTy;
4502 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4503 case TargetInfo::SignedInt: return IntTy;
4504 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4505 case TargetInfo::SignedLong: return LongTy;
4506 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4507 case TargetInfo::SignedLongLong: return LongLongTy;
4508 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4509 }
4510
4511 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004512 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004513}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004514
4515//===----------------------------------------------------------------------===//
4516// Type Predicates.
4517//===----------------------------------------------------------------------===//
4518
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004519/// isObjCNSObjectType - Return true if this is an NSObject object using
4520/// NSObject attribute on a c-style pointer type.
4521/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004522/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004523///
4524bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCallf4c73712011-01-19 06:33:43 +00004525 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004526 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004527 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004528 return true;
4529 }
Mike Stump1eb44332009-09-09 15:08:12 +00004530 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004531}
4532
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004533/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4534/// garbage collection attribute.
4535///
John McCallae278a32011-01-12 00:34:59 +00004536Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4537 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4538 return Qualifiers::GCNone;
4539
4540 assert(getLangOptions().ObjC1);
4541 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4542
4543 // Default behaviour under objective-C's gc is for ObjC pointers
4544 // (or pointers to them) be treated as though they were declared
4545 // as __strong.
4546 if (GCAttrs == Qualifiers::GCNone) {
4547 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4548 return Qualifiers::Strong;
4549 else if (Ty->isPointerType())
4550 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4551 } else {
4552 // It's not valid to set GC attributes on anything that isn't a
4553 // pointer.
4554#ifndef NDEBUG
4555 QualType CT = Ty->getCanonicalTypeInternal();
4556 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4557 CT = AT->getElementType();
4558 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4559#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004560 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004561 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004562}
4563
Chris Lattner6ac46a42008-04-07 06:51:04 +00004564//===----------------------------------------------------------------------===//
4565// Type Compatibility Testing
4566//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004567
Mike Stump1eb44332009-09-09 15:08:12 +00004568/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004569/// compatible.
4570static bool areCompatVectorTypes(const VectorType *LHS,
4571 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004572 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004573 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004574 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004575}
4576
Douglas Gregor255210e2010-08-06 10:14:59 +00004577bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4578 QualType SecondVec) {
4579 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4580 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4581
4582 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4583 return true;
4584
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004585 // Treat Neon vector types and most AltiVec vector types as if they are the
4586 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004587 const VectorType *First = FirstVec->getAs<VectorType>();
4588 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004589 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004590 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004591 First->getVectorKind() != VectorType::AltiVecPixel &&
4592 First->getVectorKind() != VectorType::AltiVecBool &&
4593 Second->getVectorKind() != VectorType::AltiVecPixel &&
4594 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004595 return true;
4596
4597 return false;
4598}
4599
Steve Naroff4084c302009-07-23 01:01:38 +00004600//===----------------------------------------------------------------------===//
4601// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4602//===----------------------------------------------------------------------===//
4603
4604/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4605/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00004606bool
4607ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4608 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00004609 if (lProto == rProto)
4610 return true;
4611 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4612 E = rProto->protocol_end(); PI != E; ++PI)
4613 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4614 return true;
4615 return false;
4616}
4617
Steve Naroff4084c302009-07-23 01:01:38 +00004618/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4619/// return true if lhs's protocols conform to rhs's protocol; false
4620/// otherwise.
4621bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4622 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4623 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4624 return false;
4625}
4626
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004627/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4628/// Class<p1, ...>.
4629bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4630 QualType rhs) {
4631 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4632 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4633 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4634
4635 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4636 E = lhsQID->qual_end(); I != E; ++I) {
4637 bool match = false;
4638 ObjCProtocolDecl *lhsProto = *I;
4639 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4640 E = rhsOPT->qual_end(); J != E; ++J) {
4641 ObjCProtocolDecl *rhsProto = *J;
4642 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4643 match = true;
4644 break;
4645 }
4646 }
4647 if (!match)
4648 return false;
4649 }
4650 return true;
4651}
4652
Steve Naroff4084c302009-07-23 01:01:38 +00004653/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4654/// ObjCQualifiedIDType.
4655bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4656 bool compare) {
4657 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004658 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004659 lhs->isObjCIdType() || lhs->isObjCClassType())
4660 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004661 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004662 rhs->isObjCIdType() || rhs->isObjCClassType())
4663 return true;
4664
4665 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004666 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004667
Steve Naroff4084c302009-07-23 01:01:38 +00004668 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004669
Steve Naroff4084c302009-07-23 01:01:38 +00004670 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004671 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004672 // make sure we check the class hierarchy.
4673 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4674 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4675 E = lhsQID->qual_end(); I != E; ++I) {
4676 // when comparing an id<P> on lhs with a static type on rhs,
4677 // see if static class implements all of id's protocols, directly or
4678 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004679 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004680 return false;
4681 }
4682 }
4683 // If there are no qualifiers and no interface, we have an 'id'.
4684 return true;
4685 }
Mike Stump1eb44332009-09-09 15:08:12 +00004686 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004687 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4688 E = lhsQID->qual_end(); I != E; ++I) {
4689 ObjCProtocolDecl *lhsProto = *I;
4690 bool match = false;
4691
4692 // when comparing an id<P> on lhs with a static type on rhs,
4693 // see if static class implements all of id's protocols, directly or
4694 // through its super class and categories.
4695 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4696 E = rhsOPT->qual_end(); J != E; ++J) {
4697 ObjCProtocolDecl *rhsProto = *J;
4698 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4699 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4700 match = true;
4701 break;
4702 }
4703 }
Mike Stump1eb44332009-09-09 15:08:12 +00004704 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004705 // make sure we check the class hierarchy.
4706 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4707 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4708 E = lhsQID->qual_end(); I != E; ++I) {
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.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004712 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004713 match = true;
4714 break;
4715 }
4716 }
4717 }
4718 if (!match)
4719 return false;
4720 }
Mike Stump1eb44332009-09-09 15:08:12 +00004721
Steve Naroff4084c302009-07-23 01:01:38 +00004722 return true;
4723 }
Mike Stump1eb44332009-09-09 15:08:12 +00004724
Steve Naroff4084c302009-07-23 01:01:38 +00004725 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4726 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4727
Mike Stump1eb44332009-09-09 15:08:12 +00004728 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004729 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004730 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004731 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4732 E = lhsOPT->qual_end(); I != E; ++I) {
4733 ObjCProtocolDecl *lhsProto = *I;
4734 bool match = false;
4735
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004736 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00004737 // see if static class implements all of id's protocols, directly or
4738 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004739 // First, lhs protocols in the qualifier list must be found, direct
4740 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00004741 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4742 E = rhsQID->qual_end(); J != E; ++J) {
4743 ObjCProtocolDecl *rhsProto = *J;
4744 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4745 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4746 match = true;
4747 break;
4748 }
4749 }
4750 if (!match)
4751 return false;
4752 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004753
4754 // Static class's protocols, or its super class or category protocols
4755 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4756 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4757 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4758 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4759 // This is rather dubious but matches gcc's behavior. If lhs has
4760 // no type qualifier and its class has no static protocol(s)
4761 // assume that it is mismatch.
4762 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4763 return false;
4764 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4765 LHSInheritedProtocols.begin(),
4766 E = LHSInheritedProtocols.end(); I != E; ++I) {
4767 bool match = false;
4768 ObjCProtocolDecl *lhsProto = (*I);
4769 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4770 E = rhsQID->qual_end(); J != E; ++J) {
4771 ObjCProtocolDecl *rhsProto = *J;
4772 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4773 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4774 match = true;
4775 break;
4776 }
4777 }
4778 if (!match)
4779 return false;
4780 }
4781 }
Steve Naroff4084c302009-07-23 01:01:38 +00004782 return true;
4783 }
4784 return false;
4785}
4786
Eli Friedman3d815e72008-08-22 00:56:42 +00004787/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004788/// compatible for assignment from RHS to LHS. This handles validation of any
4789/// protocol qualifiers on the LHS or RHS.
4790///
Steve Naroff14108da2009-07-10 23:34:53 +00004791bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4792 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004793 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4794 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4795
Steve Naroffde2e22d2009-07-15 18:40:39 +00004796 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004797 if (LHS->isObjCUnqualifiedIdOrClass() ||
4798 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004799 return true;
4800
John McCallc12c5bb2010-05-15 11:32:37 +00004801 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004802 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4803 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004804 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004805
4806 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4807 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4808 QualType(RHSOPT,0));
4809
John McCallc12c5bb2010-05-15 11:32:37 +00004810 // If we have 2 user-defined types, fall into that path.
4811 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004812 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004813
Steve Naroff4084c302009-07-23 01:01:38 +00004814 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004815}
4816
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004817/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4818/// for providing type-safty for objective-c pointers used to pass/return
4819/// arguments in block literals. When passed as arguments, passing 'A*' where
4820/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4821/// not OK. For the return type, the opposite is not OK.
4822bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4823 const ObjCObjectPointerType *LHSOPT,
4824 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004825 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004826 return true;
4827
4828 if (LHSOPT->isObjCBuiltinType()) {
4829 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4830 }
4831
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004832 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004833 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4834 QualType(RHSOPT,0),
4835 false);
4836
4837 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4838 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4839 if (LHS && RHS) { // We have 2 user-defined types.
4840 if (LHS != RHS) {
4841 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4842 return false;
4843 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4844 return true;
4845 }
4846 else
4847 return true;
4848 }
4849 return false;
4850}
4851
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004852/// getIntersectionOfProtocols - This routine finds the intersection of set
4853/// of protocols inherited from two distinct objective-c pointer objects.
4854/// It is used to build composite qualifier list of the composite type of
4855/// the conditional expression involving two objective-c pointer objects.
4856static
4857void getIntersectionOfProtocols(ASTContext &Context,
4858 const ObjCObjectPointerType *LHSOPT,
4859 const ObjCObjectPointerType *RHSOPT,
4860 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4861
John McCallc12c5bb2010-05-15 11:32:37 +00004862 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4863 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4864 assert(LHS->getInterface() && "LHS must have an interface base");
4865 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004866
4867 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4868 unsigned LHSNumProtocols = LHS->getNumProtocols();
4869 if (LHSNumProtocols > 0)
4870 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4871 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004872 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004873 Context.CollectInheritedProtocols(LHS->getInterface(),
4874 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004875 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4876 LHSInheritedProtocols.end());
4877 }
4878
4879 unsigned RHSNumProtocols = RHS->getNumProtocols();
4880 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004881 ObjCProtocolDecl **RHSProtocols =
4882 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004883 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4884 if (InheritedProtocolSet.count(RHSProtocols[i]))
4885 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4886 }
4887 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004888 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004889 Context.CollectInheritedProtocols(RHS->getInterface(),
4890 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004891 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4892 RHSInheritedProtocols.begin(),
4893 E = RHSInheritedProtocols.end(); I != E; ++I)
4894 if (InheritedProtocolSet.count((*I)))
4895 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004896 }
4897}
4898
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004899/// areCommonBaseCompatible - Returns common base class of the two classes if
4900/// one found. Note that this is O'2 algorithm. But it will be called as the
4901/// last type comparison in a ?-exp of ObjC pointer types before a
4902/// warning is issued. So, its invokation is extremely rare.
4903QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004904 const ObjCObjectPointerType *Lptr,
4905 const ObjCObjectPointerType *Rptr) {
4906 const ObjCObjectType *LHS = Lptr->getObjectType();
4907 const ObjCObjectType *RHS = Rptr->getObjectType();
4908 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4909 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4910 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004911 return QualType();
4912
John McCallc12c5bb2010-05-15 11:32:37 +00004913 while ((LDecl = LDecl->getSuperClass())) {
4914 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004915 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004916 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4917 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4918
4919 QualType Result = QualType(LHS, 0);
4920 if (!Protocols.empty())
4921 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4922 Result = getObjCObjectPointerType(Result);
4923 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004924 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004925 }
4926
4927 return QualType();
4928}
4929
John McCallc12c5bb2010-05-15 11:32:37 +00004930bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4931 const ObjCObjectType *RHS) {
4932 assert(LHS->getInterface() && "LHS is not an interface type");
4933 assert(RHS->getInterface() && "RHS is not an interface type");
4934
Chris Lattner6ac46a42008-04-07 06:51:04 +00004935 // Verify that the base decls are compatible: the RHS must be a subclass of
4936 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004937 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004938 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004939
Chris Lattner6ac46a42008-04-07 06:51:04 +00004940 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4941 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004942 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004943 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004944
Chris Lattner6ac46a42008-04-07 06:51:04 +00004945 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4946 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004947 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004948 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004949
John McCallc12c5bb2010-05-15 11:32:37 +00004950 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4951 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004952 LHSPI != LHSPE; LHSPI++) {
4953 bool RHSImplementsProtocol = false;
4954
4955 // If the RHS doesn't implement the protocol on the left, the types
4956 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004957 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4958 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004959 RHSPI != RHSPE; RHSPI++) {
4960 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004961 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004962 break;
4963 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004964 }
4965 // FIXME: For better diagnostics, consider passing back the protocol name.
4966 if (!RHSImplementsProtocol)
4967 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004968 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004969 // The RHS implements all protocols listed on the LHS.
4970 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004971}
4972
Steve Naroff389bf462009-02-12 17:52:19 +00004973bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4974 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004975 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4976 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004977
Steve Naroff14108da2009-07-10 23:34:53 +00004978 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004979 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004980
4981 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4982 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004983}
4984
Douglas Gregor569c3162010-08-07 11:51:51 +00004985bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4986 return canAssignObjCInterfaces(
4987 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4988 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4989}
4990
Mike Stump1eb44332009-09-09 15:08:12 +00004991/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004992/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004993/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004994/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00004995bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4996 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004997 if (getLangOptions().CPlusPlus)
4998 return hasSameType(LHS, RHS);
4999
Douglas Gregor447234d2010-07-29 15:18:02 +00005000 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005001}
5002
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005003bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5004 return !mergeTypes(LHS, RHS, true).isNull();
5005}
5006
Peter Collingbourne48466752010-10-24 18:30:18 +00005007/// mergeTransparentUnionType - if T is a transparent union type and a member
5008/// of T is compatible with SubType, return the merged type, else return
5009/// QualType()
5010QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5011 bool OfBlockPointer,
5012 bool Unqualified) {
5013 if (const RecordType *UT = T->getAsUnionType()) {
5014 RecordDecl *UD = UT->getDecl();
5015 if (UD->hasAttr<TransparentUnionAttr>()) {
5016 for (RecordDecl::field_iterator it = UD->field_begin(),
5017 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005018 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005019 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5020 if (!MT.isNull())
5021 return MT;
5022 }
5023 }
5024 }
5025
5026 return QualType();
5027}
5028
5029/// mergeFunctionArgumentTypes - merge two types which appear as function
5030/// argument types
5031QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5032 bool OfBlockPointer,
5033 bool Unqualified) {
5034 // GNU extension: two types are compatible if they appear as a function
5035 // argument, one of the types is a transparent union type and the other
5036 // type is compatible with a union member
5037 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5038 Unqualified);
5039 if (!lmerge.isNull())
5040 return lmerge;
5041
5042 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5043 Unqualified);
5044 if (!rmerge.isNull())
5045 return rmerge;
5046
5047 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5048}
5049
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005050QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005051 bool OfBlockPointer,
5052 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005053 const FunctionType *lbase = lhs->getAs<FunctionType>();
5054 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005055 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5056 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005057 bool allLTypes = true;
5058 bool allRTypes = true;
5059
5060 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005061 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005062 if (OfBlockPointer) {
5063 QualType RHS = rbase->getResultType();
5064 QualType LHS = lbase->getResultType();
5065 bool UnqualifiedResult = Unqualified;
5066 if (!UnqualifiedResult)
5067 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
5068 retType = mergeTypes(RHS, LHS, true, UnqualifiedResult);
5069 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005070 else
John McCall8cc246c2010-12-15 01:06:38 +00005071 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5072 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005073 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005074
5075 if (Unqualified)
5076 retType = retType.getUnqualifiedType();
5077
5078 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5079 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5080 if (Unqualified) {
5081 LRetType = LRetType.getUnqualifiedType();
5082 RRetType = RRetType.getUnqualifiedType();
5083 }
5084
5085 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005086 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005087 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005088 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005089
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005090 // FIXME: double check this
5091 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5092 // rbase->getRegParmAttr() != 0 &&
5093 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005094 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5095 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005096
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005097 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005098 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005099 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005100
John McCall8cc246c2010-12-15 01:06:38 +00005101 // Regparm is part of the calling convention.
5102 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5103 return QualType();
5104
5105 // It's noreturn if either type is.
5106 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5107 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5108 if (NoReturn != lbaseInfo.getNoReturn())
5109 allLTypes = false;
5110 if (NoReturn != rbaseInfo.getNoReturn())
5111 allRTypes = false;
5112
5113 FunctionType::ExtInfo einfo(NoReturn,
5114 lbaseInfo.getRegParm(),
5115 lbaseInfo.getCC());
John McCalle23cf432010-12-14 08:05:40 +00005116
Eli Friedman3d815e72008-08-22 00:56:42 +00005117 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005118 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5119 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005120 unsigned lproto_nargs = lproto->getNumArgs();
5121 unsigned rproto_nargs = rproto->getNumArgs();
5122
5123 // Compatible functions must have the same number of arguments
5124 if (lproto_nargs != rproto_nargs)
5125 return QualType();
5126
5127 // Variadic and non-variadic functions aren't compatible
5128 if (lproto->isVariadic() != rproto->isVariadic())
5129 return QualType();
5130
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005131 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5132 return QualType();
5133
Eli Friedman3d815e72008-08-22 00:56:42 +00005134 // Check argument compatibility
5135 llvm::SmallVector<QualType, 10> types;
5136 for (unsigned i = 0; i < lproto_nargs; i++) {
5137 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5138 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005139 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5140 OfBlockPointer,
5141 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005142 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005143
5144 if (Unqualified)
5145 argtype = argtype.getUnqualifiedType();
5146
Eli Friedman3d815e72008-08-22 00:56:42 +00005147 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005148 if (Unqualified) {
5149 largtype = largtype.getUnqualifiedType();
5150 rargtype = rargtype.getUnqualifiedType();
5151 }
5152
Chris Lattner61710852008-10-05 17:34:18 +00005153 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5154 allLTypes = false;
5155 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5156 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005157 }
5158 if (allLTypes) return lhs;
5159 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005160
5161 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5162 EPI.ExtInfo = einfo;
5163 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005164 }
5165
5166 if (lproto) allRTypes = false;
5167 if (rproto) allLTypes = false;
5168
Douglas Gregor72564e72009-02-26 23:50:07 +00005169 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005170 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005171 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005172 if (proto->isVariadic()) return QualType();
5173 // Check that the types are compatible with the types that
5174 // would result from default argument promotions (C99 6.7.5.3p15).
5175 // The only types actually affected are promotable integer
5176 // types and floats, which would be passed as a different
5177 // type depending on whether the prototype is visible.
5178 unsigned proto_nargs = proto->getNumArgs();
5179 for (unsigned i = 0; i < proto_nargs; ++i) {
5180 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005181
5182 // Look at the promotion type of enum types, since that is the type used
5183 // to pass enum values.
5184 if (const EnumType *Enum = argTy->getAs<EnumType>())
5185 argTy = Enum->getDecl()->getPromotionType();
5186
Eli Friedman3d815e72008-08-22 00:56:42 +00005187 if (argTy->isPromotableIntegerType() ||
5188 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5189 return QualType();
5190 }
5191
5192 if (allLTypes) return lhs;
5193 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005194
5195 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5196 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005197 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005198 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005199 }
5200
5201 if (allLTypes) return lhs;
5202 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005203 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005204}
5205
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005206QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005207 bool OfBlockPointer,
5208 bool Unqualified) {
Bill Wendling43d69752007-12-03 07:33:35 +00005209 // C++ [expr]: If an expression initially has the type "reference to T", the
5210 // type is adjusted to "T" prior to any further analysis, the expression
5211 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005212 // expression is an lvalue unless the reference is an rvalue reference and
5213 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005214 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5215 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005216
5217 if (Unqualified) {
5218 LHS = LHS.getUnqualifiedType();
5219 RHS = RHS.getUnqualifiedType();
5220 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005221
Eli Friedman3d815e72008-08-22 00:56:42 +00005222 QualType LHSCan = getCanonicalType(LHS),
5223 RHSCan = getCanonicalType(RHS);
5224
5225 // If two types are identical, they are compatible.
5226 if (LHSCan == RHSCan)
5227 return LHS;
5228
John McCall0953e762009-09-24 19:53:00 +00005229 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005230 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5231 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005232 if (LQuals != RQuals) {
5233 // If any of these qualifiers are different, we have a type
5234 // mismatch.
5235 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5236 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5237 return QualType();
5238
5239 // Exactly one GC qualifier difference is allowed: __strong is
5240 // okay if the other type has no GC qualifier but is an Objective
5241 // C object pointer (i.e. implicitly strong by default). We fix
5242 // this by pretending that the unqualified type was actually
5243 // qualified __strong.
5244 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5245 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5246 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5247
5248 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5249 return QualType();
5250
5251 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5252 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5253 }
5254 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5255 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5256 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005257 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005258 }
5259
5260 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005261
Eli Friedman852d63b2009-06-01 01:22:52 +00005262 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5263 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005264
Chris Lattner1adb8832008-01-14 05:45:46 +00005265 // We want to consider the two function types to be the same for these
5266 // comparisons, just force one to the other.
5267 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5268 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005269
5270 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005271 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5272 LHSClass = Type::ConstantArray;
5273 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5274 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005275
John McCallc12c5bb2010-05-15 11:32:37 +00005276 // ObjCInterfaces are just specialized ObjCObjects.
5277 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5278 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5279
Nate Begeman213541a2008-04-18 23:10:10 +00005280 // Canonicalize ExtVector -> Vector.
5281 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5282 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005283
Chris Lattnera36a61f2008-04-07 05:43:21 +00005284 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005285 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005286 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005287 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005288 // Compatibility is based on the underlying type, not the promotion
5289 // type.
John McCall183700f2009-09-21 23:43:11 +00005290 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005291 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5292 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005293 }
John McCall183700f2009-09-21 23:43:11 +00005294 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005295 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5296 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005297 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005298
Eli Friedman3d815e72008-08-22 00:56:42 +00005299 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005300 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005301
Steve Naroff4a746782008-01-09 22:43:08 +00005302 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005303 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005304#define TYPE(Class, Base)
5305#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005306#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005307#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5308#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5309#include "clang/AST/TypeNodes.def"
5310 assert(false && "Non-canonical and dependent types shouldn't get here");
5311 return QualType();
5312
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005313 case Type::LValueReference:
5314 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005315 case Type::MemberPointer:
5316 assert(false && "C++ should never be in mergeTypes");
5317 return QualType();
5318
John McCallc12c5bb2010-05-15 11:32:37 +00005319 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005320 case Type::IncompleteArray:
5321 case Type::VariableArray:
5322 case Type::FunctionProto:
5323 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005324 assert(false && "Types are eliminated above");
5325 return QualType();
5326
Chris Lattner1adb8832008-01-14 05:45:46 +00005327 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005328 {
5329 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005330 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5331 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005332 if (Unqualified) {
5333 LHSPointee = LHSPointee.getUnqualifiedType();
5334 RHSPointee = RHSPointee.getUnqualifiedType();
5335 }
5336 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5337 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005338 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005339 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005340 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005341 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005342 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005343 return getPointerType(ResultType);
5344 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005345 case Type::BlockPointer:
5346 {
5347 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005348 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5349 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005350 if (Unqualified) {
5351 LHSPointee = LHSPointee.getUnqualifiedType();
5352 RHSPointee = RHSPointee.getUnqualifiedType();
5353 }
5354 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5355 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005356 if (ResultType.isNull()) return QualType();
5357 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5358 return LHS;
5359 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5360 return RHS;
5361 return getBlockPointerType(ResultType);
5362 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005363 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005364 {
5365 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5366 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5367 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5368 return QualType();
5369
5370 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5371 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005372 if (Unqualified) {
5373 LHSElem = LHSElem.getUnqualifiedType();
5374 RHSElem = RHSElem.getUnqualifiedType();
5375 }
5376
5377 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005378 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005379 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5380 return LHS;
5381 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5382 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005383 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5384 ArrayType::ArraySizeModifier(), 0);
5385 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5386 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005387 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5388 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005389 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5390 return LHS;
5391 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5392 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005393 if (LVAT) {
5394 // FIXME: This isn't correct! But tricky to implement because
5395 // the array's size has to be the size of LHS, but the type
5396 // has to be different.
5397 return LHS;
5398 }
5399 if (RVAT) {
5400 // FIXME: This isn't correct! But tricky to implement because
5401 // the array's size has to be the size of RHS, but the type
5402 // has to be different.
5403 return RHS;
5404 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005405 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5406 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005407 return getIncompleteArrayType(ResultType,
5408 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005409 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005410 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005411 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005412 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005413 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005414 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005415 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005416 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005417 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005418 case Type::Complex:
5419 // Distinct complex types are incompatible.
5420 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005421 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005422 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005423 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5424 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005425 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005426 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005427 case Type::ObjCObject: {
5428 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005429 // FIXME: This should be type compatibility, e.g. whether
5430 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005431 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5432 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5433 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005434 return LHS;
5435
Eli Friedman3d815e72008-08-22 00:56:42 +00005436 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005437 }
Steve Naroff14108da2009-07-10 23:34:53 +00005438 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005439 if (OfBlockPointer) {
5440 if (canAssignObjCInterfacesInBlockPointer(
5441 LHS->getAs<ObjCObjectPointerType>(),
5442 RHS->getAs<ObjCObjectPointerType>()))
5443 return LHS;
5444 return QualType();
5445 }
John McCall183700f2009-09-21 23:43:11 +00005446 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5447 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005448 return LHS;
5449
Steve Naroffbc76dd02008-12-10 22:14:21 +00005450 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005451 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005452 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005453
5454 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005455}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005456
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005457/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5458/// 'RHS' attributes and returns the merged version; including for function
5459/// return types.
5460QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5461 QualType LHSCan = getCanonicalType(LHS),
5462 RHSCan = getCanonicalType(RHS);
5463 // If two types are identical, they are compatible.
5464 if (LHSCan == RHSCan)
5465 return LHS;
5466 if (RHSCan->isFunctionType()) {
5467 if (!LHSCan->isFunctionType())
5468 return QualType();
5469 QualType OldReturnType =
5470 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5471 QualType NewReturnType =
5472 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5473 QualType ResReturnType =
5474 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5475 if (ResReturnType.isNull())
5476 return QualType();
5477 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5478 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5479 // In either case, use OldReturnType to build the new function type.
5480 const FunctionType *F = LHS->getAs<FunctionType>();
5481 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005482 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5483 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005484 QualType ResultType
5485 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005486 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005487 return ResultType;
5488 }
5489 }
5490 return QualType();
5491 }
5492
5493 // If the qualifiers are different, the types can still be merged.
5494 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5495 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5496 if (LQuals != RQuals) {
5497 // If any of these qualifiers are different, we have a type mismatch.
5498 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5499 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5500 return QualType();
5501
5502 // Exactly one GC qualifier difference is allowed: __strong is
5503 // okay if the other type has no GC qualifier but is an Objective
5504 // C object pointer (i.e. implicitly strong by default). We fix
5505 // this by pretending that the unqualified type was actually
5506 // qualified __strong.
5507 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5508 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5509 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5510
5511 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5512 return QualType();
5513
5514 if (GC_L == Qualifiers::Strong)
5515 return LHS;
5516 if (GC_R == Qualifiers::Strong)
5517 return RHS;
5518 return QualType();
5519 }
5520
5521 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5522 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5523 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5524 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5525 if (ResQT == LHSBaseQT)
5526 return LHS;
5527 if (ResQT == RHSBaseQT)
5528 return RHS;
5529 }
5530 return QualType();
5531}
5532
Chris Lattner5426bf62008-04-07 07:01:58 +00005533//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005534// Integer Predicates
5535//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005536
Jay Foad4ba2a172011-01-12 09:06:06 +00005537unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00005538 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005539 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005540 if (T->isBooleanType())
5541 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005542 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005543 return (unsigned)getTypeSize(T);
5544}
5545
5546QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005547 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005548
5549 // Turn <4 x signed int> -> <4 x unsigned int>
5550 if (const VectorType *VTy = T->getAs<VectorType>())
5551 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005552 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005553
5554 // For enums, we return the unsigned version of the base type.
5555 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005556 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005557
5558 const BuiltinType *BTy = T->getAs<BuiltinType>();
5559 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005560 switch (BTy->getKind()) {
5561 case BuiltinType::Char_S:
5562 case BuiltinType::SChar:
5563 return UnsignedCharTy;
5564 case BuiltinType::Short:
5565 return UnsignedShortTy;
5566 case BuiltinType::Int:
5567 return UnsignedIntTy;
5568 case BuiltinType::Long:
5569 return UnsignedLongTy;
5570 case BuiltinType::LongLong:
5571 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005572 case BuiltinType::Int128:
5573 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005574 default:
5575 assert(0 && "Unexpected signed integer type");
5576 return QualType();
5577 }
5578}
5579
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005580ASTMutationListener::~ASTMutationListener() { }
5581
Chris Lattner86df27b2009-06-14 00:45:47 +00005582
5583//===----------------------------------------------------------------------===//
5584// Builtin Type Computation
5585//===----------------------------------------------------------------------===//
5586
5587/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00005588/// pointer over the consumed characters. This returns the resultant type. If
5589/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5590/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5591/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00005592///
5593/// RequiresICE is filled in on return to indicate whether the value is required
5594/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00005595static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005596 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00005597 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00005598 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005599 // Modifiers.
5600 int HowLong = 0;
5601 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00005602 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005603
Chris Lattner33daae62010-10-01 22:42:38 +00005604 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00005605 bool Done = false;
5606 while (!Done) {
5607 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005608 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005609 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00005610 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005611 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005612 case 'S':
5613 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5614 assert(!Signed && "Can't use 'S' modifier multiple times!");
5615 Signed = true;
5616 break;
5617 case 'U':
5618 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5619 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5620 Unsigned = true;
5621 break;
5622 case 'L':
5623 assert(HowLong <= 2 && "Can't have LLLL modifier");
5624 ++HowLong;
5625 break;
5626 }
5627 }
5628
5629 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005630
Chris Lattner86df27b2009-06-14 00:45:47 +00005631 // Read the base type.
5632 switch (*Str++) {
5633 default: assert(0 && "Unknown builtin type letter!");
5634 case 'v':
5635 assert(HowLong == 0 && !Signed && !Unsigned &&
5636 "Bad modifiers used with 'v'!");
5637 Type = Context.VoidTy;
5638 break;
5639 case 'f':
5640 assert(HowLong == 0 && !Signed && !Unsigned &&
5641 "Bad modifiers used with 'f'!");
5642 Type = Context.FloatTy;
5643 break;
5644 case 'd':
5645 assert(HowLong < 2 && !Signed && !Unsigned &&
5646 "Bad modifiers used with 'd'!");
5647 if (HowLong)
5648 Type = Context.LongDoubleTy;
5649 else
5650 Type = Context.DoubleTy;
5651 break;
5652 case 's':
5653 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5654 if (Unsigned)
5655 Type = Context.UnsignedShortTy;
5656 else
5657 Type = Context.ShortTy;
5658 break;
5659 case 'i':
5660 if (HowLong == 3)
5661 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5662 else if (HowLong == 2)
5663 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5664 else if (HowLong == 1)
5665 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5666 else
5667 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5668 break;
5669 case 'c':
5670 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5671 if (Signed)
5672 Type = Context.SignedCharTy;
5673 else if (Unsigned)
5674 Type = Context.UnsignedCharTy;
5675 else
5676 Type = Context.CharTy;
5677 break;
5678 case 'b': // boolean
5679 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5680 Type = Context.BoolTy;
5681 break;
5682 case 'z': // size_t.
5683 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5684 Type = Context.getSizeType();
5685 break;
5686 case 'F':
5687 Type = Context.getCFConstantStringType();
5688 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00005689 case 'G':
5690 Type = Context.getObjCIdType();
5691 break;
5692 case 'H':
5693 Type = Context.getObjCSelType();
5694 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005695 case 'a':
5696 Type = Context.getBuiltinVaListType();
5697 assert(!Type.isNull() && "builtin va list type not initialized!");
5698 break;
5699 case 'A':
5700 // This is a "reference" to a va_list; however, what exactly
5701 // this means depends on how va_list is defined. There are two
5702 // different kinds of va_list: ones passed by value, and ones
5703 // passed by reference. An example of a by-value va_list is
5704 // x86, where va_list is a char*. An example of by-ref va_list
5705 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5706 // we want this argument to be a char*&; for x86-64, we want
5707 // it to be a __va_list_tag*.
5708 Type = Context.getBuiltinVaListType();
5709 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00005710 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00005711 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00005712 else
Chris Lattner86df27b2009-06-14 00:45:47 +00005713 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005714 break;
5715 case 'V': {
5716 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005717 unsigned NumElements = strtoul(Str, &End, 10);
5718 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00005719 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005720
Chris Lattner14e0e742010-10-01 22:53:11 +00005721 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5722 RequiresICE, false);
5723 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00005724
5725 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005726 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00005727 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00005728 break;
5729 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005730 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00005731 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5732 false);
5733 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00005734 Type = Context.getComplexType(ElementType);
5735 break;
5736 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005737 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005738 Type = Context.getFILEType();
5739 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005740 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005741 return QualType();
5742 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005743 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005744 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005745 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005746 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005747 else
5748 Type = Context.getjmp_bufType();
5749
Mike Stumpfd612db2009-07-28 23:47:15 +00005750 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005751 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005752 return QualType();
5753 }
5754 break;
Mike Stump782fa302009-07-28 02:25:19 +00005755 }
Mike Stump1eb44332009-09-09 15:08:12 +00005756
Chris Lattner33daae62010-10-01 22:42:38 +00005757 // If there are modifiers and if we're allowed to parse them, go for it.
5758 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00005759 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005760 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00005761 default: Done = true; --Str; break;
5762 case '*':
5763 case '&': {
5764 // Both pointers and references can have their pointee types
5765 // qualified with an address space.
5766 char *End;
5767 unsigned AddrSpace = strtoul(Str, &End, 10);
5768 if (End != Str && AddrSpace != 0) {
5769 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5770 Str = End;
5771 }
5772 if (c == '*')
5773 Type = Context.getPointerType(Type);
5774 else
5775 Type = Context.getLValueReferenceType(Type);
5776 break;
5777 }
5778 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5779 case 'C':
5780 Type = Type.withConst();
5781 break;
5782 case 'D':
5783 Type = Context.getVolatileType(Type);
5784 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005785 }
5786 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00005787
Chris Lattner14e0e742010-10-01 22:53:11 +00005788 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00005789 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00005790
Chris Lattner86df27b2009-06-14 00:45:47 +00005791 return Type;
5792}
5793
5794/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00005795QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00005796 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00005797 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00005798 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00005799
Chris Lattner86df27b2009-06-14 00:45:47 +00005800 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005801
Chris Lattner14e0e742010-10-01 22:53:11 +00005802 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00005803 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00005804 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5805 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005806 if (Error != GE_None)
5807 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00005808
5809 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5810
Chris Lattner86df27b2009-06-14 00:45:47 +00005811 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00005812 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005813 if (Error != GE_None)
5814 return QualType();
5815
Chris Lattner14e0e742010-10-01 22:53:11 +00005816 // If this argument is required to be an IntegerConstantExpression and the
5817 // caller cares, fill in the bitmask we return.
5818 if (RequiresICE && IntegerConstantArgs)
5819 *IntegerConstantArgs |= 1 << ArgTypes.size();
5820
Chris Lattner86df27b2009-06-14 00:45:47 +00005821 // Do array -> pointer decay. The builtin should use the decayed type.
5822 if (Ty->isArrayType())
5823 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005824
Chris Lattner86df27b2009-06-14 00:45:47 +00005825 ArgTypes.push_back(Ty);
5826 }
5827
5828 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5829 "'.' should only occur at end of builtin type list!");
5830
John McCall00ccbef2010-12-21 00:44:39 +00005831 FunctionType::ExtInfo EI;
5832 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5833
5834 bool Variadic = (TypeStr[0] == '.');
5835
5836 // We really shouldn't be making a no-proto type here, especially in C++.
5837 if (ArgTypes.empty() && Variadic)
5838 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005839
John McCalle23cf432010-12-14 08:05:40 +00005840 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00005841 EPI.ExtInfo = EI;
5842 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00005843
5844 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00005845}
Eli Friedmana95d7572009-08-19 07:44:53 +00005846
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005847GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5848 GVALinkage External = GVA_StrongExternal;
5849
5850 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005851 switch (L) {
5852 case NoLinkage:
5853 case InternalLinkage:
5854 case UniqueExternalLinkage:
5855 return GVA_Internal;
5856
5857 case ExternalLinkage:
5858 switch (FD->getTemplateSpecializationKind()) {
5859 case TSK_Undeclared:
5860 case TSK_ExplicitSpecialization:
5861 External = GVA_StrongExternal;
5862 break;
5863
5864 case TSK_ExplicitInstantiationDefinition:
5865 return GVA_ExplicitTemplateInstantiation;
5866
5867 case TSK_ExplicitInstantiationDeclaration:
5868 case TSK_ImplicitInstantiation:
5869 External = GVA_TemplateInstantiation;
5870 break;
5871 }
5872 }
5873
5874 if (!FD->isInlined())
5875 return External;
5876
5877 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5878 // GNU or C99 inline semantics. Determine whether this symbol should be
5879 // externally visible.
5880 if (FD->isInlineDefinitionExternallyVisible())
5881 return External;
5882
5883 // C99 inline semantics, where the symbol is not externally visible.
5884 return GVA_C99Inline;
5885 }
5886
5887 // C++0x [temp.explicit]p9:
5888 // [ Note: The intent is that an inline function that is the subject of
5889 // an explicit instantiation declaration will still be implicitly
5890 // instantiated when used so that the body can be considered for
5891 // inlining, but that no out-of-line copy of the inline function would be
5892 // generated in the translation unit. -- end note ]
5893 if (FD->getTemplateSpecializationKind()
5894 == TSK_ExplicitInstantiationDeclaration)
5895 return GVA_C99Inline;
5896
5897 return GVA_CXXInline;
5898}
5899
5900GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5901 // If this is a static data member, compute the kind of template
5902 // specialization. Otherwise, this variable is not part of a
5903 // template.
5904 TemplateSpecializationKind TSK = TSK_Undeclared;
5905 if (VD->isStaticDataMember())
5906 TSK = VD->getTemplateSpecializationKind();
5907
5908 Linkage L = VD->getLinkage();
5909 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5910 VD->getType()->getLinkage() == UniqueExternalLinkage)
5911 L = UniqueExternalLinkage;
5912
5913 switch (L) {
5914 case NoLinkage:
5915 case InternalLinkage:
5916 case UniqueExternalLinkage:
5917 return GVA_Internal;
5918
5919 case ExternalLinkage:
5920 switch (TSK) {
5921 case TSK_Undeclared:
5922 case TSK_ExplicitSpecialization:
5923 return GVA_StrongExternal;
5924
5925 case TSK_ExplicitInstantiationDeclaration:
5926 llvm_unreachable("Variable should not be instantiated");
5927 // Fall through to treat this like any other instantiation.
5928
5929 case TSK_ExplicitInstantiationDefinition:
5930 return GVA_ExplicitTemplateInstantiation;
5931
5932 case TSK_ImplicitInstantiation:
5933 return GVA_TemplateInstantiation;
5934 }
5935 }
5936
5937 return GVA_StrongExternal;
5938}
5939
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00005940bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005941 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5942 if (!VD->isFileVarDecl())
5943 return false;
5944 } else if (!isa<FunctionDecl>(D))
5945 return false;
5946
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005947 // Weak references don't produce any output by themselves.
5948 if (D->hasAttr<WeakRefAttr>())
5949 return false;
5950
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005951 // Aliases and used decls are required.
5952 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5953 return true;
5954
5955 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5956 // Forward declarations aren't required.
5957 if (!FD->isThisDeclarationADefinition())
5958 return false;
5959
5960 // Constructors and destructors are required.
5961 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5962 return true;
5963
5964 // The key function for a class is required.
5965 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5966 const CXXRecordDecl *RD = MD->getParent();
5967 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5968 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5969 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5970 return true;
5971 }
5972 }
5973
5974 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5975
5976 // static, static inline, always_inline, and extern inline functions can
5977 // always be deferred. Normal inline functions can be deferred in C99/C++.
5978 // Implicit template instantiations can also be deferred in C++.
5979 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5980 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5981 return false;
5982 return true;
5983 }
5984
5985 const VarDecl *VD = cast<VarDecl>(D);
5986 assert(VD->isFileVarDecl() && "Expected file scoped var");
5987
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005988 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5989 return false;
5990
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005991 // Structs that have non-trivial constructors or destructors are required.
5992
5993 // FIXME: Handle references.
5994 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5995 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005996 if (RD->hasDefinition() &&
5997 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005998 return true;
5999 }
6000 }
6001
6002 GVALinkage L = GetGVALinkageForVariable(VD);
6003 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6004 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6005 return false;
6006 }
6007
6008 return true;
6009}
Charles Davis071cc7d2010-08-16 03:33:14 +00006010
Charles Davisee743f92010-11-09 18:04:24 +00006011CallingConv ASTContext::getDefaultMethodCallConv() {
6012 // Pass through to the C++ ABI object
6013 return ABI->getDefaultMethodCallConv();
6014}
6015
Jay Foad4ba2a172011-01-12 09:06:06 +00006016bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006017 // Pass through to the C++ ABI object
6018 return ABI->isNearlyEmpty(RD);
6019}
6020
Peter Collingbourne14110472011-01-13 18:57:25 +00006021MangleContext *ASTContext::createMangleContext() {
6022 switch (Target.getCXXABI()) {
6023 case CXXABI_ARM:
6024 case CXXABI_Itanium:
6025 return createItaniumMangleContext(*this, getDiagnostics());
6026 case CXXABI_Microsoft:
6027 return createMicrosoftMangleContext(*this, getDiagnostics());
6028 }
6029 assert(0 && "Unsupported ABI");
6030 return 0;
6031}
6032
Charles Davis071cc7d2010-08-16 03:33:14 +00006033CXXABI::~CXXABI() {}