blob: 3d74d3a9380af93f6278333e36e49472d2548443 [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(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000110 SourceLocation(),
111 SourceLocation(),
112 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000113 TTP->getIndex(), 0, false,
114 TTP->isParameterPack()));
115 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000116 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
117 QualType T = getCanonicalType(NTTP->getType());
118 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
119 NonTypeTemplateParmDecl *Param;
120 if (NTTP->isExpandedParameterPack()) {
121 llvm::SmallVector<QualType, 2> ExpandedTypes;
122 llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
123 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
124 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
125 ExpandedTInfos.push_back(
126 getTrivialTypeSourceInfo(ExpandedTypes.back()));
127 }
128
129 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000130 SourceLocation(),
131 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000132 NTTP->getDepth(),
133 NTTP->getPosition(), 0,
134 T,
135 TInfo,
136 ExpandedTypes.data(),
137 ExpandedTypes.size(),
138 ExpandedTInfos.data());
139 } else {
140 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000141 SourceLocation(),
142 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000143 NTTP->getDepth(),
144 NTTP->getPosition(), 0,
145 T,
146 NTTP->isParameterPack(),
147 TInfo);
148 }
149 CanonParams.push_back(Param);
150
151 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000152 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
153 cast<TemplateTemplateParmDecl>(*P)));
154 }
155
156 TemplateTemplateParmDecl *CanonTTP
157 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
158 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000159 TTP->getPosition(),
160 TTP->isParameterPack(),
161 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000162 TemplateParameterList::Create(*this, SourceLocation(),
163 SourceLocation(),
164 CanonParams.data(),
165 CanonParams.size(),
166 SourceLocation()));
167
168 // Get the new insert position for the node we care about.
169 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
170 assert(Canonical == 0 && "Shouldn't be in the map!");
171 (void)Canonical;
172
173 // Create the canonical template template parameter entry.
174 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
175 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
176 return CanonTTP;
177}
178
Charles Davis071cc7d2010-08-16 03:33:14 +0000179CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000180 if (!LangOpts.CPlusPlus) return 0;
181
Charles Davis20cf7172010-08-19 02:18:14 +0000182 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000183 case CXXABI_ARM:
184 return CreateARMCXXABI(*this);
185 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000186 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000187 case CXXABI_Microsoft:
188 return CreateMicrosoftCXXABI(*this);
189 }
John McCallee79a4c2010-08-21 22:46:04 +0000190 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000191}
192
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000193static const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
194 const LangOptions &LOpts) {
195 if (LOpts.FakeAddressSpaceMap) {
196 // The fake address space map must have a distinct entry for each
197 // language-specific address space.
198 static const unsigned FakeAddrSpaceMap[] = {
199 1, // opencl_global
200 2, // opencl_local
201 3 // opencl_constant
202 };
203 return FakeAddrSpaceMap;
204 } else {
205 return T.getAddressSpaceMap();
206 }
207}
208
Chris Lattner61710852008-10-05 17:34:18 +0000209ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000210 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000211 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000212 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000213 unsigned size_reserve) :
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000214 FunctionProtoTypes(this_()),
John McCallef990012010-06-11 11:07:21 +0000215 TemplateSpecializationTypes(this_()),
216 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000217 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
218 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000219 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000220 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Peter Collingbourne14b6ba72011-02-09 21:04:32 +0000221 cudaConfigureCallDecl(0),
John McCallbf1a0282010-06-04 23:28:52 +0000222 NullTypeSourceInfo(QualType()),
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000223 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
224 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000225 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000226 BuiltinInfo(builtins),
227 DeclarationNames(*this),
Argyrios Kyrtzidis9a44b5f2010-10-28 09:29:35 +0000228 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000229 LastSDM(0, 0),
John McCall8178df32011-02-22 22:38:33 +0000230 UniqueBlockByRefTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000231 ObjCIdRedefinitionType = QualType();
232 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000233 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000234 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000235 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000236 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000237}
238
Reid Spencer5f016e22007-07-11 17:01:13 +0000239ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000240 // Release the DenseMaps associated with DeclContext objects.
241 // FIXME: Is this the ideal solution?
242 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000243
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000244 // Call all of the deallocation functions.
245 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
246 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000247
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000248 // Release all of the memory associated with overridden C++ methods.
249 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
250 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
251 OM != OMEnd; ++OM)
252 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000253
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000254 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000255 // because they can contain DenseMaps.
256 for (llvm::DenseMap<const ObjCContainerDecl*,
257 const ASTRecordLayout*>::iterator
258 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
259 // Increment in loop to prevent using deallocated memory.
260 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
261 R->Destroy(*this);
262
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000263 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
264 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
265 // Increment in loop to prevent using deallocated memory.
266 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
267 R->Destroy(*this);
268 }
Douglas Gregor63200642010-08-30 16:49:28 +0000269
270 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
271 AEnd = DeclAttrs.end();
272 A != AEnd; ++A)
273 A->second->~AttrVec();
274}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000275
Douglas Gregor00545312010-05-23 18:26:36 +0000276void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
277 Deallocations.push_back(std::make_pair(Callback, Data));
278}
279
Mike Stump1eb44332009-09-09 15:08:12 +0000280void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000281ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
282 ExternalSource.reset(Source.take());
283}
284
Reid Spencer5f016e22007-07-11 17:01:13 +0000285void ASTContext::PrintStats() const {
286 fprintf(stderr, "*** AST Context Stats:\n");
287 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000288
Douglas Gregordbe833d2009-05-26 14:40:08 +0000289 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000290#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000291#define ABSTRACT_TYPE(Name, Parent)
292#include "clang/AST/TypeNodes.def"
293 0 // Extra
294 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000295
Reid Spencer5f016e22007-07-11 17:01:13 +0000296 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
297 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000298 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000299 }
300
Douglas Gregordbe833d2009-05-26 14:40:08 +0000301 unsigned Idx = 0;
302 unsigned TotalBytes = 0;
303#define TYPE(Name, Parent) \
304 if (counts[Idx]) \
305 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
306 TotalBytes += counts[Idx] * sizeof(Name##Type); \
307 ++Idx;
308#define ABSTRACT_TYPE(Name, Parent)
309#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Douglas Gregordbe833d2009-05-26 14:40:08 +0000311 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000312
Douglas Gregor4923aa22010-07-02 20:37:36 +0000313 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000314 fprintf(stderr, " %u/%u implicit default constructors created\n",
315 NumImplicitDefaultConstructorsDeclared,
316 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000317 fprintf(stderr, " %u/%u implicit copy constructors created\n",
318 NumImplicitCopyConstructorsDeclared,
319 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000320 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
321 NumImplicitCopyAssignmentOperatorsDeclared,
322 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000323 fprintf(stderr, " %u/%u implicit destructors created\n",
324 NumImplicitDestructorsDeclared, NumImplicitDestructors);
325
Douglas Gregor2cf26342009-04-09 22:27:44 +0000326 if (ExternalSource.get()) {
327 fprintf(stderr, "\n");
328 ExternalSource->PrintStats();
329 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000330
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000331 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000332}
333
334
John McCalle27ec8a2009-10-23 23:03:21 +0000335void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000336 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000337 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000338 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000339}
340
Reid Spencer5f016e22007-07-11 17:01:13 +0000341void ASTContext::InitBuiltinTypes() {
342 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Reid Spencer5f016e22007-07-11 17:01:13 +0000344 // C99 6.2.5p19.
345 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 // C99 6.2.5p2.
348 InitBuiltinType(BoolTy, BuiltinType::Bool);
349 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000350 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000351 InitBuiltinType(CharTy, BuiltinType::Char_S);
352 else
353 InitBuiltinType(CharTy, BuiltinType::Char_U);
354 // C99 6.2.5p4.
355 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
356 InitBuiltinType(ShortTy, BuiltinType::Short);
357 InitBuiltinType(IntTy, BuiltinType::Int);
358 InitBuiltinType(LongTy, BuiltinType::Long);
359 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // C99 6.2.5p6.
362 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
363 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
364 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
365 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
366 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 // C99 6.2.5p10.
369 InitBuiltinType(FloatTy, BuiltinType::Float);
370 InitBuiltinType(DoubleTy, BuiltinType::Double);
371 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000372
Chris Lattner2df9ced2009-04-30 02:43:43 +0000373 // GNU extension, 128-bit integers.
374 InitBuiltinType(Int128Ty, BuiltinType::Int128);
375 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
376
Chris Lattner3f59c972010-12-25 23:25:43 +0000377 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
378 if (!LangOpts.ShortWChar)
379 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
380 else // -fshort-wchar makes wchar_t be unsigned.
381 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
382 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000383 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000384
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000385 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
386 InitBuiltinType(Char16Ty, BuiltinType::Char16);
387 else // C99
388 Char16Ty = getFromTargetType(Target.getChar16Type());
389
390 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
391 InitBuiltinType(Char32Ty, BuiltinType::Char32);
392 else // C99
393 Char32Ty = getFromTargetType(Target.getChar32Type());
394
Douglas Gregor898574e2008-12-05 23:32:09 +0000395 // Placeholder type for type-dependent expressions whose type is
396 // completely unknown. No code should ever check a type against
397 // DependentTy and users should never see it; however, it is here to
398 // help diagnose failures to properly check for type-dependent
399 // expressions.
400 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000401
John McCall2a984ca2010-10-12 00:20:44 +0000402 // Placeholder type for functions.
403 InitBuiltinType(OverloadTy, BuiltinType::Overload);
404
John McCall1de4d4e2011-04-07 08:22:57 +0000405 // "any" type; useful for debugger-like clients.
406 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
407
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 // C99 6.2.5p11.
409 FloatComplexTy = getComplexType(FloatTy);
410 DoubleComplexTy = getComplexType(DoubleTy);
411 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000412
Steve Naroff7e219e42007-10-15 14:41:52 +0000413 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Steve Naroffde2e22d2009-07-15 18:40:39 +0000415 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
416 ObjCIdTypedefType = QualType();
417 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000418 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000420 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000421 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
422 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000423 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000424
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000425 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000427 // void * type
428 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000429
430 // nullptr type (C++0x 2.14.7)
431 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000432}
433
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000434Diagnostic &ASTContext::getDiagnostics() const {
435 return SourceMgr.getDiagnostics();
436}
437
Douglas Gregor63200642010-08-30 16:49:28 +0000438AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
439 AttrVec *&Result = DeclAttrs[D];
440 if (!Result) {
441 void *Mem = Allocate(sizeof(AttrVec));
442 Result = new (Mem) AttrVec;
443 }
444
445 return *Result;
446}
447
448/// \brief Erase the attributes corresponding to the given declaration.
449void ASTContext::eraseDeclAttrs(const Decl *D) {
450 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
451 if (Pos != DeclAttrs.end()) {
452 Pos->second->~AttrVec();
453 DeclAttrs.erase(Pos);
454 }
455}
456
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000457MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000458ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000459 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000460 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000461 = InstantiatedFromStaticDataMember.find(Var);
462 if (Pos == InstantiatedFromStaticDataMember.end())
463 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Douglas Gregor7caa6822009-07-24 20:34:43 +0000465 return Pos->second;
466}
467
Mike Stump1eb44332009-09-09 15:08:12 +0000468void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000469ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000470 TemplateSpecializationKind TSK,
471 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000472 assert(Inst->isStaticDataMember() && "Not a static data member");
473 assert(Tmpl->isStaticDataMember() && "Not a static data member");
474 assert(!InstantiatedFromStaticDataMember[Inst] &&
475 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000476 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000477 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000478}
479
John McCall7ba107a2009-11-18 02:36:19 +0000480NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000481ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000482 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000483 = InstantiatedFromUsingDecl.find(UUD);
484 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000485 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Anders Carlsson0d8df782009-08-29 19:37:28 +0000487 return Pos->second;
488}
489
490void
John McCalled976492009-12-04 22:46:56 +0000491ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
492 assert((isa<UsingDecl>(Pattern) ||
493 isa<UnresolvedUsingValueDecl>(Pattern) ||
494 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
495 "pattern decl is not a using decl");
496 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
497 InstantiatedFromUsingDecl[Inst] = Pattern;
498}
499
500UsingShadowDecl *
501ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
502 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
503 = InstantiatedFromUsingShadowDecl.find(Inst);
504 if (Pos == InstantiatedFromUsingShadowDecl.end())
505 return 0;
506
507 return Pos->second;
508}
509
510void
511ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
512 UsingShadowDecl *Pattern) {
513 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
514 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000515}
516
Anders Carlssond8b285f2009-09-01 04:26:58 +0000517FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
518 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
519 = InstantiatedFromUnnamedFieldDecl.find(Field);
520 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
521 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Anders Carlssond8b285f2009-09-01 04:26:58 +0000523 return Pos->second;
524}
525
526void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
527 FieldDecl *Tmpl) {
528 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
529 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
530 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
531 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000532
Anders Carlssond8b285f2009-09-01 04:26:58 +0000533 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
534}
535
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000536ASTContext::overridden_cxx_method_iterator
537ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
538 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
539 = OverriddenMethods.find(Method);
540 if (Pos == OverriddenMethods.end())
541 return 0;
542
543 return Pos->second.begin();
544}
545
546ASTContext::overridden_cxx_method_iterator
547ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
548 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
549 = OverriddenMethods.find(Method);
550 if (Pos == OverriddenMethods.end())
551 return 0;
552
553 return Pos->second.end();
554}
555
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000556unsigned
557ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
558 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
559 = OverriddenMethods.find(Method);
560 if (Pos == OverriddenMethods.end())
561 return 0;
562
563 return Pos->second.size();
564}
565
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000566void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
567 const CXXMethodDecl *Overridden) {
568 OverriddenMethods[Method].push_back(Overridden);
569}
570
Chris Lattner464175b2007-07-18 17:52:12 +0000571//===----------------------------------------------------------------------===//
572// Type Sizing and Analysis
573//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000574
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000575/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
576/// scalar floating point type.
577const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000578 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000579 assert(BT && "Not a floating point type!");
580 switch (BT->getKind()) {
581 default: assert(0 && "Not a floating point type!");
582 case BuiltinType::Float: return Target.getFloatFormat();
583 case BuiltinType::Double: return Target.getDoubleFormat();
584 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
585 }
586}
587
Ken Dyck8b752f12010-01-27 17:10:57 +0000588/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000589/// specified decl. Note that bitfields do not have a valid alignment, so
590/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000591/// If @p RefAsPointee, references are treated like their underlying type
592/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000593CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000594 unsigned Align = Target.getCharWidth();
595
John McCall4081a5c2010-10-08 18:24:19 +0000596 bool UseAlignAttrOnly = false;
597 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
598 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000599
John McCall4081a5c2010-10-08 18:24:19 +0000600 // __attribute__((aligned)) can increase or decrease alignment
601 // *except* on a struct or struct member, where it only increases
602 // alignment unless 'packed' is also specified.
603 //
604 // It is an error for [[align]] to decrease alignment, so we can
605 // ignore that possibility; Sema should diagnose it.
606 if (isa<FieldDecl>(D)) {
607 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
608 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
609 } else {
610 UseAlignAttrOnly = true;
611 }
612 }
613
John McCallba4f5d52011-01-20 07:57:12 +0000614 // If we're using the align attribute only, just ignore everything
615 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000616 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000617 // do nothing
618
John McCall4081a5c2010-10-08 18:24:19 +0000619 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000620 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000621 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000622 if (RefAsPointee)
623 T = RT->getPointeeType();
624 else
625 T = getPointerType(RT->getPointeeType());
626 }
627 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000628 // Adjust alignments of declarations with array type by the
629 // large-array alignment on the target.
Rafael Espindola6deecb02010-06-04 23:15:27 +0000630 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000631 const ArrayType *arrayType;
632 if (MinWidth && (arrayType = getAsArrayType(T))) {
633 if (isa<VariableArrayType>(arrayType))
634 Align = std::max(Align, Target.getLargeArrayAlign());
635 else if (isa<ConstantArrayType>(arrayType) &&
636 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
637 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000638
John McCall3b657512011-01-19 10:06:00 +0000639 // Walk through any array types while we're at it.
640 T = getBaseElementType(arrayType);
641 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000642 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
643 }
John McCallba4f5d52011-01-20 07:57:12 +0000644
645 // Fields can be subject to extra alignment constraints, like if
646 // the field is packed, the struct is packed, or the struct has a
647 // a max-field-alignment constraint (#pragma pack). So calculate
648 // the actual alignment of the field within the struct, and then
649 // (as we're expected to) constrain that by the alignment of the type.
650 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
651 // So calculate the alignment of the field.
652 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
653
654 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000655 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000656
657 // Use the GCD of that and the offset within the record.
658 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
659 if (offset > 0) {
660 // Alignment is always a power of 2, so the GCD will be a power of 2,
661 // which means we get to do this crazy thing instead of Euclid's.
662 uint64_t lowBitOfOffset = offset & (~offset + 1);
663 if (lowBitOfOffset < fieldAlign)
664 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
665 }
666
667 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000668 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000669 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000670
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000671 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000672}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000673
John McCallea1471e2010-05-20 01:18:31 +0000674std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000675ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000676 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000677 return std::make_pair(toCharUnitsFromBits(Info.first),
678 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000679}
680
681std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000682ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000683 return getTypeInfoInChars(T.getTypePtr());
684}
685
Chris Lattnera7674d82007-07-13 22:13:22 +0000686/// getTypeSize - Return the size of the specified type, in bits. This method
687/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000688///
689/// FIXME: Pointers into different addr spaces could have different sizes and
690/// alignment requirements: getPointerInfo should take an AddrSpace, this
691/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000692std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000693ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000694 uint64_t Width=0;
695 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000696 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000697#define TYPE(Class, Base)
698#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000699#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000700#define DEPENDENT_TYPE(Class, Base) case Type::Class:
701#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000702 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000703 break;
704
Chris Lattner692233e2007-07-13 22:27:08 +0000705 case Type::FunctionNoProto:
706 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000707 // GCC extension: alignof(function) = 32 bits
708 Width = 0;
709 Align = 32;
710 break;
711
Douglas Gregor72564e72009-02-26 23:50:07 +0000712 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000713 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000714 Width = 0;
715 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
716 break;
717
Steve Narofffb22d962007-08-30 01:06:46 +0000718 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000719 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Chris Lattner98be4942008-03-05 18:54:05 +0000721 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000722 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000723 Align = EltInfo.second;
724 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000725 }
Nate Begeman213541a2008-04-18 23:10:10 +0000726 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000727 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000728 const VectorType *VT = cast<VectorType>(T);
729 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
730 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000731 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000732 // If the alignment is not a power of 2, round up to the next power of 2.
733 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000734 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000735 Align = llvm::NextPowerOf2(Align);
736 Width = llvm::RoundUpToAlignment(Width, Align);
737 }
Chris Lattner030d8842007-07-19 22:06:24 +0000738 break;
739 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000740
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000741 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000742 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000743 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000744 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000745 // GCC extension: alignof(void) = 8 bits.
746 Width = 0;
747 Align = 8;
748 break;
749
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000750 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000751 Width = Target.getBoolWidth();
752 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000753 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000754 case BuiltinType::Char_S:
755 case BuiltinType::Char_U:
756 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000757 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000758 Width = Target.getCharWidth();
759 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000760 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000761 case BuiltinType::WChar_S:
762 case BuiltinType::WChar_U:
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000763 Width = Target.getWCharWidth();
764 Align = Target.getWCharAlign();
765 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000766 case BuiltinType::Char16:
767 Width = Target.getChar16Width();
768 Align = Target.getChar16Align();
769 break;
770 case BuiltinType::Char32:
771 Width = Target.getChar32Width();
772 Align = Target.getChar32Align();
773 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000774 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000775 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000776 Width = Target.getShortWidth();
777 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000778 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000779 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000780 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000781 Width = Target.getIntWidth();
782 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000783 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000784 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000785 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000786 Width = Target.getLongWidth();
787 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000788 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000789 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000790 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000791 Width = Target.getLongLongWidth();
792 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000793 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000794 case BuiltinType::Int128:
795 case BuiltinType::UInt128:
796 Width = 128;
797 Align = 128; // int128_t is 128-bit aligned on all targets.
798 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000799 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000800 Width = Target.getFloatWidth();
801 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000802 break;
803 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000804 Width = Target.getDoubleWidth();
805 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000806 break;
807 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000808 Width = Target.getLongDoubleWidth();
809 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000810 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000811 case BuiltinType::NullPtr:
812 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
813 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000814 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000815 case BuiltinType::ObjCId:
816 case BuiltinType::ObjCClass:
817 case BuiltinType::ObjCSel:
818 Width = Target.getPointerWidth(0);
819 Align = Target.getPointerAlign(0);
820 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000821 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000822 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000823 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000824 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000825 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000826 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000827 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000828 unsigned AS = getTargetAddressSpace(
829 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff485eeff2008-09-24 15:05:44 +0000830 Width = Target.getPointerWidth(AS);
831 Align = Target.getPointerAlign(AS);
832 break;
833 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000834 case Type::LValueReference:
835 case Type::RValueReference: {
836 // alignof and sizeof should never enter this code path here, so we go
837 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000838 unsigned AS = getTargetAddressSpace(
839 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl5d484e82009-11-23 17:18:46 +0000840 Width = Target.getPointerWidth(AS);
841 Align = Target.getPointerAlign(AS);
842 break;
843 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000844 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000845 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner5426bf62008-04-07 07:01:58 +0000846 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000847 Align = Target.getPointerAlign(AS);
848 break;
849 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000850 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000851 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000852 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000853 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000854 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000855 Align = PtrDiffInfo.second;
856 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000857 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000858 case Type::Complex: {
859 // Complex types have the same alignment as their elements, but twice the
860 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000861 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000862 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000863 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000864 Align = EltInfo.second;
865 break;
866 }
John McCallc12c5bb2010-05-15 11:32:37 +0000867 case Type::ObjCObject:
868 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000869 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000870 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000871 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000872 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000873 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +0000874 break;
875 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000876 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000877 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000878 const TagType *TT = cast<TagType>(T);
879
880 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +0000881 Width = 8;
882 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +0000883 break;
884 }
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Daniel Dunbar1d751182008-11-08 05:48:37 +0000886 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000887 return getTypeInfo(ET->getDecl()->getIntegerType());
888
Daniel Dunbar1d751182008-11-08 05:48:37 +0000889 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000890 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000891 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000892 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000893 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000894 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000895
Chris Lattner9fcfe922009-10-22 05:17:15 +0000896 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000897 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
898 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000899
Richard Smith34b41d92011-02-20 03:19:35 +0000900 case Type::Auto: {
901 const AutoType *A = cast<AutoType>(T);
902 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +0000903 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +0000904 }
905
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000906 case Type::Paren:
907 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
908
Douglas Gregor18857642009-04-30 17:32:17 +0000909 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +0000910 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000911 std::pair<uint64_t, unsigned> Info
912 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +0000913 // If the typedef has an aligned attribute on it, it overrides any computed
914 // alignment we have. This violates the GCC documentation (which says that
915 // attribute(aligned) can only round up) but matches its implementation.
916 if (unsigned AttrAlign = Typedef->getMaxAlignment())
917 Align = AttrAlign;
918 else
919 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +0000920 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000921 break;
Chris Lattner71763312008-04-06 22:05:18 +0000922 }
Douglas Gregor18857642009-04-30 17:32:17 +0000923
924 case Type::TypeOfExpr:
925 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
926 .getTypePtr());
927
928 case Type::TypeOf:
929 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
930
Anders Carlsson395b4752009-06-24 19:06:50 +0000931 case Type::Decltype:
932 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
933 .getTypePtr());
934
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000935 case Type::Elaborated:
936 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000937
John McCall9d156a72011-01-06 01:58:22 +0000938 case Type::Attributed:
939 return getTypeInfo(
940 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
941
Douglas Gregor18857642009-04-30 17:32:17 +0000942 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000943 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000944 "Cannot request the size of a dependent type");
945 // FIXME: this is likely to be wrong once we support template
946 // aliases, since a template alias could refer to a typedef that
947 // has an __aligned__ attribute on it.
948 return getTypeInfo(getCanonicalType(T));
949 }
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Chris Lattner464175b2007-07-18 17:52:12 +0000951 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000952 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000953}
954
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000955/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
956CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
957 return CharUnits::fromQuantity(BitSize / getCharWidth());
958}
959
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000960/// toBits - Convert a size in characters to a size in characters.
961int64_t ASTContext::toBits(CharUnits CharSize) const {
962 return CharSize.getQuantity() * getCharWidth();
963}
964
Ken Dyckbdc601b2009-12-22 14:23:30 +0000965/// getTypeSizeInChars - Return the size of the specified type, in characters.
966/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +0000967CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000968 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +0000969}
Jay Foad4ba2a172011-01-12 09:06:06 +0000970CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000971 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +0000972}
973
Ken Dyck16e20cc2010-01-26 17:25:18 +0000974/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000975/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +0000976CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000977 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +0000978}
Jay Foad4ba2a172011-01-12 09:06:06 +0000979CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000980 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +0000981}
982
Chris Lattner34ebde42009-01-27 18:08:34 +0000983/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
984/// type for the current target in bits. This can be different than the ABI
985/// alignment in cases where it is beneficial for performance to overalign
986/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +0000987unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +0000988 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000989
990 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000991 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000992 T = CT->getElementType().getTypePtr();
993 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
994 T->isSpecificBuiltinType(BuiltinType::LongLong))
995 return std::max(ABIAlign, (unsigned)getTypeSize(T));
996
Chris Lattner34ebde42009-01-27 18:08:34 +0000997 return ABIAlign;
998}
999
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001000/// ShallowCollectObjCIvars -
1001/// Collect all ivars, including those synthesized, in the current class.
1002///
1003void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad4ba2a172011-01-12 09:06:06 +00001004 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001005 // FIXME. This need be removed but there are two many places which
1006 // assume const-ness of ObjCInterfaceDecl
1007 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1008 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1009 Iv= Iv->getNextIvar())
1010 Ivars.push_back(Iv);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001011}
1012
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001013/// DeepCollectObjCIvars -
1014/// This routine first collects all declared, but not synthesized, ivars in
1015/// super class and then collects all ivars, including those synthesized for
1016/// current class. This routine is used for implementation of current class
1017/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001018///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001019void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1020 bool leafClass,
Jay Foad4ba2a172011-01-12 09:06:06 +00001021 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001022 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1023 DeepCollectObjCIvars(SuperClass, false, Ivars);
1024 if (!leafClass) {
1025 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1026 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001027 Ivars.push_back(*I);
1028 }
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001029 else
1030 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian98200742009-05-12 18:14:29 +00001031}
1032
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001033/// CollectInheritedProtocols - Collect all protocols in current class and
1034/// those inherited by it.
1035void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001036 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001037 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001038 // We can use protocol_iterator here instead of
1039 // all_referenced_protocol_iterator since we are walking all categories.
1040 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1041 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001042 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001043 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001044 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001045 PE = Proto->protocol_end(); P != PE; ++P) {
1046 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001047 CollectInheritedProtocols(*P, Protocols);
1048 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001049 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001050
1051 // Categories of this Interface.
1052 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1053 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1054 CollectInheritedProtocols(CDeclChain, Protocols);
1055 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1056 while (SD) {
1057 CollectInheritedProtocols(SD, Protocols);
1058 SD = SD->getSuperClass();
1059 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001060 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001061 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001062 PE = OC->protocol_end(); P != PE; ++P) {
1063 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001064 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001065 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1066 PE = Proto->protocol_end(); P != PE; ++P)
1067 CollectInheritedProtocols(*P, Protocols);
1068 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001069 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001070 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1071 PE = OP->protocol_end(); P != PE; ++P) {
1072 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001073 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001074 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1075 PE = Proto->protocol_end(); P != PE; ++P)
1076 CollectInheritedProtocols(*P, Protocols);
1077 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001078 }
1079}
1080
Jay Foad4ba2a172011-01-12 09:06:06 +00001081unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001082 unsigned count = 0;
1083 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001084 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1085 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001086 count += CDecl->ivar_size();
1087
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001088 // Count ivar defined in this class's implementation. This
1089 // includes synthesized ivars.
1090 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001091 count += ImplDecl->ivar_size();
1092
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001093 return count;
1094}
1095
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001096/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1097ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1098 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1099 I = ObjCImpls.find(D);
1100 if (I != ObjCImpls.end())
1101 return cast<ObjCImplementationDecl>(I->second);
1102 return 0;
1103}
1104/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1105ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1106 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1107 I = ObjCImpls.find(D);
1108 if (I != ObjCImpls.end())
1109 return cast<ObjCCategoryImplDecl>(I->second);
1110 return 0;
1111}
1112
1113/// \brief Set the implementation of ObjCInterfaceDecl.
1114void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1115 ObjCImplementationDecl *ImplD) {
1116 assert(IFaceD && ImplD && "Passed null params");
1117 ObjCImpls[IFaceD] = ImplD;
1118}
1119/// \brief Set the implementation of ObjCCategoryDecl.
1120void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1121 ObjCCategoryImplDecl *ImplD) {
1122 assert(CatD && ImplD && "Passed null params");
1123 ObjCImpls[CatD] = ImplD;
1124}
1125
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001126/// \brief Get the copy initialization expression of VarDecl,or NULL if
1127/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001128Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001129 assert(VD && "Passed null params");
1130 assert(VD->hasAttr<BlocksAttr>() &&
1131 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001132 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001133 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001134 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1135}
1136
1137/// \brief Set the copy inialization expression of a block var decl.
1138void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1139 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001140 assert(VD->hasAttr<BlocksAttr>() &&
1141 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001142 BlockVarCopyInits[VD] = Init;
1143}
1144
John McCalla93c9342009-12-07 02:54:59 +00001145/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001146///
John McCalla93c9342009-12-07 02:54:59 +00001147/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001148/// the TypeLoc wrappers.
1149///
1150/// \param T the type that will be the basis for type source info. This type
1151/// should refer to how the declarator was written in source code, not to
1152/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001153TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001154 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001155 if (!DataSize)
1156 DataSize = TypeLoc::getFullDataSizeForType(T);
1157 else
1158 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001159 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001160
John McCalla93c9342009-12-07 02:54:59 +00001161 TypeSourceInfo *TInfo =
1162 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1163 new (TInfo) TypeSourceInfo(T);
1164 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001165}
1166
John McCalla93c9342009-12-07 02:54:59 +00001167TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001168 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001169 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001170 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001171 return DI;
1172}
1173
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001174const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001175ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001176 return getObjCLayout(D, 0);
1177}
1178
1179const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001180ASTContext::getASTObjCImplementationLayout(
1181 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001182 return getObjCLayout(D->getClassInterface(), D);
1183}
1184
Chris Lattnera7674d82007-07-13 22:13:22 +00001185//===----------------------------------------------------------------------===//
1186// Type creation/memoization methods
1187//===----------------------------------------------------------------------===//
1188
Jay Foad4ba2a172011-01-12 09:06:06 +00001189QualType
John McCall3b657512011-01-19 10:06:00 +00001190ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1191 unsigned fastQuals = quals.getFastQualifiers();
1192 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001193
1194 // Check if we've already instantiated this type.
1195 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001196 ExtQuals::Profile(ID, baseType, quals);
1197 void *insertPos = 0;
1198 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1199 assert(eq->getQualifiers() == quals);
1200 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001201 }
1202
John McCall3b657512011-01-19 10:06:00 +00001203 // If the base type is not canonical, make the appropriate canonical type.
1204 QualType canon;
1205 if (!baseType->isCanonicalUnqualified()) {
1206 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1207 canonSplit.second.addConsistentQualifiers(quals);
1208 canon = getExtQualType(canonSplit.first, canonSplit.second);
1209
1210 // Re-find the insert position.
1211 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1212 }
1213
1214 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1215 ExtQualNodes.InsertNode(eq, insertPos);
1216 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001217}
1218
Jay Foad4ba2a172011-01-12 09:06:06 +00001219QualType
1220ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001221 QualType CanT = getCanonicalType(T);
1222 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001223 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001224
John McCall0953e762009-09-24 19:53:00 +00001225 // If we are composing extended qualifiers together, merge together
1226 // into one ExtQuals node.
1227 QualifierCollector Quals;
1228 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001229
John McCall0953e762009-09-24 19:53:00 +00001230 // If this type already has an address space specified, it cannot get
1231 // another one.
1232 assert(!Quals.hasAddressSpace() &&
1233 "Type cannot be in multiple addr spaces!");
1234 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
John McCall0953e762009-09-24 19:53:00 +00001236 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001237}
1238
Chris Lattnerb7d25532009-02-18 22:53:11 +00001239QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001240 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001241 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001242 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001243 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001244
John McCall7f040a92010-12-24 02:08:15 +00001245 if (const PointerType *ptr = T->getAs<PointerType>()) {
1246 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001247 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001248 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1249 return getPointerType(ResultType);
1250 }
1251 }
Mike Stump1eb44332009-09-09 15:08:12 +00001252
John McCall0953e762009-09-24 19:53:00 +00001253 // If we are composing extended qualifiers together, merge together
1254 // into one ExtQuals node.
1255 QualifierCollector Quals;
1256 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001257
John McCall0953e762009-09-24 19:53:00 +00001258 // If this type already has an ObjCGC specified, it cannot get
1259 // another one.
1260 assert(!Quals.hasObjCGCAttr() &&
1261 "Type cannot have multiple ObjCGCs!");
1262 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001263
John McCall0953e762009-09-24 19:53:00 +00001264 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001265}
Chris Lattnera7674d82007-07-13 22:13:22 +00001266
John McCalle6a365d2010-12-19 02:44:49 +00001267const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1268 FunctionType::ExtInfo Info) {
1269 if (T->getExtInfo() == Info)
1270 return T;
1271
1272 QualType Result;
1273 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1274 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1275 } else {
1276 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1277 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1278 EPI.ExtInfo = Info;
1279 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1280 FPT->getNumArgs(), EPI);
1281 }
1282
1283 return cast<FunctionType>(Result.getTypePtr());
1284}
1285
Reid Spencer5f016e22007-07-11 17:01:13 +00001286/// getComplexType - Return the uniqued reference to the type for a complex
1287/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001288QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 // Unique pointers, to guarantee there is only one pointer of a particular
1290 // structure.
1291 llvm::FoldingSetNodeID ID;
1292 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 void *InsertPos = 0;
1295 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1296 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 // If the pointee type isn't canonical, this won't be a canonical type either,
1299 // so fill in the canonical type field.
1300 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001301 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001302 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 // Get the new insert position for the node we care about.
1305 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001306 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 }
John McCall6b304a02009-09-24 23:30:46 +00001308 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001309 Types.push_back(New);
1310 ComplexTypes.InsertNode(New, InsertPos);
1311 return QualType(New, 0);
1312}
1313
Reid Spencer5f016e22007-07-11 17:01:13 +00001314/// getPointerType - Return the uniqued reference to the type for a pointer to
1315/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001316QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 // Unique pointers, to guarantee there is only one pointer of a particular
1318 // structure.
1319 llvm::FoldingSetNodeID ID;
1320 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 void *InsertPos = 0;
1323 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1324 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 // If the pointee type isn't canonical, this won't be a canonical type either,
1327 // so fill in the canonical type field.
1328 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001329 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001330 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Reid Spencer5f016e22007-07-11 17:01:13 +00001332 // Get the new insert position for the node we care about.
1333 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001334 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001335 }
John McCall6b304a02009-09-24 23:30:46 +00001336 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001337 Types.push_back(New);
1338 PointerTypes.InsertNode(New, InsertPos);
1339 return QualType(New, 0);
1340}
1341
Mike Stump1eb44332009-09-09 15:08:12 +00001342/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001343/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001344QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001345 assert(T->isFunctionType() && "block of function types only");
1346 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001347 // structure.
1348 llvm::FoldingSetNodeID ID;
1349 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001350
Steve Naroff5618bd42008-08-27 16:04:49 +00001351 void *InsertPos = 0;
1352 if (BlockPointerType *PT =
1353 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1354 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001355
1356 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001357 // type either so fill in the canonical type field.
1358 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001359 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001360 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Steve Naroff5618bd42008-08-27 16:04:49 +00001362 // Get the new insert position for the node we care about.
1363 BlockPointerType *NewIP =
1364 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001365 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001366 }
John McCall6b304a02009-09-24 23:30:46 +00001367 BlockPointerType *New
1368 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001369 Types.push_back(New);
1370 BlockPointerTypes.InsertNode(New, InsertPos);
1371 return QualType(New, 0);
1372}
1373
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001374/// getLValueReferenceType - Return the uniqued reference to the type for an
1375/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001376QualType
1377ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 // Unique pointers, to guarantee there is only one pointer of a particular
1379 // structure.
1380 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001381 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001382
1383 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001384 if (LValueReferenceType *RT =
1385 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001386 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001387
John McCall54e14c42009-10-22 22:37:11 +00001388 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1389
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 // If the referencee type isn't canonical, this won't be a canonical type
1391 // either, so fill in the canonical type field.
1392 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001393 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1394 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1395 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001396
Reid Spencer5f016e22007-07-11 17:01:13 +00001397 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001398 LValueReferenceType *NewIP =
1399 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001400 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001401 }
1402
John McCall6b304a02009-09-24 23:30:46 +00001403 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001404 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1405 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001407 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001408
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001409 return QualType(New, 0);
1410}
1411
1412/// getRValueReferenceType - Return the uniqued reference to the type for an
1413/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001414QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001415 // Unique pointers, to guarantee there is only one pointer of a particular
1416 // structure.
1417 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001418 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001419
1420 void *InsertPos = 0;
1421 if (RValueReferenceType *RT =
1422 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1423 return QualType(RT, 0);
1424
John McCall54e14c42009-10-22 22:37:11 +00001425 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1426
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001427 // If the referencee type isn't canonical, this won't be a canonical type
1428 // either, so fill in the canonical type field.
1429 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001430 if (InnerRef || !T.isCanonical()) {
1431 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1432 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001433
1434 // Get the new insert position for the node we care about.
1435 RValueReferenceType *NewIP =
1436 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001437 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001438 }
1439
John McCall6b304a02009-09-24 23:30:46 +00001440 RValueReferenceType *New
1441 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001442 Types.push_back(New);
1443 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 return QualType(New, 0);
1445}
1446
Sebastian Redlf30208a2009-01-24 21:16:55 +00001447/// getMemberPointerType - Return the uniqued reference to the type for a
1448/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001449QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001450 // Unique pointers, to guarantee there is only one pointer of a particular
1451 // structure.
1452 llvm::FoldingSetNodeID ID;
1453 MemberPointerType::Profile(ID, T, Cls);
1454
1455 void *InsertPos = 0;
1456 if (MemberPointerType *PT =
1457 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1458 return QualType(PT, 0);
1459
1460 // If the pointee or class type isn't canonical, this won't be a canonical
1461 // type either, so fill in the canonical type field.
1462 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001463 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001464 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1465
1466 // Get the new insert position for the node we care about.
1467 MemberPointerType *NewIP =
1468 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001469 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001470 }
John McCall6b304a02009-09-24 23:30:46 +00001471 MemberPointerType *New
1472 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001473 Types.push_back(New);
1474 MemberPointerTypes.InsertNode(New, InsertPos);
1475 return QualType(New, 0);
1476}
1477
Mike Stump1eb44332009-09-09 15:08:12 +00001478/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001479/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001480QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001481 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001482 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001483 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001484 assert((EltTy->isDependentType() ||
1485 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001486 "Constant array of VLAs is illegal!");
1487
Chris Lattner38aeec72009-05-13 04:12:56 +00001488 // Convert the array size into a canonical width matching the pointer size for
1489 // the target.
1490 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001491 ArySize =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001492 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001495 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001498 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001499 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001501
John McCall3b657512011-01-19 10:06:00 +00001502 // If the element type isn't canonical or has qualifiers, this won't
1503 // be a canonical type either, so fill in the canonical type field.
1504 QualType Canon;
1505 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1506 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1507 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001508 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001509 Canon = getQualifiedType(Canon, canonSplit.second);
1510
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001512 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001513 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001514 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 }
Mike Stump1eb44332009-09-09 15:08:12 +00001516
John McCall6b304a02009-09-24 23:30:46 +00001517 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001518 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001519 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 Types.push_back(New);
1521 return QualType(New, 0);
1522}
1523
John McCallce889032011-01-18 08:40:38 +00001524/// getVariableArrayDecayedType - Turns the given type, which may be
1525/// variably-modified, into the corresponding type with all the known
1526/// sizes replaced with [*].
1527QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1528 // Vastly most common case.
1529 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001530
John McCallce889032011-01-18 08:40:38 +00001531 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001532
John McCallce889032011-01-18 08:40:38 +00001533 SplitQualType split = type.getSplitDesugaredType();
1534 const Type *ty = split.first;
1535 switch (ty->getTypeClass()) {
1536#define TYPE(Class, Base)
1537#define ABSTRACT_TYPE(Class, Base)
1538#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1539#include "clang/AST/TypeNodes.def"
1540 llvm_unreachable("didn't desugar past all non-canonical types?");
1541
1542 // These types should never be variably-modified.
1543 case Type::Builtin:
1544 case Type::Complex:
1545 case Type::Vector:
1546 case Type::ExtVector:
1547 case Type::DependentSizedExtVector:
1548 case Type::ObjCObject:
1549 case Type::ObjCInterface:
1550 case Type::ObjCObjectPointer:
1551 case Type::Record:
1552 case Type::Enum:
1553 case Type::UnresolvedUsing:
1554 case Type::TypeOfExpr:
1555 case Type::TypeOf:
1556 case Type::Decltype:
1557 case Type::DependentName:
1558 case Type::InjectedClassName:
1559 case Type::TemplateSpecialization:
1560 case Type::DependentTemplateSpecialization:
1561 case Type::TemplateTypeParm:
1562 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001563 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001564 case Type::PackExpansion:
1565 llvm_unreachable("type should never be variably-modified");
1566
1567 // These types can be variably-modified but should never need to
1568 // further decay.
1569 case Type::FunctionNoProto:
1570 case Type::FunctionProto:
1571 case Type::BlockPointer:
1572 case Type::MemberPointer:
1573 return type;
1574
1575 // These types can be variably-modified. All these modifications
1576 // preserve structure except as noted by comments.
1577 // TODO: if we ever care about optimizing VLAs, there are no-op
1578 // optimizations available here.
1579 case Type::Pointer:
1580 result = getPointerType(getVariableArrayDecayedType(
1581 cast<PointerType>(ty)->getPointeeType()));
1582 break;
1583
1584 case Type::LValueReference: {
1585 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1586 result = getLValueReferenceType(
1587 getVariableArrayDecayedType(lv->getPointeeType()),
1588 lv->isSpelledAsLValue());
1589 break;
1590 }
1591
1592 case Type::RValueReference: {
1593 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1594 result = getRValueReferenceType(
1595 getVariableArrayDecayedType(lv->getPointeeType()));
1596 break;
1597 }
1598
1599 case Type::ConstantArray: {
1600 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1601 result = getConstantArrayType(
1602 getVariableArrayDecayedType(cat->getElementType()),
1603 cat->getSize(),
1604 cat->getSizeModifier(),
1605 cat->getIndexTypeCVRQualifiers());
1606 break;
1607 }
1608
1609 case Type::DependentSizedArray: {
1610 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1611 result = getDependentSizedArrayType(
1612 getVariableArrayDecayedType(dat->getElementType()),
1613 dat->getSizeExpr(),
1614 dat->getSizeModifier(),
1615 dat->getIndexTypeCVRQualifiers(),
1616 dat->getBracketsRange());
1617 break;
1618 }
1619
1620 // Turn incomplete types into [*] types.
1621 case Type::IncompleteArray: {
1622 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1623 result = getVariableArrayType(
1624 getVariableArrayDecayedType(iat->getElementType()),
1625 /*size*/ 0,
1626 ArrayType::Normal,
1627 iat->getIndexTypeCVRQualifiers(),
1628 SourceRange());
1629 break;
1630 }
1631
1632 // Turn VLA types into [*] types.
1633 case Type::VariableArray: {
1634 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1635 result = getVariableArrayType(
1636 getVariableArrayDecayedType(vat->getElementType()),
1637 /*size*/ 0,
1638 ArrayType::Star,
1639 vat->getIndexTypeCVRQualifiers(),
1640 vat->getBracketsRange());
1641 break;
1642 }
1643 }
1644
1645 // Apply the top-level qualifiers from the original.
1646 return getQualifiedType(result, split.second);
1647}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001648
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001649/// getVariableArrayType - Returns a non-unique reference to the type for a
1650/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001651QualType ASTContext::getVariableArrayType(QualType EltTy,
1652 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001653 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001654 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001655 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001656 // Since we don't unique expressions, it isn't possible to unique VLA's
1657 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001658 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001659
John McCall3b657512011-01-19 10:06:00 +00001660 // Be sure to pull qualifiers off the element type.
1661 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1662 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1663 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001664 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001665 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001666 }
1667
John McCall6b304a02009-09-24 23:30:46 +00001668 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001669 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001670
1671 VariableArrayTypes.push_back(New);
1672 Types.push_back(New);
1673 return QualType(New, 0);
1674}
1675
Douglas Gregor898574e2008-12-05 23:32:09 +00001676/// getDependentSizedArrayType - Returns a non-unique reference to
1677/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001678/// type.
John McCall3b657512011-01-19 10:06:00 +00001679QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1680 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001681 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001682 unsigned elementTypeQuals,
1683 SourceRange brackets) const {
1684 assert((!numElements || numElements->isTypeDependent() ||
1685 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001686 "Size must be type- or value-dependent!");
1687
John McCall3b657512011-01-19 10:06:00 +00001688 // Dependently-sized array types that do not have a specified number
1689 // of elements will have their sizes deduced from a dependent
1690 // initializer. We do no canonicalization here at all, which is okay
1691 // because they can't be used in most locations.
1692 if (!numElements) {
1693 DependentSizedArrayType *newType
1694 = new (*this, TypeAlignment)
1695 DependentSizedArrayType(*this, elementType, QualType(),
1696 numElements, ASM, elementTypeQuals,
1697 brackets);
1698 Types.push_back(newType);
1699 return QualType(newType, 0);
1700 }
1701
1702 // Otherwise, we actually build a new type every time, but we
1703 // also build a canonical type.
1704
1705 SplitQualType canonElementType = getCanonicalType(elementType).split();
1706
1707 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001708 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001709 DependentSizedArrayType::Profile(ID, *this,
1710 QualType(canonElementType.first, 0),
1711 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001712
John McCall3b657512011-01-19 10:06:00 +00001713 // Look for an existing type with these properties.
1714 DependentSizedArrayType *canonTy =
1715 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001716
John McCall3b657512011-01-19 10:06:00 +00001717 // If we don't have one, build one.
1718 if (!canonTy) {
1719 canonTy = new (*this, TypeAlignment)
1720 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1721 QualType(), numElements, ASM, elementTypeQuals,
1722 brackets);
1723 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1724 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001725 }
1726
John McCall3b657512011-01-19 10:06:00 +00001727 // Apply qualifiers from the element type to the array.
1728 QualType canon = getQualifiedType(QualType(canonTy,0),
1729 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001730
John McCall3b657512011-01-19 10:06:00 +00001731 // If we didn't need extra canonicalization for the element type,
1732 // then just use that as our result.
1733 if (QualType(canonElementType.first, 0) == elementType)
1734 return canon;
1735
1736 // Otherwise, we need to build a type which follows the spelling
1737 // of the element type.
1738 DependentSizedArrayType *sugaredType
1739 = new (*this, TypeAlignment)
1740 DependentSizedArrayType(*this, elementType, canon, numElements,
1741 ASM, elementTypeQuals, brackets);
1742 Types.push_back(sugaredType);
1743 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001744}
1745
John McCall3b657512011-01-19 10:06:00 +00001746QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001747 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001748 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001749 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001750 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001751
John McCall3b657512011-01-19 10:06:00 +00001752 void *insertPos = 0;
1753 if (IncompleteArrayType *iat =
1754 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1755 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001756
1757 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001758 // either, so fill in the canonical type field. We also have to pull
1759 // qualifiers off the element type.
1760 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001761
John McCall3b657512011-01-19 10:06:00 +00001762 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1763 SplitQualType canonSplit = getCanonicalType(elementType).split();
1764 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1765 ASM, elementTypeQuals);
1766 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001767
1768 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001769 IncompleteArrayType *existing =
1770 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1771 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001772 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001773
John McCall3b657512011-01-19 10:06:00 +00001774 IncompleteArrayType *newType = new (*this, TypeAlignment)
1775 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001776
John McCall3b657512011-01-19 10:06:00 +00001777 IncompleteArrayTypes.InsertNode(newType, insertPos);
1778 Types.push_back(newType);
1779 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001780}
1781
Steve Naroff73322922007-07-18 18:00:27 +00001782/// getVectorType - Return the unique reference to a vector type of
1783/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001784QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001785 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001786 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Reid Spencer5f016e22007-07-11 17:01:13 +00001788 // Check if we've already instantiated a vector of this type.
1789 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001790 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001791
Reid Spencer5f016e22007-07-11 17:01:13 +00001792 void *InsertPos = 0;
1793 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1794 return QualType(VTP, 0);
1795
1796 // If the element type isn't canonical, this won't be a canonical type either,
1797 // so fill in the canonical type field.
1798 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001799 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001800 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 // Get the new insert position for the node we care about.
1803 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001804 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001805 }
John McCall6b304a02009-09-24 23:30:46 +00001806 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001807 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001808 VectorTypes.InsertNode(New, InsertPos);
1809 Types.push_back(New);
1810 return QualType(New, 0);
1811}
1812
Nate Begeman213541a2008-04-18 23:10:10 +00001813/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001814/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001815QualType
1816ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall3b657512011-01-19 10:06:00 +00001817 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Steve Naroff73322922007-07-18 18:00:27 +00001819 // Check if we've already instantiated a vector of this type.
1820 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001821 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001822 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001823 void *InsertPos = 0;
1824 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1825 return QualType(VTP, 0);
1826
1827 // If the element type isn't canonical, this won't be a canonical type either,
1828 // so fill in the canonical type field.
1829 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001830 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001831 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Steve Naroff73322922007-07-18 18:00:27 +00001833 // Get the new insert position for the node we care about.
1834 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001835 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001836 }
John McCall6b304a02009-09-24 23:30:46 +00001837 ExtVectorType *New = new (*this, TypeAlignment)
1838 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001839 VectorTypes.InsertNode(New, InsertPos);
1840 Types.push_back(New);
1841 return QualType(New, 0);
1842}
1843
Jay Foad4ba2a172011-01-12 09:06:06 +00001844QualType
1845ASTContext::getDependentSizedExtVectorType(QualType vecType,
1846 Expr *SizeExpr,
1847 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001848 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001849 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001850 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001852 void *InsertPos = 0;
1853 DependentSizedExtVectorType *Canon
1854 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1855 DependentSizedExtVectorType *New;
1856 if (Canon) {
1857 // We already have a canonical version of this array type; use it as
1858 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001859 New = new (*this, TypeAlignment)
1860 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1861 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001862 } else {
1863 QualType CanonVecTy = getCanonicalType(vecType);
1864 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001865 New = new (*this, TypeAlignment)
1866 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1867 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001868
1869 DependentSizedExtVectorType *CanonCheck
1870 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1871 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1872 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001873 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1874 } else {
1875 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1876 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001877 New = new (*this, TypeAlignment)
1878 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001879 }
1880 }
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001882 Types.push_back(New);
1883 return QualType(New, 0);
1884}
1885
Douglas Gregor72564e72009-02-26 23:50:07 +00001886/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001887///
Jay Foad4ba2a172011-01-12 09:06:06 +00001888QualType
1889ASTContext::getFunctionNoProtoType(QualType ResultTy,
1890 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00001891 const CallingConv DefaultCC = Info.getCC();
1892 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1893 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00001894 // Unique functions, to guarantee there is only one function of a particular
1895 // structure.
1896 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001897 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001900 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001901 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001902 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001905 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001906 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001907 Canonical =
1908 getFunctionNoProtoType(getCanonicalType(ResultTy),
1909 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Reid Spencer5f016e22007-07-11 17:01:13 +00001911 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001912 FunctionNoProtoType *NewIP =
1913 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001914 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 }
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Roman Divackycfe9af22011-03-01 17:40:53 +00001917 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00001918 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00001919 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00001920 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001921 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001922 return QualType(New, 0);
1923}
1924
1925/// getFunctionType - Return a normal function type with a typed argument
1926/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00001927QualType
1928ASTContext::getFunctionType(QualType ResultTy,
1929 const QualType *ArgArray, unsigned NumArgs,
1930 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001931 // Unique functions, to guarantee there is only one function of a particular
1932 // structure.
1933 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001934 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00001935
1936 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001937 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001938 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001939 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001940
1941 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00001942 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001944 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001945 isCanonical = false;
1946
Roman Divackycfe9af22011-03-01 17:40:53 +00001947 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
1948 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1949 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00001950
Reid Spencer5f016e22007-07-11 17:01:13 +00001951 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001952 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001953 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001954 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 llvm::SmallVector<QualType, 16> CanonicalArgs;
1956 CanonicalArgs.reserve(NumArgs);
1957 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001958 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001959
John McCalle23cf432010-12-14 08:05:40 +00001960 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00001961 CanonicalEPI.ExceptionSpecType = EST_None;
1962 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00001963 CanonicalEPI.ExtInfo
1964 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1965
Chris Lattnerf52ab252008-04-06 22:59:24 +00001966 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001967 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00001968 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00001969
Reid Spencer5f016e22007-07-11 17:01:13 +00001970 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001971 FunctionProtoType *NewIP =
1972 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001973 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001974 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001975
Douglas Gregor72564e72009-02-26 23:50:07 +00001976 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001977 // for two variable size arrays (for parameter and exception types) at the
Sebastian Redl60618fa2011-03-12 11:50:43 +00001978 // end of them. Instead of the exception types, there could be a noexcept
1979 // expression and a context pointer.
John McCalle23cf432010-12-14 08:05:40 +00001980 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00001981 NumArgs * sizeof(QualType);
1982 if (EPI.ExceptionSpecType == EST_Dynamic)
1983 Size += EPI.NumExceptions * sizeof(QualType);
1984 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001985 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00001986 }
John McCalle23cf432010-12-14 08:05:40 +00001987 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00001988 FunctionProtoType::ExtProtoInfo newEPI = EPI;
1989 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001990 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00001991 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001992 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001993 return QualType(FTP, 0);
1994}
1995
John McCall3cb0ebd2010-03-10 03:28:59 +00001996#ifndef NDEBUG
1997static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1998 if (!isa<CXXRecordDecl>(D)) return false;
1999 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2000 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2001 return true;
2002 if (RD->getDescribedClassTemplate() &&
2003 !isa<ClassTemplateSpecializationDecl>(RD))
2004 return true;
2005 return false;
2006}
2007#endif
2008
2009/// getInjectedClassNameType - Return the unique reference to the
2010/// injected class name type for the specified templated declaration.
2011QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002012 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002013 assert(NeedsInjectedClassNameType(Decl));
2014 if (Decl->TypeForDecl) {
2015 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00002016 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002017 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2018 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2019 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2020 } else {
John McCallf4c73712011-01-19 06:33:43 +00002021 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002022 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002023 Decl->TypeForDecl = newType;
2024 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002025 }
2026 return QualType(Decl->TypeForDecl, 0);
2027}
2028
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002029/// getTypeDeclType - Return the unique reference to the type for the
2030/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002031QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002032 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002033 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Richard Smith162e1c12011-04-15 14:24:37 +00002035 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002036 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002037
John McCallbecb8d52010-03-10 06:48:02 +00002038 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2039 "Template type parameter types are always available.");
2040
John McCall19c85762010-02-16 03:57:14 +00002041 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002042 assert(!Record->getPreviousDeclaration() &&
2043 "struct/union has previous declaration");
2044 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002045 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002046 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002047 assert(!Enum->getPreviousDeclaration() &&
2048 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002049 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002050 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002051 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002052 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2053 Decl->TypeForDecl = newType;
2054 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002055 } else
John McCallbecb8d52010-03-10 06:48:02 +00002056 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002057
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002058 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002059}
2060
Reid Spencer5f016e22007-07-11 17:01:13 +00002061/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002062/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002063QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002064ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2065 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002067
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002068 if (Canonical.isNull())
2069 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002070 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002071 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002072 Decl->TypeForDecl = newType;
2073 Types.push_back(newType);
2074 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002075}
2076
Jay Foad4ba2a172011-01-12 09:06:06 +00002077QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002078 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2079
2080 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2081 if (PrevDecl->TypeForDecl)
2082 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2083
John McCallf4c73712011-01-19 06:33:43 +00002084 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2085 Decl->TypeForDecl = newType;
2086 Types.push_back(newType);
2087 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002088}
2089
Jay Foad4ba2a172011-01-12 09:06:06 +00002090QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002091 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2092
2093 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2094 if (PrevDecl->TypeForDecl)
2095 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2096
John McCallf4c73712011-01-19 06:33:43 +00002097 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2098 Decl->TypeForDecl = newType;
2099 Types.push_back(newType);
2100 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002101}
2102
John McCall9d156a72011-01-06 01:58:22 +00002103QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2104 QualType modifiedType,
2105 QualType equivalentType) {
2106 llvm::FoldingSetNodeID id;
2107 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2108
2109 void *insertPos = 0;
2110 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2111 if (type) return QualType(type, 0);
2112
2113 QualType canon = getCanonicalType(equivalentType);
2114 type = new (*this, TypeAlignment)
2115 AttributedType(canon, attrKind, modifiedType, equivalentType);
2116
2117 Types.push_back(type);
2118 AttributedTypes.InsertNode(type, insertPos);
2119
2120 return QualType(type, 0);
2121}
2122
2123
John McCall49a832b2009-10-18 09:09:24 +00002124/// \brief Retrieve a substitution-result type.
2125QualType
2126ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002127 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002128 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002129 && "replacement types must always be canonical");
2130
2131 llvm::FoldingSetNodeID ID;
2132 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2133 void *InsertPos = 0;
2134 SubstTemplateTypeParmType *SubstParm
2135 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2136
2137 if (!SubstParm) {
2138 SubstParm = new (*this, TypeAlignment)
2139 SubstTemplateTypeParmType(Parm, Replacement);
2140 Types.push_back(SubstParm);
2141 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2142 }
2143
2144 return QualType(SubstParm, 0);
2145}
2146
Douglas Gregorc3069d62011-01-14 02:55:32 +00002147/// \brief Retrieve a
2148QualType ASTContext::getSubstTemplateTypeParmPackType(
2149 const TemplateTypeParmType *Parm,
2150 const TemplateArgument &ArgPack) {
2151#ifndef NDEBUG
2152 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2153 PEnd = ArgPack.pack_end();
2154 P != PEnd; ++P) {
2155 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2156 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2157 }
2158#endif
2159
2160 llvm::FoldingSetNodeID ID;
2161 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2162 void *InsertPos = 0;
2163 if (SubstTemplateTypeParmPackType *SubstParm
2164 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2165 return QualType(SubstParm, 0);
2166
2167 QualType Canon;
2168 if (!Parm->isCanonicalUnqualified()) {
2169 Canon = getCanonicalType(QualType(Parm, 0));
2170 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2171 ArgPack);
2172 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2173 }
2174
2175 SubstTemplateTypeParmPackType *SubstParm
2176 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2177 ArgPack);
2178 Types.push_back(SubstParm);
2179 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2180 return QualType(SubstParm, 0);
2181}
2182
Douglas Gregorfab9d672009-02-05 23:33:38 +00002183/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002184/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002185/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002186QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002187 bool ParameterPack,
Jay Foad4ba2a172011-01-12 09:06:06 +00002188 IdentifierInfo *Name) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002189 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00002190 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002191 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002192 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002193 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2194
2195 if (TypeParm)
2196 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002197
Douglas Gregorefed5c82010-06-16 15:23:05 +00002198 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002199 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00002200 TypeParm = new (*this, TypeAlignment)
2201 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002202
2203 TemplateTypeParmType *TypeCheck
2204 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2205 assert(!TypeCheck && "Template type parameter canonical type broken");
2206 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002207 } else
John McCall6b304a02009-09-24 23:30:46 +00002208 TypeParm = new (*this, TypeAlignment)
2209 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002210
2211 Types.push_back(TypeParm);
2212 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2213
2214 return QualType(TypeParm, 0);
2215}
2216
John McCall3cb0ebd2010-03-10 03:28:59 +00002217TypeSourceInfo *
2218ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2219 SourceLocation NameLoc,
2220 const TemplateArgumentListInfo &Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002221 QualType CanonType) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002222 assert(!Name.getAsDependentTemplateName() &&
2223 "No dependent template names here!");
John McCall3cb0ebd2010-03-10 03:28:59 +00002224 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2225
2226 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2227 TemplateSpecializationTypeLoc TL
2228 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2229 TL.setTemplateNameLoc(NameLoc);
2230 TL.setLAngleLoc(Args.getLAngleLoc());
2231 TL.setRAngleLoc(Args.getRAngleLoc());
2232 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2233 TL.setArgLocInfo(i, Args[i].getLocInfo());
2234 return DI;
2235}
2236
Mike Stump1eb44332009-09-09 15:08:12 +00002237QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002238ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002239 const TemplateArgumentListInfo &Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002240 QualType Canon) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002241 assert(!Template.getAsDependentTemplateName() &&
2242 "No dependent template names here!");
2243
John McCalld5532b62009-11-23 01:53:49 +00002244 unsigned NumArgs = Args.size();
2245
John McCall833ca992009-10-29 08:12:44 +00002246 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2247 ArgVec.reserve(NumArgs);
2248 for (unsigned i = 0; i != NumArgs; ++i)
2249 ArgVec.push_back(Args[i].getArgument());
2250
John McCall31f17ec2010-04-27 00:57:59 +00002251 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00002252 Canon);
John McCall833ca992009-10-29 08:12:44 +00002253}
2254
2255QualType
2256ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002257 const TemplateArgument *Args,
2258 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002259 QualType Canon) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002260 assert(!Template.getAsDependentTemplateName() &&
2261 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002262 // Look through qualified template names.
2263 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2264 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002265
Douglas Gregorb88e8882009-07-30 17:40:51 +00002266 if (!Canon.isNull())
2267 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002268 else
2269 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00002270
Douglas Gregor1275ae02009-07-28 23:00:59 +00002271 // Allocate the (non-canonical) template specialization type, but don't
2272 // try to unique it: these types typically have location information that
2273 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00002274 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00002275 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00002276 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002277 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002278 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002279 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00002280 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00002281
Douglas Gregor55f6b142009-02-09 18:46:07 +00002282 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002283 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002284}
2285
Mike Stump1eb44332009-09-09 15:08:12 +00002286QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002287ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2288 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002289 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002290 assert(!Template.getAsDependentTemplateName() &&
2291 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002292 // Look through qualified template names.
2293 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2294 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002295
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002296 // Build the canonical template specialization type.
2297 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2298 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2299 CanonArgs.reserve(NumArgs);
2300 for (unsigned I = 0; I != NumArgs; ++I)
2301 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2302
2303 // Determine whether this canonical template specialization type already
2304 // exists.
2305 llvm::FoldingSetNodeID ID;
2306 TemplateSpecializationType::Profile(ID, CanonTemplate,
2307 CanonArgs.data(), NumArgs, *this);
2308
2309 void *InsertPos = 0;
2310 TemplateSpecializationType *Spec
2311 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2312
2313 if (!Spec) {
2314 // Allocate a new canonical template specialization type.
2315 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2316 sizeof(TemplateArgument) * NumArgs),
2317 TypeAlignment);
2318 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2319 CanonArgs.data(), NumArgs,
2320 QualType());
2321 Types.push_back(Spec);
2322 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2323 }
2324
2325 assert(Spec->isDependentType() &&
2326 "Non-dependent template-id type must have a canonical type");
2327 return QualType(Spec, 0);
2328}
2329
2330QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002331ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2332 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002333 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002334 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002335 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002336
2337 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002338 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002339 if (T)
2340 return QualType(T, 0);
2341
Douglas Gregor789b1f62010-02-04 18:10:26 +00002342 QualType Canon = NamedType;
2343 if (!Canon.isCanonical()) {
2344 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002345 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2346 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002347 (void)CheckT;
2348 }
2349
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002350 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002351 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002352 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002353 return QualType(T, 0);
2354}
2355
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002356QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002357ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002358 llvm::FoldingSetNodeID ID;
2359 ParenType::Profile(ID, InnerType);
2360
2361 void *InsertPos = 0;
2362 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2363 if (T)
2364 return QualType(T, 0);
2365
2366 QualType Canon = InnerType;
2367 if (!Canon.isCanonical()) {
2368 Canon = getCanonicalType(InnerType);
2369 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2370 assert(!CheckT && "Paren canonical type broken");
2371 (void)CheckT;
2372 }
2373
2374 T = new (*this) ParenType(InnerType, Canon);
2375 Types.push_back(T);
2376 ParenTypes.InsertNode(T, InsertPos);
2377 return QualType(T, 0);
2378}
2379
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002380QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2381 NestedNameSpecifier *NNS,
2382 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002383 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002384 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2385
2386 if (Canon.isNull()) {
2387 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002388 ElaboratedTypeKeyword CanonKeyword = Keyword;
2389 if (Keyword == ETK_None)
2390 CanonKeyword = ETK_Typename;
2391
2392 if (CanonNNS != NNS || CanonKeyword != Keyword)
2393 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002394 }
2395
2396 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002397 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002398
2399 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002400 DependentNameType *T
2401 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002402 if (T)
2403 return QualType(T, 0);
2404
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002405 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002406 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002407 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002408 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002409}
2410
Mike Stump1eb44332009-09-09 15:08:12 +00002411QualType
John McCall33500952010-06-11 00:33:02 +00002412ASTContext::getDependentTemplateSpecializationType(
2413 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002414 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002415 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002416 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002417 // TODO: avoid this copy
2418 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2419 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2420 ArgCopy.push_back(Args[I].getArgument());
2421 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2422 ArgCopy.size(),
2423 ArgCopy.data());
2424}
2425
2426QualType
2427ASTContext::getDependentTemplateSpecializationType(
2428 ElaboratedTypeKeyword Keyword,
2429 NestedNameSpecifier *NNS,
2430 const IdentifierInfo *Name,
2431 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002432 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002433 assert((!NNS || NNS->isDependent()) &&
2434 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002435
Douglas Gregor789b1f62010-02-04 18:10:26 +00002436 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002437 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2438 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002439
2440 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002441 DependentTemplateSpecializationType *T
2442 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002443 if (T)
2444 return QualType(T, 0);
2445
John McCall33500952010-06-11 00:33:02 +00002446 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002447
John McCall33500952010-06-11 00:33:02 +00002448 ElaboratedTypeKeyword CanonKeyword = Keyword;
2449 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2450
2451 bool AnyNonCanonArgs = false;
2452 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2453 for (unsigned I = 0; I != NumArgs; ++I) {
2454 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2455 if (!CanonArgs[I].structurallyEquals(Args[I]))
2456 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002457 }
2458
John McCall33500952010-06-11 00:33:02 +00002459 QualType Canon;
2460 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2461 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2462 Name, NumArgs,
2463 CanonArgs.data());
2464
2465 // Find the insert position again.
2466 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2467 }
2468
2469 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2470 sizeof(TemplateArgument) * NumArgs),
2471 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002472 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002473 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002474 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002475 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002476 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002477}
2478
Douglas Gregorcded4f62011-01-14 17:04:44 +00002479QualType ASTContext::getPackExpansionType(QualType Pattern,
2480 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002481 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002482 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002483
2484 assert(Pattern->containsUnexpandedParameterPack() &&
2485 "Pack expansions must expand one or more parameter packs");
2486 void *InsertPos = 0;
2487 PackExpansionType *T
2488 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2489 if (T)
2490 return QualType(T, 0);
2491
2492 QualType Canon;
2493 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002494 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002495
2496 // Find the insert position again.
2497 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2498 }
2499
Douglas Gregorcded4f62011-01-14 17:04:44 +00002500 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002501 Types.push_back(T);
2502 PackExpansionTypes.InsertNode(T, InsertPos);
2503 return QualType(T, 0);
2504}
2505
Chris Lattner88cb27a2008-04-07 04:56:42 +00002506/// CmpProtocolNames - Comparison predicate for sorting protocols
2507/// alphabetically.
2508static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2509 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002510 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002511}
2512
John McCallc12c5bb2010-05-15 11:32:37 +00002513static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002514 unsigned NumProtocols) {
2515 if (NumProtocols == 0) return true;
2516
2517 for (unsigned i = 1; i != NumProtocols; ++i)
2518 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2519 return false;
2520 return true;
2521}
2522
2523static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002524 unsigned &NumProtocols) {
2525 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002526
Chris Lattner88cb27a2008-04-07 04:56:42 +00002527 // Sort protocols, keyed by name.
2528 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2529
2530 // Remove duplicates.
2531 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2532 NumProtocols = ProtocolsEnd-Protocols;
2533}
2534
John McCallc12c5bb2010-05-15 11:32:37 +00002535QualType ASTContext::getObjCObjectType(QualType BaseType,
2536 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002537 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002538 // If the base type is an interface and there aren't any protocols
2539 // to add, then the interface type will do just fine.
2540 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2541 return BaseType;
2542
2543 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002544 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002545 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002546 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002547 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2548 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002549
John McCallc12c5bb2010-05-15 11:32:37 +00002550 // Build the canonical type, which has the canonical base type and
2551 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002552 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002553 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2554 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2555 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002556 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2557 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002558 unsigned UniqueCount = NumProtocols;
2559
John McCall54e14c42009-10-22 22:37:11 +00002560 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002561 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2562 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002563 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002564 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2565 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002566 }
2567
2568 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002569 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2570 }
2571
2572 unsigned Size = sizeof(ObjCObjectTypeImpl);
2573 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2574 void *Mem = Allocate(Size, TypeAlignment);
2575 ObjCObjectTypeImpl *T =
2576 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2577
2578 Types.push_back(T);
2579 ObjCObjectTypes.InsertNode(T, InsertPos);
2580 return QualType(T, 0);
2581}
2582
2583/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2584/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002585QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002586 llvm::FoldingSetNodeID ID;
2587 ObjCObjectPointerType::Profile(ID, ObjectT);
2588
2589 void *InsertPos = 0;
2590 if (ObjCObjectPointerType *QT =
2591 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2592 return QualType(QT, 0);
2593
2594 // Find the canonical object type.
2595 QualType Canonical;
2596 if (!ObjectT.isCanonical()) {
2597 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2598
2599 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002600 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2601 }
2602
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002603 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002604 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2605 ObjCObjectPointerType *QType =
2606 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002608 Types.push_back(QType);
2609 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002610 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002611}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002612
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002613/// getObjCInterfaceType - Return the unique reference to the type for the
2614/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002615QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002616 if (Decl->TypeForDecl)
2617 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002618
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002619 // FIXME: redeclarations?
2620 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2621 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2622 Decl->TypeForDecl = T;
2623 Types.push_back(T);
2624 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002625}
2626
Douglas Gregor72564e72009-02-26 23:50:07 +00002627/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2628/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002629/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002630/// DeclRefExpr's. 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::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002633 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002634 if (tofExpr->isTypeDependent()) {
2635 llvm::FoldingSetNodeID ID;
2636 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002637
Douglas Gregorb1975722009-07-30 23:18:24 +00002638 void *InsertPos = 0;
2639 DependentTypeOfExprType *Canon
2640 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2641 if (Canon) {
2642 // We already have a "canonical" version of an identical, dependent
2643 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002644 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002645 QualType((TypeOfExprType*)Canon, 0));
2646 }
2647 else {
2648 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002649 Canon
2650 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002651 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2652 toe = Canon;
2653 }
2654 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002655 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002656 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002657 }
Steve Naroff9752f252007-08-01 18:02:17 +00002658 Types.push_back(toe);
2659 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002660}
2661
Steve Naroff9752f252007-08-01 18:02:17 +00002662/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2663/// TypeOfType AST's. The only motivation to unique these nodes would be
2664/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002665/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002666/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002667QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002668 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002669 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002670 Types.push_back(tot);
2671 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002672}
2673
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002674/// getDecltypeForExpr - Given an expr, will return the decltype for that
2675/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002676static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002677 if (e->isTypeDependent())
2678 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002680 // If e is an id expression or a class member access, decltype(e) is defined
2681 // as the type of the entity named by e.
2682 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2683 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2684 return VD->getType();
2685 }
2686 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2687 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2688 return FD->getType();
2689 }
2690 // If e is a function call or an invocation of an overloaded operator,
2691 // (parentheses around e are ignored), decltype(e) is defined as the
2692 // return type of that function.
2693 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2694 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002696 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002697
2698 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002699 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002700 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002701 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002702
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002703 return T;
2704}
2705
Anders Carlsson395b4752009-06-24 19:06:50 +00002706/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2707/// DecltypeType AST's. The only motivation to unique these nodes would be
2708/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002709/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002710/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002711QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002712 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002713 if (e->isTypeDependent()) {
2714 llvm::FoldingSetNodeID ID;
2715 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002716
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002717 void *InsertPos = 0;
2718 DependentDecltypeType *Canon
2719 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2720 if (Canon) {
2721 // We already have a "canonical" version of an equivalent, dependent
2722 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002723 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002724 QualType((DecltypeType*)Canon, 0));
2725 }
2726 else {
2727 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002728 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002729 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2730 dt = Canon;
2731 }
2732 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002733 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002734 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002735 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002736 Types.push_back(dt);
2737 return QualType(dt, 0);
2738}
2739
Richard Smith483b9f32011-02-21 20:05:19 +00002740/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002741QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002742 void *InsertPos = 0;
2743 if (!DeducedType.isNull()) {
2744 // Look in the folding set for an existing type.
2745 llvm::FoldingSetNodeID ID;
2746 AutoType::Profile(ID, DeducedType);
2747 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2748 return QualType(AT, 0);
2749 }
2750
2751 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2752 Types.push_back(AT);
2753 if (InsertPos)
2754 AutoTypes.InsertNode(AT, InsertPos);
2755 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002756}
2757
Richard Smithad762fc2011-04-14 22:09:26 +00002758/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2759QualType ASTContext::getAutoDeductType() const {
2760 if (AutoDeductTy.isNull())
2761 AutoDeductTy = getAutoType(QualType());
2762 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2763 return AutoDeductTy;
2764}
2765
2766/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2767QualType ASTContext::getAutoRRefDeductType() const {
2768 if (AutoRRefDeductTy.isNull())
2769 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2770 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2771 return AutoRRefDeductTy;
2772}
2773
Reid Spencer5f016e22007-07-11 17:01:13 +00002774/// getTagDeclType - Return the unique reference to the type for the
2775/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00002776QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00002777 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002778 // FIXME: What is the design on getTagDeclType when it requires casting
2779 // away const? mutable?
2780 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002781}
2782
Mike Stump1eb44332009-09-09 15:08:12 +00002783/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2784/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2785/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002786CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002787 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002788}
2789
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002790/// getSignedWCharType - Return the type of "signed wchar_t".
2791/// Used when in C++, as a GCC extension.
2792QualType ASTContext::getSignedWCharType() const {
2793 // FIXME: derive from "Target" ?
2794 return WCharTy;
2795}
2796
2797/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2798/// Used when in C++, as a GCC extension.
2799QualType ASTContext::getUnsignedWCharType() const {
2800 // FIXME: derive from "Target" ?
2801 return UnsignedIntTy;
2802}
2803
Chris Lattner8b9023b2007-07-13 03:05:23 +00002804/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2805/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2806QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002807 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002808}
2809
Chris Lattnere6327742008-04-02 05:18:44 +00002810//===----------------------------------------------------------------------===//
2811// Type Operators
2812//===----------------------------------------------------------------------===//
2813
Jay Foad4ba2a172011-01-12 09:06:06 +00002814CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00002815 // Push qualifiers into arrays, and then discard any remaining
2816 // qualifiers.
2817 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002818 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002819 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002820 QualType Result;
2821 if (isa<ArrayType>(Ty)) {
2822 Result = getArrayDecayedType(QualType(Ty,0));
2823 } else if (isa<FunctionType>(Ty)) {
2824 Result = getPointerType(QualType(Ty, 0));
2825 } else {
2826 Result = QualType(Ty, 0);
2827 }
2828
2829 return CanQualType::CreateUnsafe(Result);
2830}
2831
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002832
John McCall62c28c82011-01-18 07:41:22 +00002833QualType ASTContext::getUnqualifiedArrayType(QualType type,
2834 Qualifiers &quals) {
2835 SplitQualType splitType = type.getSplitUnqualifiedType();
2836
2837 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2838 // the unqualified desugared type and then drops it on the floor.
2839 // We then have to strip that sugar back off with
2840 // getUnqualifiedDesugaredType(), which is silly.
2841 const ArrayType *AT =
2842 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2843
2844 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00002845 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00002846 quals = splitType.second;
2847 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002848 }
2849
John McCall62c28c82011-01-18 07:41:22 +00002850 // Otherwise, recurse on the array's element type.
2851 QualType elementType = AT->getElementType();
2852 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2853
2854 // If that didn't change the element type, AT has no qualifiers, so we
2855 // can just use the results in splitType.
2856 if (elementType == unqualElementType) {
2857 assert(quals.empty()); // from the recursive call
2858 quals = splitType.second;
2859 return QualType(splitType.first, 0);
2860 }
2861
2862 // Otherwise, add in the qualifiers from the outermost type, then
2863 // build the type back up.
2864 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002865
Douglas Gregor9dadd942010-05-17 18:45:21 +00002866 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002867 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002868 CAT->getSizeModifier(), 0);
2869 }
2870
Douglas Gregor9dadd942010-05-17 18:45:21 +00002871 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002872 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002873 }
2874
Douglas Gregor9dadd942010-05-17 18:45:21 +00002875 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002876 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00002877 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00002878 VAT->getSizeModifier(),
2879 VAT->getIndexTypeCVRQualifiers(),
2880 VAT->getBracketsRange());
2881 }
2882
2883 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00002884 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002885 DSAT->getSizeModifier(), 0,
2886 SourceRange());
2887}
2888
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002889/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2890/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2891/// they point to and return true. If T1 and T2 aren't pointer types
2892/// or pointer-to-member types, or if they are not similar at this
2893/// level, returns false and leaves T1 and T2 unchanged. Top-level
2894/// qualifiers on T1 and T2 are ignored. This function will typically
2895/// be called in a loop that successively "unwraps" pointer and
2896/// pointer-to-member types to compare them at each level.
2897bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2898 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2899 *T2PtrType = T2->getAs<PointerType>();
2900 if (T1PtrType && T2PtrType) {
2901 T1 = T1PtrType->getPointeeType();
2902 T2 = T2PtrType->getPointeeType();
2903 return true;
2904 }
2905
2906 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2907 *T2MPType = T2->getAs<MemberPointerType>();
2908 if (T1MPType && T2MPType &&
2909 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2910 QualType(T2MPType->getClass(), 0))) {
2911 T1 = T1MPType->getPointeeType();
2912 T2 = T2MPType->getPointeeType();
2913 return true;
2914 }
2915
2916 if (getLangOptions().ObjC1) {
2917 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2918 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2919 if (T1OPType && T2OPType) {
2920 T1 = T1OPType->getPointeeType();
2921 T2 = T2OPType->getPointeeType();
2922 return true;
2923 }
2924 }
2925
2926 // FIXME: Block pointers, too?
2927
2928 return false;
2929}
2930
Jay Foad4ba2a172011-01-12 09:06:06 +00002931DeclarationNameInfo
2932ASTContext::getNameForTemplate(TemplateName Name,
2933 SourceLocation NameLoc) const {
John McCall80ad16f2009-11-24 18:42:40 +00002934 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002935 // DNInfo work in progress: CHECKME: what about DNLoc?
2936 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2937
John McCall80ad16f2009-11-24 18:42:40 +00002938 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002939 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002940 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002941 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2942 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002943 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00002944 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2945 // DNInfo work in progress: FIXME: source locations?
2946 DeclarationNameLoc DNLoc;
2947 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2948 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2949 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002950 }
2951 }
2952
John McCall0bd6feb2009-12-02 08:04:21 +00002953 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2954 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002955 // DNInfo work in progress: CHECKME: what about DNLoc?
2956 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002957}
2958
Jay Foad4ba2a172011-01-12 09:06:06 +00002959TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002960 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2961 if (TemplateTemplateParmDecl *TTP
2962 = dyn_cast<TemplateTemplateParmDecl>(Template))
2963 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2964
2965 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002966 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002967 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002968
Douglas Gregor1aee05d2011-01-15 06:45:20 +00002969 if (SubstTemplateTemplateParmPackStorage *SubstPack
2970 = Name.getAsSubstTemplateTemplateParmPack()) {
2971 TemplateTemplateParmDecl *CanonParam
2972 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2973 TemplateArgument CanonArgPack
2974 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2975 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2976 }
2977
John McCall0bd6feb2009-12-02 08:04:21 +00002978 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002979
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002980 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2981 assert(DTN && "Non-dependent template names must refer to template decls.");
2982 return DTN->CanonicalTemplateName;
2983}
2984
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002985bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2986 X = getCanonicalTemplateName(X);
2987 Y = getCanonicalTemplateName(Y);
2988 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2989}
2990
Mike Stump1eb44332009-09-09 15:08:12 +00002991TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00002992ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00002993 switch (Arg.getKind()) {
2994 case TemplateArgument::Null:
2995 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002996
Douglas Gregor1275ae02009-07-28 23:00:59 +00002997 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002998 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002999
Douglas Gregor1275ae02009-07-28 23:00:59 +00003000 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003001 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Douglas Gregor788cd062009-11-11 01:00:40 +00003003 case TemplateArgument::Template:
3004 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003005
3006 case TemplateArgument::TemplateExpansion:
3007 return TemplateArgument(getCanonicalTemplateName(
3008 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003009 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003010
Douglas Gregor1275ae02009-07-28 23:00:59 +00003011 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003012 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003013 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003014
Douglas Gregor1275ae02009-07-28 23:00:59 +00003015 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003016 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003017
Douglas Gregor1275ae02009-07-28 23:00:59 +00003018 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003019 if (Arg.pack_size() == 0)
3020 return Arg;
3021
Douglas Gregor910f8002010-11-07 23:05:16 +00003022 TemplateArgument *CanonArgs
3023 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003024 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003025 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003026 AEnd = Arg.pack_end();
3027 A != AEnd; (void)++A, ++Idx)
3028 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003029
Douglas Gregor910f8002010-11-07 23:05:16 +00003030 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003031 }
3032 }
3033
3034 // Silence GCC warning
3035 assert(false && "Unhandled template argument kind");
3036 return TemplateArgument();
3037}
3038
Douglas Gregord57959a2009-03-27 23:10:48 +00003039NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003040ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003041 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003042 return 0;
3043
3044 switch (NNS->getKind()) {
3045 case NestedNameSpecifier::Identifier:
3046 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003047 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003048 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3049 NNS->getAsIdentifier());
3050
3051 case NestedNameSpecifier::Namespace:
3052 // A namespace is canonical; build a nested-name-specifier with
3053 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003054 return NestedNameSpecifier::Create(*this, 0,
3055 NNS->getAsNamespace()->getOriginalNamespace());
3056
3057 case NestedNameSpecifier::NamespaceAlias:
3058 // A namespace is canonical; build a nested-name-specifier with
3059 // this namespace and no prefix.
3060 return NestedNameSpecifier::Create(*this, 0,
3061 NNS->getAsNamespaceAlias()->getNamespace()
3062 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003063
3064 case NestedNameSpecifier::TypeSpec:
3065 case NestedNameSpecifier::TypeSpecWithTemplate: {
3066 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003067
3068 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3069 // break it apart into its prefix and identifier, then reconsititute those
3070 // as the canonical nested-name-specifier. This is required to canonicalize
3071 // a dependent nested-name-specifier involving typedefs of dependent-name
3072 // types, e.g.,
3073 // typedef typename T::type T1;
3074 // typedef typename T1::type T2;
3075 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3076 NestedNameSpecifier *Prefix
3077 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3078 return NestedNameSpecifier::Create(*this, Prefix,
3079 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3080 }
3081
Douglas Gregor643f8432010-11-04 00:14:23 +00003082 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003083 if (const DependentTemplateSpecializationType *DTST
3084 = T->getAs<DependentTemplateSpecializationType>()) {
3085 NestedNameSpecifier *Prefix
3086 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003087
3088 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3089 Prefix, DTST->getIdentifier(),
3090 DTST->getNumArgs(),
3091 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003092 T = getCanonicalType(T);
3093 }
3094
John McCall3b657512011-01-19 10:06:00 +00003095 return NestedNameSpecifier::Create(*this, 0, false,
3096 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003097 }
3098
3099 case NestedNameSpecifier::Global:
3100 // The global specifier is canonical and unique.
3101 return NNS;
3102 }
3103
3104 // Required to silence a GCC warning
3105 return 0;
3106}
3107
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003108
Jay Foad4ba2a172011-01-12 09:06:06 +00003109const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003110 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003111 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003112 // Handle the common positive case fast.
3113 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3114 return AT;
3115 }
Mike Stump1eb44332009-09-09 15:08:12 +00003116
John McCall0953e762009-09-24 19:53:00 +00003117 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003118 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003119 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003120
John McCall0953e762009-09-24 19:53:00 +00003121 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003122 // implements C99 6.7.3p8: "If the specification of an array type includes
3123 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003124
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003125 // If we get here, we either have type qualifiers on the type, or we have
3126 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003127 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003128
John McCall3b657512011-01-19 10:06:00 +00003129 SplitQualType split = T.getSplitDesugaredType();
3130 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003132 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003133 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3134 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003135 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003136
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003137 // Otherwise, we have an array and we have qualifiers on it. Push the
3138 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003139 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003140
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003141 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3142 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3143 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003144 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003145 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3146 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3147 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003148 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003149
Mike Stump1eb44332009-09-09 15:08:12 +00003150 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003151 = dyn_cast<DependentSizedArrayType>(ATy))
3152 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003153 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003154 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003155 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003156 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003157 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003158
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003159 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003160 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003161 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003162 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003163 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003164 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003165}
3166
Chris Lattnere6327742008-04-02 05:18:44 +00003167/// getArrayDecayedType - Return the properly qualified result of decaying the
3168/// specified array type to a pointer. This operation is non-trivial when
3169/// handling typedefs etc. The canonical type of "T" must be an array type,
3170/// this returns a pointer to a properly qualified element of the array.
3171///
3172/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003173QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003174 // Get the element type with 'getAsArrayType' so that we don't lose any
3175 // typedefs in the element type of the array. This also handles propagation
3176 // of type qualifiers from the array type into the element type if present
3177 // (C99 6.7.3p8).
3178 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3179 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003180
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003181 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003182
3183 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003184 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003185}
3186
John McCall3b657512011-01-19 10:06:00 +00003187QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3188 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003189}
3190
John McCall3b657512011-01-19 10:06:00 +00003191QualType ASTContext::getBaseElementType(QualType type) const {
3192 Qualifiers qs;
3193 while (true) {
3194 SplitQualType split = type.getSplitDesugaredType();
3195 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3196 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003197
John McCall3b657512011-01-19 10:06:00 +00003198 type = array->getElementType();
3199 qs.addConsistentQualifiers(split.second);
3200 }
Mike Stump1eb44332009-09-09 15:08:12 +00003201
John McCall3b657512011-01-19 10:06:00 +00003202 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003203}
3204
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003205/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003206uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003207ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3208 uint64_t ElementCount = 1;
3209 do {
3210 ElementCount *= CA->getSize().getZExtValue();
3211 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3212 } while (CA);
3213 return ElementCount;
3214}
3215
Reid Spencer5f016e22007-07-11 17:01:13 +00003216/// getFloatingRank - Return a relative rank for floating point types.
3217/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003218static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003219 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003220 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003221
John McCall183700f2009-09-21 23:43:11 +00003222 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3223 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00003224 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003225 case BuiltinType::Float: return FloatRank;
3226 case BuiltinType::Double: return DoubleRank;
3227 case BuiltinType::LongDouble: return LongDoubleRank;
3228 }
3229}
3230
Mike Stump1eb44332009-09-09 15:08:12 +00003231/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3232/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003233/// 'typeDomain' is a real floating point or complex type.
3234/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003235QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3236 QualType Domain) const {
3237 FloatingRank EltRank = getFloatingRank(Size);
3238 if (Domain->isComplexType()) {
3239 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00003240 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003241 case FloatRank: return FloatComplexTy;
3242 case DoubleRank: return DoubleComplexTy;
3243 case LongDoubleRank: return LongDoubleComplexTy;
3244 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003245 }
Chris Lattner1361b112008-04-06 23:58:54 +00003246
3247 assert(Domain->isRealFloatingType() && "Unknown domain!");
3248 switch (EltRank) {
3249 default: assert(0 && "getFloatingRank(): illegal value for rank");
3250 case FloatRank: return FloatTy;
3251 case DoubleRank: return DoubleTy;
3252 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003253 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003254}
3255
Chris Lattner7cfeb082008-04-06 23:55:33 +00003256/// getFloatingTypeOrder - Compare the rank of the two specified floating
3257/// point types, ignoring the domain of the type (i.e. 'double' ==
3258/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003259/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003260int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003261 FloatingRank LHSR = getFloatingRank(LHS);
3262 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003263
Chris Lattnera75cea32008-04-06 23:38:49 +00003264 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003265 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003266 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003267 return 1;
3268 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003269}
3270
Chris Lattnerf52ab252008-04-06 22:59:24 +00003271/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3272/// routine will assert if passed a built-in type that isn't an integer or enum,
3273/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003274unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003275 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCallf4c73712011-01-19 06:33:43 +00003276 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00003277 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00003278
Chris Lattner3f59c972010-12-25 23:25:43 +00003279 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3280 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmana3426752009-07-05 23:44:27 +00003281 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3282
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003283 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3284 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3285
3286 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3287 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3288
Chris Lattnerf52ab252008-04-06 22:59:24 +00003289 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00003290 default: assert(0 && "getIntegerRank(): not a built-in integer");
3291 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003292 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003293 case BuiltinType::Char_S:
3294 case BuiltinType::Char_U:
3295 case BuiltinType::SChar:
3296 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003297 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003298 case BuiltinType::Short:
3299 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003300 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003301 case BuiltinType::Int:
3302 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003303 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003304 case BuiltinType::Long:
3305 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003306 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003307 case BuiltinType::LongLong:
3308 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003309 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003310 case BuiltinType::Int128:
3311 case BuiltinType::UInt128:
3312 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003313 }
3314}
3315
Eli Friedman04e83572009-08-20 04:21:42 +00003316/// \brief Whether this is a promotable bitfield reference according
3317/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3318///
3319/// \returns the type this bit-field will promote to, or NULL if no
3320/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003321QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003322 if (E->isTypeDependent() || E->isValueDependent())
3323 return QualType();
3324
Eli Friedman04e83572009-08-20 04:21:42 +00003325 FieldDecl *Field = E->getBitField();
3326 if (!Field)
3327 return QualType();
3328
3329 QualType FT = Field->getType();
3330
3331 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3332 uint64_t BitWidth = BitWidthAP.getZExtValue();
3333 uint64_t IntSize = getTypeSize(IntTy);
3334 // GCC extension compatibility: if the bit-field size is less than or equal
3335 // to the size of int, it gets promoted no matter what its type is.
3336 // For instance, unsigned long bf : 4 gets promoted to signed int.
3337 if (BitWidth < IntSize)
3338 return IntTy;
3339
3340 if (BitWidth == IntSize)
3341 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3342
3343 // Types bigger than int are not subject to promotions, and therefore act
3344 // like the base type.
3345 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3346 // is ridiculous.
3347 return QualType();
3348}
3349
Eli Friedmana95d7572009-08-19 07:44:53 +00003350/// getPromotedIntegerType - Returns the type that Promotable will
3351/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3352/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003353QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003354 assert(!Promotable.isNull());
3355 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003356 if (const EnumType *ET = Promotable->getAs<EnumType>())
3357 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003358 if (Promotable->isSignedIntegerType())
3359 return IntTy;
3360 uint64_t PromotableSize = getTypeSize(Promotable);
3361 uint64_t IntSize = getTypeSize(IntTy);
3362 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3363 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3364}
3365
Mike Stump1eb44332009-09-09 15:08:12 +00003366/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003367/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003368/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003369int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003370 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3371 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003372 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003373
Chris Lattnerf52ab252008-04-06 22:59:24 +00003374 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3375 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003376
Chris Lattner7cfeb082008-04-06 23:55:33 +00003377 unsigned LHSRank = getIntegerRank(LHSC);
3378 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003379
Chris Lattner7cfeb082008-04-06 23:55:33 +00003380 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3381 if (LHSRank == RHSRank) return 0;
3382 return LHSRank > RHSRank ? 1 : -1;
3383 }
Mike Stump1eb44332009-09-09 15:08:12 +00003384
Chris Lattner7cfeb082008-04-06 23:55:33 +00003385 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3386 if (LHSUnsigned) {
3387 // If the unsigned [LHS] type is larger, return it.
3388 if (LHSRank >= RHSRank)
3389 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003390
Chris Lattner7cfeb082008-04-06 23:55:33 +00003391 // If the signed type can represent all values of the unsigned type, it
3392 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003393 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003394 return -1;
3395 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003396
Chris Lattner7cfeb082008-04-06 23:55:33 +00003397 // If the unsigned [RHS] type is larger, return it.
3398 if (RHSRank >= LHSRank)
3399 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003400
Chris Lattner7cfeb082008-04-06 23:55:33 +00003401 // If the signed type can represent all values of the unsigned type, it
3402 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003403 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003404 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003405}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003406
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003407static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003408CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3409 DeclContext *DC, IdentifierInfo *Id) {
3410 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003411 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003412 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003413 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003414 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003415}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003416
Mike Stump1eb44332009-09-09 15:08:12 +00003417// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003418QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003419 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003420 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003421 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003422 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003423 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003424
Anders Carlssonf06273f2007-11-19 00:25:30 +00003425 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003426
Anders Carlsson71993dd2007-08-17 05:31:46 +00003427 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003428 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003429 // int flags;
3430 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003431 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003432 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003433 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003434 FieldTypes[3] = LongTy;
3435
Anders Carlsson71993dd2007-08-17 05:31:46 +00003436 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003437 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003438 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003439 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003440 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003441 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003442 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003443 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003444 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003445 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003446 }
3447
Douglas Gregor838db382010-02-11 01:19:42 +00003448 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003449 }
Mike Stump1eb44332009-09-09 15:08:12 +00003450
Anders Carlsson71993dd2007-08-17 05:31:46 +00003451 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003452}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003453
Douglas Gregor319ac892009-04-23 22:29:11 +00003454void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003455 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003456 assert(Rec && "Invalid CFConstantStringType");
3457 CFConstantStringTypeDecl = Rec->getDecl();
3458}
3459
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003460// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003461QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003462 if (!NSConstantStringTypeDecl) {
3463 NSConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003464 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003465 &Idents.get("__builtin_NSString"));
3466 NSConstantStringTypeDecl->startDefinition();
3467
3468 QualType FieldTypes[3];
3469
3470 // const int *isa;
3471 FieldTypes[0] = getPointerType(IntTy.withConst());
3472 // const char *str;
3473 FieldTypes[1] = getPointerType(CharTy.withConst());
3474 // unsigned int length;
3475 FieldTypes[2] = UnsignedIntTy;
3476
3477 // Create fields
3478 for (unsigned i = 0; i < 3; ++i) {
3479 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003480 SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003481 SourceLocation(), 0,
3482 FieldTypes[i], /*TInfo=*/0,
3483 /*BitWidth=*/0,
3484 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003485 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003486 NSConstantStringTypeDecl->addDecl(Field);
3487 }
3488
3489 NSConstantStringTypeDecl->completeDefinition();
3490 }
3491
3492 return getTagDeclType(NSConstantStringTypeDecl);
3493}
3494
3495void ASTContext::setNSConstantStringType(QualType T) {
3496 const RecordType *Rec = T->getAs<RecordType>();
3497 assert(Rec && "Invalid NSConstantStringType");
3498 NSConstantStringTypeDecl = Rec->getDecl();
3499}
3500
Jay Foad4ba2a172011-01-12 09:06:06 +00003501QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003502 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003503 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003504 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003505 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003506 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003508 QualType FieldTypes[] = {
3509 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003510 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003511 getPointerType(UnsignedLongTy),
3512 getConstantArrayType(UnsignedLongTy,
3513 llvm::APInt(32, 5), ArrayType::Normal, 0)
3514 };
Mike Stump1eb44332009-09-09 15:08:12 +00003515
Douglas Gregor44b43212008-12-11 16:49:14 +00003516 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003517 FieldDecl *Field = FieldDecl::Create(*this,
3518 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003519 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003520 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003521 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003522 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003523 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003524 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003525 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003526 }
Mike Stump1eb44332009-09-09 15:08:12 +00003527
Douglas Gregor838db382010-02-11 01:19:42 +00003528 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003529 }
Mike Stump1eb44332009-09-09 15:08:12 +00003530
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003531 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3532}
3533
Jay Foad4ba2a172011-01-12 09:06:06 +00003534QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003535 if (BlockDescriptorType)
3536 return getTagDeclType(BlockDescriptorType);
3537
3538 RecordDecl *T;
3539 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003540 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003541 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003542 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003543
3544 QualType FieldTypes[] = {
3545 UnsignedLongTy,
3546 UnsignedLongTy,
3547 };
3548
3549 const char *FieldNames[] = {
3550 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003551 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003552 };
3553
3554 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003555 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003556 SourceLocation(),
3557 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003558 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003559 /*BitWidth=*/0,
3560 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003561 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003562 T->addDecl(Field);
3563 }
3564
Douglas Gregor838db382010-02-11 01:19:42 +00003565 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003566
3567 BlockDescriptorType = T;
3568
3569 return getTagDeclType(BlockDescriptorType);
3570}
3571
3572void ASTContext::setBlockDescriptorType(QualType T) {
3573 const RecordType *Rec = T->getAs<RecordType>();
3574 assert(Rec && "Invalid BlockDescriptorType");
3575 BlockDescriptorType = Rec->getDecl();
3576}
3577
Jay Foad4ba2a172011-01-12 09:06:06 +00003578QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003579 if (BlockDescriptorExtendedType)
3580 return getTagDeclType(BlockDescriptorExtendedType);
3581
3582 RecordDecl *T;
3583 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003584 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003585 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003586 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003587
3588 QualType FieldTypes[] = {
3589 UnsignedLongTy,
3590 UnsignedLongTy,
3591 getPointerType(VoidPtrTy),
3592 getPointerType(VoidPtrTy)
3593 };
3594
3595 const char *FieldNames[] = {
3596 "reserved",
3597 "Size",
3598 "CopyFuncPtr",
3599 "DestroyFuncPtr"
3600 };
3601
3602 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003603 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003604 SourceLocation(),
3605 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003606 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003607 /*BitWidth=*/0,
3608 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003609 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003610 T->addDecl(Field);
3611 }
3612
Douglas Gregor838db382010-02-11 01:19:42 +00003613 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003614
3615 BlockDescriptorExtendedType = T;
3616
3617 return getTagDeclType(BlockDescriptorExtendedType);
3618}
3619
3620void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3621 const RecordType *Rec = T->getAs<RecordType>();
3622 assert(Rec && "Invalid BlockDescriptorType");
3623 BlockDescriptorExtendedType = Rec->getDecl();
3624}
3625
Jay Foad4ba2a172011-01-12 09:06:06 +00003626bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003627 if (Ty->isBlockPointerType())
3628 return true;
3629 if (isObjCNSObjectType(Ty))
3630 return true;
3631 if (Ty->isObjCObjectPointerType())
3632 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003633 if (getLangOptions().CPlusPlus) {
3634 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3635 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3636 return RD->hasConstCopyConstructor(*this);
3637
3638 }
3639 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003640 return false;
3641}
3642
Jay Foad4ba2a172011-01-12 09:06:06 +00003643QualType
3644ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003645 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003646 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003647 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003648 // unsigned int __flags;
3649 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003650 // void *__copy_helper; // as needed
3651 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003652 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003653 // } *
3654
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003655 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3656
3657 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003658 llvm::SmallString<36> Name;
3659 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3660 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003661 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003662 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003663 T->startDefinition();
3664 QualType Int32Ty = IntTy;
3665 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3666 QualType FieldTypes[] = {
3667 getPointerType(VoidPtrTy),
3668 getPointerType(getTagDeclType(T)),
3669 Int32Ty,
3670 Int32Ty,
3671 getPointerType(VoidPtrTy),
3672 getPointerType(VoidPtrTy),
3673 Ty
3674 };
3675
Daniel Dunbar4087f272010-08-17 22:39:59 +00003676 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003677 "__isa",
3678 "__forwarding",
3679 "__flags",
3680 "__size",
3681 "__copy_helper",
3682 "__destroy_helper",
3683 DeclName,
3684 };
3685
3686 for (size_t i = 0; i < 7; ++i) {
3687 if (!HasCopyAndDispose && i >=4 && i <= 5)
3688 continue;
3689 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003690 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003691 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003692 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003693 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003694 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003695 T->addDecl(Field);
3696 }
3697
Douglas Gregor838db382010-02-11 01:19:42 +00003698 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003699
3700 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003701}
3702
Douglas Gregor319ac892009-04-23 22:29:11 +00003703void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003704 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003705 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3706 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3707}
3708
Anders Carlssone8c49532007-10-29 06:33:42 +00003709// This returns true if a type has been typedefed to BOOL:
3710// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003711static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003712 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003713 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3714 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003715
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003716 return false;
3717}
3718
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003719/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003720/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003721CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck199c3d62010-01-11 17:06:35 +00003722 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003723
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003724 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003725 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003726 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003727 // Treat arrays as pointers, since that's how they're passed in.
3728 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003729 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003730 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003731}
3732
3733static inline
3734std::string charUnitsToString(const CharUnits &CU) {
3735 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003736}
3737
John McCall6b5a61b2011-02-07 10:33:21 +00003738/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003739/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00003740std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3741 std::string S;
3742
David Chisnall5e530af2009-11-17 19:33:30 +00003743 const BlockDecl *Decl = Expr->getBlockDecl();
3744 QualType BlockTy =
3745 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3746 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003747 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003748 // Compute size of all parameters.
3749 // Start with computing size of a pointer in number of bytes.
3750 // FIXME: There might(should) be a better way of doing this computation!
3751 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003752 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3753 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003754 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003755 E = Decl->param_end(); PI != E; ++PI) {
3756 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003757 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003758 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003759 ParmOffset += sz;
3760 }
3761 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003762 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003763 // Block pointer and offset.
3764 S += "@?0";
3765 ParmOffset = PtrSize;
3766
3767 // Argument types.
3768 ParmOffset = PtrSize;
3769 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3770 Decl->param_end(); PI != E; ++PI) {
3771 ParmVarDecl *PVDecl = *PI;
3772 QualType PType = PVDecl->getOriginalType();
3773 if (const ArrayType *AT =
3774 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3775 // Use array's original type only if it has known number of
3776 // elements.
3777 if (!isa<ConstantArrayType>(AT))
3778 PType = PVDecl->getType();
3779 } else if (PType->isFunctionType())
3780 PType = PVDecl->getType();
3781 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003782 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003783 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003784 }
John McCall6b5a61b2011-02-07 10:33:21 +00003785
3786 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00003787}
3788
David Chisnall5389f482010-12-30 14:05:53 +00003789void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3790 std::string& S) {
3791 // Encode result type.
3792 getObjCEncodingForType(Decl->getResultType(), S);
3793 CharUnits ParmOffset;
3794 // Compute size of all parameters.
3795 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3796 E = Decl->param_end(); PI != E; ++PI) {
3797 QualType PType = (*PI)->getType();
3798 CharUnits sz = getObjCEncodingTypeSize(PType);
3799 assert (sz.isPositive() &&
3800 "getObjCEncodingForMethodDecl - Incomplete param type");
3801 ParmOffset += sz;
3802 }
3803 S += charUnitsToString(ParmOffset);
3804 ParmOffset = CharUnits::Zero();
3805
3806 // Argument types.
3807 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3808 E = Decl->param_end(); PI != E; ++PI) {
3809 ParmVarDecl *PVDecl = *PI;
3810 QualType PType = PVDecl->getOriginalType();
3811 if (const ArrayType *AT =
3812 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3813 // Use array's original type only if it has known number of
3814 // elements.
3815 if (!isa<ConstantArrayType>(AT))
3816 PType = PVDecl->getType();
3817 } else if (PType->isFunctionType())
3818 PType = PVDecl->getType();
3819 getObjCEncodingForType(PType, S);
3820 S += charUnitsToString(ParmOffset);
3821 ParmOffset += getObjCEncodingTypeSize(PType);
3822 }
3823}
3824
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003825/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003826/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003827void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00003828 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003829 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003830 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003831 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003832 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003833 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003834 // Compute size of all parameters.
3835 // Start with computing size of a pointer in number of bytes.
3836 // FIXME: There might(should) be a better way of doing this computation!
3837 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003838 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003839 // The first two arguments (self and _cmd) are pointers; account for
3840 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003841 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003842 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003843 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003844 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003845 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003846 assert (sz.isPositive() &&
3847 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003848 ParmOffset += sz;
3849 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003850 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003851 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003852 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003853
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003854 // Argument types.
3855 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003856 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003857 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003858 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003859 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003860 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003861 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3862 // Use array's original type only if it has known number of
3863 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003864 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003865 PType = PVDecl->getType();
3866 } else if (PType->isFunctionType())
3867 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003868 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003869 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003870 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003871 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003872 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003873 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003874 }
3875}
3876
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003877/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003878/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003879/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3880/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003881/// Property attributes are stored as a comma-delimited C string. The simple
3882/// attributes readonly and bycopy are encoded as single characters. The
3883/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3884/// encoded as single characters, followed by an identifier. Property types
3885/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003886/// these attributes are defined by the following enumeration:
3887/// @code
3888/// enum PropertyAttributes {
3889/// kPropertyReadOnly = 'R', // property is read-only.
3890/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3891/// kPropertyByref = '&', // property is a reference to the value last assigned
3892/// kPropertyDynamic = 'D', // property is dynamic
3893/// kPropertyGetter = 'G', // followed by getter selector name
3894/// kPropertySetter = 'S', // followed by setter selector name
3895/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3896/// kPropertyType = 't' // followed by old-style type encoding.
3897/// kPropertyWeak = 'W' // 'weak' property
3898/// kPropertyStrong = 'P' // property GC'able
3899/// kPropertyNonAtomic = 'N' // property non-atomic
3900/// };
3901/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003902void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003903 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00003904 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003905 // Collect information from the property implementation decl(s).
3906 bool Dynamic = false;
3907 ObjCPropertyImplDecl *SynthesizePID = 0;
3908
3909 // FIXME: Duplicated code due to poor abstraction.
3910 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003911 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003912 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3913 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003914 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003915 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003916 ObjCPropertyImplDecl *PID = *i;
3917 if (PID->getPropertyDecl() == PD) {
3918 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3919 Dynamic = true;
3920 } else {
3921 SynthesizePID = PID;
3922 }
3923 }
3924 }
3925 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003926 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003927 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003928 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003929 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003930 ObjCPropertyImplDecl *PID = *i;
3931 if (PID->getPropertyDecl() == PD) {
3932 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3933 Dynamic = true;
3934 } else {
3935 SynthesizePID = PID;
3936 }
3937 }
Mike Stump1eb44332009-09-09 15:08:12 +00003938 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003939 }
3940 }
3941
3942 // FIXME: This is not very efficient.
3943 S = "T";
3944
3945 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003946 // GCC has some special rules regarding encoding of properties which
3947 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003948 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003949 true /* outermost type */,
3950 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003951
3952 if (PD->isReadOnly()) {
3953 S += ",R";
3954 } else {
3955 switch (PD->getSetterKind()) {
3956 case ObjCPropertyDecl::Assign: break;
3957 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003958 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003959 }
3960 }
3961
3962 // It really isn't clear at all what this means, since properties
3963 // are "dynamic by default".
3964 if (Dynamic)
3965 S += ",D";
3966
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003967 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3968 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003969
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003970 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3971 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003972 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003973 }
3974
3975 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3976 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003977 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003978 }
3979
3980 if (SynthesizePID) {
3981 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3982 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003983 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003984 }
3985
3986 // FIXME: OBJCGC: weak & strong
3987}
3988
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003989/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003990/// Another legacy compatibility encoding: 32-bit longs are encoded as
3991/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003992/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3993///
3994void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003995 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003996 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00003997 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003998 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003999 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004000 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004001 PointeeTy = IntTy;
4002 }
4003 }
4004}
4005
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004006void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004007 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004008 // We follow the behavior of gcc, expanding structures which are
4009 // directly pointed to, and expanding embedded structures. Note that
4010 // these rules are sufficient to prevent recursive encoding of the
4011 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004012 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004013 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004014}
4015
David Chisnall64fd7e82010-06-04 01:10:52 +00004016static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4017 switch (T->getAs<BuiltinType>()->getKind()) {
4018 default: assert(0 && "Unhandled builtin type kind");
4019 case BuiltinType::Void: return 'v';
4020 case BuiltinType::Bool: return 'B';
4021 case BuiltinType::Char_U:
4022 case BuiltinType::UChar: return 'C';
4023 case BuiltinType::UShort: return 'S';
4024 case BuiltinType::UInt: return 'I';
4025 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004026 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004027 case BuiltinType::UInt128: return 'T';
4028 case BuiltinType::ULongLong: return 'Q';
4029 case BuiltinType::Char_S:
4030 case BuiltinType::SChar: return 'c';
4031 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004032 case BuiltinType::WChar_S:
4033 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004034 case BuiltinType::Int: return 'i';
4035 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004036 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004037 case BuiltinType::LongLong: return 'q';
4038 case BuiltinType::Int128: return 't';
4039 case BuiltinType::Float: return 'f';
4040 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004041 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004042 }
4043}
4044
Jay Foad4ba2a172011-01-12 09:06:06 +00004045static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004046 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004047 const Expr *E = FD->getBitWidth();
4048 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004049 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004050 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4051 // The GNU runtime requires more information; bitfields are encoded as b,
4052 // then the offset (in bits) of the first element, then the type of the
4053 // bitfield, then the size in bits. For example, in this structure:
4054 //
4055 // struct
4056 // {
4057 // int integer;
4058 // int flags:2;
4059 // };
4060 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4061 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4062 // information is not especially sensible, but we're stuck with it for
4063 // compatibility with GCC, although providing it breaks anything that
4064 // actually uses runtime introspection and wants to work on both runtimes...
4065 if (!Ctx->getLangOptions().NeXTRuntime) {
4066 const RecordDecl *RD = FD->getParent();
4067 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4068 // FIXME: This same linear search is also used in ExprConstant - it might
4069 // be better if the FieldDecl stored its offset. We'd be increasing the
4070 // size of the object slightly, but saving some time every time it is used.
4071 unsigned i = 0;
4072 for (RecordDecl::field_iterator Field = RD->field_begin(),
4073 FieldEnd = RD->field_end();
4074 Field != FieldEnd; (void)++Field, ++i) {
4075 if (*Field == FD)
4076 break;
4077 }
4078 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnallc7ff82c2010-12-26 20:12:30 +00004079 if (T->isEnumeralType())
4080 S += 'i';
4081 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004082 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004083 }
4084 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004085 S += llvm::utostr(N);
4086}
4087
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004088// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004089void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4090 bool ExpandPointedToStructures,
4091 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004092 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004093 bool OutermostType,
Jay Foad4ba2a172011-01-12 09:06:06 +00004094 bool EncodingProperty) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004095 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004096 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004097 return EncodeBitField(this, S, T, FD);
4098 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004099 return;
4100 }
Mike Stump1eb44332009-09-09 15:08:12 +00004101
John McCall183700f2009-09-21 23:43:11 +00004102 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004103 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004104 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004105 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004106 return;
4107 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004108
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004109 // encoding for pointer or r3eference types.
4110 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004111 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004112 if (PT->isObjCSelType()) {
4113 S += ':';
4114 return;
4115 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004116 PointeeTy = PT->getPointeeType();
4117 }
4118 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4119 PointeeTy = RT->getPointeeType();
4120 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004121 bool isReadOnly = false;
4122 // For historical/compatibility reasons, the read-only qualifier of the
4123 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4124 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004125 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004126 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004127 if (OutermostType && T.isConstQualified()) {
4128 isReadOnly = true;
4129 S += 'r';
4130 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004131 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004132 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004133 while (P->getAs<PointerType>())
4134 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004135 if (P.isConstQualified()) {
4136 isReadOnly = true;
4137 S += 'r';
4138 }
4139 }
4140 if (isReadOnly) {
4141 // Another legacy compatibility encoding. Some ObjC qualifier and type
4142 // combinations need to be rearranged.
4143 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00004144 if (llvm::StringRef(S).endswith("nr"))
4145 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004146 }
Mike Stump1eb44332009-09-09 15:08:12 +00004147
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004148 if (PointeeTy->isCharType()) {
4149 // char pointer types should be encoded as '*' unless it is a
4150 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004151 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004152 S += '*';
4153 return;
4154 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004155 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004156 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4157 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4158 S += '#';
4159 return;
4160 }
4161 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4162 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4163 S += '@';
4164 return;
4165 }
4166 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004167 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004168 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004169 getLegacyIntegralTypeEncoding(PointeeTy);
4170
Mike Stump1eb44332009-09-09 15:08:12 +00004171 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004172 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004173 return;
4174 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004175
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004176 if (const ArrayType *AT =
4177 // Ignore type qualifiers etc.
4178 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004179 if (isa<IncompleteArrayType>(AT)) {
4180 // Incomplete arrays are encoded as a pointer to the array element.
4181 S += '^';
4182
Mike Stump1eb44332009-09-09 15:08:12 +00004183 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004184 false, ExpandStructures, FD);
4185 } else {
4186 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004187
Anders Carlsson559a8332009-02-22 01:38:57 +00004188 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4189 S += llvm::utostr(CAT->getSize().getZExtValue());
4190 else {
4191 //Variable length arrays are encoded as a regular array with 0 elements.
4192 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4193 S += '0';
4194 }
Mike Stump1eb44332009-09-09 15:08:12 +00004195
4196 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004197 false, ExpandStructures, FD);
4198 S += ']';
4199 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004200 return;
4201 }
Mike Stump1eb44332009-09-09 15:08:12 +00004202
John McCall183700f2009-09-21 23:43:11 +00004203 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004204 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004205 return;
4206 }
Mike Stump1eb44332009-09-09 15:08:12 +00004207
Ted Kremenek6217b802009-07-29 21:53:49 +00004208 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004209 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004210 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004211 // Anonymous structures print as '?'
4212 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4213 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004214 if (ClassTemplateSpecializationDecl *Spec
4215 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4216 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4217 std::string TemplateArgsStr
4218 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004219 TemplateArgs.data(),
4220 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004221 (*this).PrintingPolicy);
4222
4223 S += TemplateArgsStr;
4224 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004225 } else {
4226 S += '?';
4227 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004228 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004229 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004230 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4231 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00004232 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004233 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004234 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00004235 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004236 S += '"';
4237 }
Mike Stump1eb44332009-09-09 15:08:12 +00004238
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004239 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004240 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004241 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004242 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004243 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004244 QualType qt = Field->getType();
4245 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00004246 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004247 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004248 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004249 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004250 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004251 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004252 return;
4253 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004254
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004255 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004256 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004257 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004258 else
4259 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004260 return;
4261 }
Mike Stump1eb44332009-09-09 15:08:12 +00004262
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004263 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004264 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004265 return;
4266 }
Mike Stump1eb44332009-09-09 15:08:12 +00004267
John McCallc12c5bb2010-05-15 11:32:37 +00004268 // Ignore protocol qualifiers when mangling at this level.
4269 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4270 T = OT->getBaseType();
4271
John McCall0953e762009-09-24 19:53:00 +00004272 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004273 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004274 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004275 S += '{';
4276 const IdentifierInfo *II = OI->getIdentifier();
4277 S += II->getName();
4278 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004279 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4280 DeepCollectObjCIvars(OI, true, Ivars);
4281 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4282 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4283 if (Field->isBitField())
4284 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004285 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004286 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004287 }
4288 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004289 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004290 }
Mike Stump1eb44332009-09-09 15:08:12 +00004291
John McCall183700f2009-09-21 23:43:11 +00004292 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004293 if (OPT->isObjCIdType()) {
4294 S += '@';
4295 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004296 }
Mike Stump1eb44332009-09-09 15:08:12 +00004297
Steve Naroff27d20a22009-10-28 22:03:49 +00004298 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4299 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4300 // Since this is a binary compatibility issue, need to consult with runtime
4301 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004302 S += '#';
4303 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004304 }
Mike Stump1eb44332009-09-09 15:08:12 +00004305
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004306 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004307 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004308 ExpandPointedToStructures,
4309 ExpandStructures, FD);
4310 if (FD || EncodingProperty) {
4311 // Note that we do extended encoding of protocol qualifer list
4312 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004313 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004314 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4315 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004316 S += '<';
4317 S += (*I)->getNameAsString();
4318 S += '>';
4319 }
4320 S += '"';
4321 }
4322 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004323 }
Mike Stump1eb44332009-09-09 15:08:12 +00004324
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004325 QualType PointeeTy = OPT->getPointeeType();
4326 if (!EncodingProperty &&
4327 isa<TypedefType>(PointeeTy.getTypePtr())) {
4328 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004329 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004330 // {...};
4331 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004332 getObjCEncodingForTypeImpl(PointeeTy, S,
4333 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004334 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004335 return;
4336 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004337
4338 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004339 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004340 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004341 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004342 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4343 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004344 S += '<';
4345 S += (*I)->getNameAsString();
4346 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004347 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004348 S += '"';
4349 }
4350 return;
4351 }
Mike Stump1eb44332009-09-09 15:08:12 +00004352
John McCall532ec7b2010-05-17 23:56:34 +00004353 // gcc just blithely ignores member pointers.
4354 // TODO: maybe there should be a mangling for these
4355 if (T->getAs<MemberPointerType>())
4356 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004357
4358 if (T->isVectorType()) {
4359 // This matches gcc's encoding, even though technically it is
4360 // insufficient.
4361 // FIXME. We should do a better job than gcc.
4362 return;
4363 }
4364
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004365 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004366}
4367
Mike Stump1eb44332009-09-09 15:08:12 +00004368void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004369 std::string& S) const {
4370 if (QT & Decl::OBJC_TQ_In)
4371 S += 'n';
4372 if (QT & Decl::OBJC_TQ_Inout)
4373 S += 'N';
4374 if (QT & Decl::OBJC_TQ_Out)
4375 S += 'o';
4376 if (QT & Decl::OBJC_TQ_Bycopy)
4377 S += 'O';
4378 if (QT & Decl::OBJC_TQ_Byref)
4379 S += 'R';
4380 if (QT & Decl::OBJC_TQ_Oneway)
4381 S += 'V';
4382}
4383
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004384void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004385 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004386
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004387 BuiltinVaListType = T;
4388}
4389
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004390void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004391 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00004392}
4393
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004394void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004395 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004396}
4397
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004398void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004399 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004400}
4401
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004402void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004403 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004404}
4405
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004406void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004407 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004408 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004409
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004410 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004411}
4412
John McCall0bd6feb2009-12-02 08:04:21 +00004413/// \brief Retrieve the template name that corresponds to a non-empty
4414/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004415TemplateName
4416ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4417 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004418 unsigned size = End - Begin;
4419 assert(size > 1 && "set is not overloaded!");
4420
4421 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4422 size * sizeof(FunctionTemplateDecl*));
4423 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4424
4425 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004426 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004427 NamedDecl *D = *I;
4428 assert(isa<FunctionTemplateDecl>(D) ||
4429 (isa<UsingShadowDecl>(D) &&
4430 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4431 *Storage++ = D;
4432 }
4433
4434 return TemplateName(OT);
4435}
4436
Douglas Gregor7532dc62009-03-30 22:58:21 +00004437/// \brief Retrieve the template name that represents a qualified
4438/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004439TemplateName
4440ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4441 bool TemplateKeyword,
4442 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004443 assert(NNS && "Missing nested-name-specifier in qualified template name");
4444
Douglas Gregor789b1f62010-02-04 18:10:26 +00004445 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004446 llvm::FoldingSetNodeID ID;
4447 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4448
4449 void *InsertPos = 0;
4450 QualifiedTemplateName *QTN =
4451 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4452 if (!QTN) {
4453 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4454 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4455 }
4456
4457 return TemplateName(QTN);
4458}
4459
4460/// \brief Retrieve the template name that represents a dependent
4461/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004462TemplateName
4463ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4464 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004465 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004466 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004467
4468 llvm::FoldingSetNodeID ID;
4469 DependentTemplateName::Profile(ID, NNS, Name);
4470
4471 void *InsertPos = 0;
4472 DependentTemplateName *QTN =
4473 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4474
4475 if (QTN)
4476 return TemplateName(QTN);
4477
4478 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4479 if (CanonNNS == NNS) {
4480 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4481 } else {
4482 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4483 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004484 DependentTemplateName *CheckQTN =
4485 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4486 assert(!CheckQTN && "Dependent type name canonicalization broken");
4487 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004488 }
4489
4490 DependentTemplateNames.InsertNode(QTN, InsertPos);
4491 return TemplateName(QTN);
4492}
4493
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004494/// \brief Retrieve the template name that represents a dependent
4495/// template name such as \c MetaFun::template operator+.
4496TemplateName
4497ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004498 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004499 assert((!NNS || NNS->isDependent()) &&
4500 "Nested name specifier must be dependent");
4501
4502 llvm::FoldingSetNodeID ID;
4503 DependentTemplateName::Profile(ID, NNS, Operator);
4504
4505 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004506 DependentTemplateName *QTN
4507 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004508
4509 if (QTN)
4510 return TemplateName(QTN);
4511
4512 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4513 if (CanonNNS == NNS) {
4514 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4515 } else {
4516 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4517 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004518
4519 DependentTemplateName *CheckQTN
4520 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4521 assert(!CheckQTN && "Dependent template name canonicalization broken");
4522 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004523 }
4524
4525 DependentTemplateNames.InsertNode(QTN, InsertPos);
4526 return TemplateName(QTN);
4527}
4528
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004529TemplateName
4530ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4531 const TemplateArgument &ArgPack) const {
4532 ASTContext &Self = const_cast<ASTContext &>(*this);
4533 llvm::FoldingSetNodeID ID;
4534 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4535
4536 void *InsertPos = 0;
4537 SubstTemplateTemplateParmPackStorage *Subst
4538 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4539
4540 if (!Subst) {
4541 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4542 ArgPack.pack_size(),
4543 ArgPack.pack_begin());
4544 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4545 }
4546
4547 return TemplateName(Subst);
4548}
4549
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004550/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004551/// TargetInfo, produce the corresponding type. The unsigned @p Type
4552/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004553CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004554 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004555 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004556 case TargetInfo::SignedShort: return ShortTy;
4557 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4558 case TargetInfo::SignedInt: return IntTy;
4559 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4560 case TargetInfo::SignedLong: return LongTy;
4561 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4562 case TargetInfo::SignedLongLong: return LongLongTy;
4563 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4564 }
4565
4566 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004567 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004568}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004569
4570//===----------------------------------------------------------------------===//
4571// Type Predicates.
4572//===----------------------------------------------------------------------===//
4573
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004574/// isObjCNSObjectType - Return true if this is an NSObject object using
4575/// NSObject attribute on a c-style pointer type.
4576/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004577/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004578///
4579bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCallf4c73712011-01-19 06:33:43 +00004580 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Richard Smith162e1c12011-04-15 14:24:37 +00004581 if (TypedefNameDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004582 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004583 return true;
4584 }
Mike Stump1eb44332009-09-09 15:08:12 +00004585 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004586}
4587
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004588/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4589/// garbage collection attribute.
4590///
John McCallae278a32011-01-12 00:34:59 +00004591Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4592 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4593 return Qualifiers::GCNone;
4594
4595 assert(getLangOptions().ObjC1);
4596 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4597
4598 // Default behaviour under objective-C's gc is for ObjC pointers
4599 // (or pointers to them) be treated as though they were declared
4600 // as __strong.
4601 if (GCAttrs == Qualifiers::GCNone) {
4602 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4603 return Qualifiers::Strong;
4604 else if (Ty->isPointerType())
4605 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4606 } else {
4607 // It's not valid to set GC attributes on anything that isn't a
4608 // pointer.
4609#ifndef NDEBUG
4610 QualType CT = Ty->getCanonicalTypeInternal();
4611 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4612 CT = AT->getElementType();
4613 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4614#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004615 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004616 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004617}
4618
Chris Lattner6ac46a42008-04-07 06:51:04 +00004619//===----------------------------------------------------------------------===//
4620// Type Compatibility Testing
4621//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004622
Mike Stump1eb44332009-09-09 15:08:12 +00004623/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004624/// compatible.
4625static bool areCompatVectorTypes(const VectorType *LHS,
4626 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004627 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004628 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004629 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004630}
4631
Douglas Gregor255210e2010-08-06 10:14:59 +00004632bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4633 QualType SecondVec) {
4634 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4635 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4636
4637 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4638 return true;
4639
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004640 // Treat Neon vector types and most AltiVec vector types as if they are the
4641 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004642 const VectorType *First = FirstVec->getAs<VectorType>();
4643 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004644 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004645 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004646 First->getVectorKind() != VectorType::AltiVecPixel &&
4647 First->getVectorKind() != VectorType::AltiVecBool &&
4648 Second->getVectorKind() != VectorType::AltiVecPixel &&
4649 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004650 return true;
4651
4652 return false;
4653}
4654
Steve Naroff4084c302009-07-23 01:01:38 +00004655//===----------------------------------------------------------------------===//
4656// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4657//===----------------------------------------------------------------------===//
4658
4659/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4660/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00004661bool
4662ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4663 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00004664 if (lProto == rProto)
4665 return true;
4666 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4667 E = rProto->protocol_end(); PI != E; ++PI)
4668 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4669 return true;
4670 return false;
4671}
4672
Steve Naroff4084c302009-07-23 01:01:38 +00004673/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4674/// return true if lhs's protocols conform to rhs's protocol; false
4675/// otherwise.
4676bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4677 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4678 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4679 return false;
4680}
4681
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004682/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4683/// Class<p1, ...>.
4684bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4685 QualType rhs) {
4686 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4687 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4688 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4689
4690 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4691 E = lhsQID->qual_end(); I != E; ++I) {
4692 bool match = false;
4693 ObjCProtocolDecl *lhsProto = *I;
4694 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4695 E = rhsOPT->qual_end(); J != E; ++J) {
4696 ObjCProtocolDecl *rhsProto = *J;
4697 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4698 match = true;
4699 break;
4700 }
4701 }
4702 if (!match)
4703 return false;
4704 }
4705 return true;
4706}
4707
Steve Naroff4084c302009-07-23 01:01:38 +00004708/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4709/// ObjCQualifiedIDType.
4710bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4711 bool compare) {
4712 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004713 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004714 lhs->isObjCIdType() || lhs->isObjCClassType())
4715 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004716 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004717 rhs->isObjCIdType() || rhs->isObjCClassType())
4718 return true;
4719
4720 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004721 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004722
Steve Naroff4084c302009-07-23 01:01:38 +00004723 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004724
Steve Naroff4084c302009-07-23 01:01:38 +00004725 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004726 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004727 // make sure we check the class hierarchy.
4728 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4729 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4730 E = lhsQID->qual_end(); I != E; ++I) {
4731 // when comparing an id<P> on lhs with a static type on rhs,
4732 // see if static class implements all of id's protocols, directly or
4733 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004734 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004735 return false;
4736 }
4737 }
4738 // If there are no qualifiers and no interface, we have an 'id'.
4739 return true;
4740 }
Mike Stump1eb44332009-09-09 15:08:12 +00004741 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004742 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4743 E = lhsQID->qual_end(); I != E; ++I) {
4744 ObjCProtocolDecl *lhsProto = *I;
4745 bool match = false;
4746
4747 // when comparing an id<P> on lhs with a static type on rhs,
4748 // see if static class implements all of id's protocols, directly or
4749 // through its super class and categories.
4750 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4751 E = rhsOPT->qual_end(); J != E; ++J) {
4752 ObjCProtocolDecl *rhsProto = *J;
4753 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4754 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4755 match = true;
4756 break;
4757 }
4758 }
Mike Stump1eb44332009-09-09 15:08:12 +00004759 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004760 // make sure we check the class hierarchy.
4761 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4762 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4763 E = lhsQID->qual_end(); I != E; ++I) {
4764 // when comparing an id<P> on lhs with a static type on rhs,
4765 // see if static class implements all of id's protocols, directly or
4766 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004767 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004768 match = true;
4769 break;
4770 }
4771 }
4772 }
4773 if (!match)
4774 return false;
4775 }
Mike Stump1eb44332009-09-09 15:08:12 +00004776
Steve Naroff4084c302009-07-23 01:01:38 +00004777 return true;
4778 }
Mike Stump1eb44332009-09-09 15:08:12 +00004779
Steve Naroff4084c302009-07-23 01:01:38 +00004780 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4781 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4782
Mike Stump1eb44332009-09-09 15:08:12 +00004783 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004784 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004785 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004786 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4787 E = lhsOPT->qual_end(); I != E; ++I) {
4788 ObjCProtocolDecl *lhsProto = *I;
4789 bool match = false;
4790
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004791 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00004792 // see if static class implements all of id's protocols, directly or
4793 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004794 // First, lhs protocols in the qualifier list must be found, direct
4795 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00004796 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4797 E = rhsQID->qual_end(); J != E; ++J) {
4798 ObjCProtocolDecl *rhsProto = *J;
4799 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4800 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4801 match = true;
4802 break;
4803 }
4804 }
4805 if (!match)
4806 return false;
4807 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004808
4809 // Static class's protocols, or its super class or category protocols
4810 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4811 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4812 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4813 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4814 // This is rather dubious but matches gcc's behavior. If lhs has
4815 // no type qualifier and its class has no static protocol(s)
4816 // assume that it is mismatch.
4817 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4818 return false;
4819 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4820 LHSInheritedProtocols.begin(),
4821 E = LHSInheritedProtocols.end(); I != E; ++I) {
4822 bool match = false;
4823 ObjCProtocolDecl *lhsProto = (*I);
4824 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4825 E = rhsQID->qual_end(); J != E; ++J) {
4826 ObjCProtocolDecl *rhsProto = *J;
4827 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4828 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4829 match = true;
4830 break;
4831 }
4832 }
4833 if (!match)
4834 return false;
4835 }
4836 }
Steve Naroff4084c302009-07-23 01:01:38 +00004837 return true;
4838 }
4839 return false;
4840}
4841
Eli Friedman3d815e72008-08-22 00:56:42 +00004842/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004843/// compatible for assignment from RHS to LHS. This handles validation of any
4844/// protocol qualifiers on the LHS or RHS.
4845///
Steve Naroff14108da2009-07-10 23:34:53 +00004846bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4847 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004848 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4849 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4850
Steve Naroffde2e22d2009-07-15 18:40:39 +00004851 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004852 if (LHS->isObjCUnqualifiedIdOrClass() ||
4853 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004854 return true;
4855
John McCallc12c5bb2010-05-15 11:32:37 +00004856 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004857 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4858 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004859 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004860
4861 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4862 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4863 QualType(RHSOPT,0));
4864
John McCallc12c5bb2010-05-15 11:32:37 +00004865 // If we have 2 user-defined types, fall into that path.
4866 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004867 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004868
Steve Naroff4084c302009-07-23 01:01:38 +00004869 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004870}
4871
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004872/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004873/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004874/// arguments in block literals. When passed as arguments, passing 'A*' where
4875/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4876/// not OK. For the return type, the opposite is not OK.
4877bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4878 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00004879 const ObjCObjectPointerType *RHSOPT,
4880 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004881 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004882 return true;
4883
4884 if (LHSOPT->isObjCBuiltinType()) {
4885 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4886 }
4887
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004888 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004889 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4890 QualType(RHSOPT,0),
4891 false);
4892
4893 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4894 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4895 if (LHS && RHS) { // We have 2 user-defined types.
4896 if (LHS != RHS) {
4897 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00004898 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004899 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00004900 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004901 }
4902 else
4903 return true;
4904 }
4905 return false;
4906}
4907
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004908/// getIntersectionOfProtocols - This routine finds the intersection of set
4909/// of protocols inherited from two distinct objective-c pointer objects.
4910/// It is used to build composite qualifier list of the composite type of
4911/// the conditional expression involving two objective-c pointer objects.
4912static
4913void getIntersectionOfProtocols(ASTContext &Context,
4914 const ObjCObjectPointerType *LHSOPT,
4915 const ObjCObjectPointerType *RHSOPT,
4916 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4917
John McCallc12c5bb2010-05-15 11:32:37 +00004918 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4919 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4920 assert(LHS->getInterface() && "LHS must have an interface base");
4921 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004922
4923 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4924 unsigned LHSNumProtocols = LHS->getNumProtocols();
4925 if (LHSNumProtocols > 0)
4926 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4927 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004928 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004929 Context.CollectInheritedProtocols(LHS->getInterface(),
4930 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004931 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4932 LHSInheritedProtocols.end());
4933 }
4934
4935 unsigned RHSNumProtocols = RHS->getNumProtocols();
4936 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004937 ObjCProtocolDecl **RHSProtocols =
4938 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004939 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4940 if (InheritedProtocolSet.count(RHSProtocols[i]))
4941 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4942 }
4943 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004944 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004945 Context.CollectInheritedProtocols(RHS->getInterface(),
4946 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004947 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4948 RHSInheritedProtocols.begin(),
4949 E = RHSInheritedProtocols.end(); I != E; ++I)
4950 if (InheritedProtocolSet.count((*I)))
4951 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004952 }
4953}
4954
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004955/// areCommonBaseCompatible - Returns common base class of the two classes if
4956/// one found. Note that this is O'2 algorithm. But it will be called as the
4957/// last type comparison in a ?-exp of ObjC pointer types before a
4958/// warning is issued. So, its invokation is extremely rare.
4959QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004960 const ObjCObjectPointerType *Lptr,
4961 const ObjCObjectPointerType *Rptr) {
4962 const ObjCObjectType *LHS = Lptr->getObjectType();
4963 const ObjCObjectType *RHS = Rptr->getObjectType();
4964 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4965 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00004966 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004967 return QualType();
4968
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00004969 do {
John McCallc12c5bb2010-05-15 11:32:37 +00004970 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004971 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004972 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4973 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4974
4975 QualType Result = QualType(LHS, 0);
4976 if (!Protocols.empty())
4977 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4978 Result = getObjCObjectPointerType(Result);
4979 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004980 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00004981 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004982
4983 return QualType();
4984}
4985
John McCallc12c5bb2010-05-15 11:32:37 +00004986bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4987 const ObjCObjectType *RHS) {
4988 assert(LHS->getInterface() && "LHS is not an interface type");
4989 assert(RHS->getInterface() && "RHS is not an interface type");
4990
Chris Lattner6ac46a42008-04-07 06:51:04 +00004991 // Verify that the base decls are compatible: the RHS must be a subclass of
4992 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004993 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004994 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004995
Chris Lattner6ac46a42008-04-07 06:51:04 +00004996 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4997 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004998 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004999 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005000
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005001 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5002 // more detailed analysis is required.
5003 if (RHS->getNumProtocols() == 0) {
5004 // OK, if LHS is a superclass of RHS *and*
5005 // this superclass is assignment compatible with LHS.
5006 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005007 bool IsSuperClass =
5008 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5009 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005010 // OK if conversion of LHS to SuperClass results in narrowing of types
5011 // ; i.e., SuperClass may implement at least one of the protocols
5012 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5013 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5014 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005015 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005016 // If super class has no protocols, it is not a match.
5017 if (SuperClassInheritedProtocols.empty())
5018 return false;
5019
5020 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5021 LHSPE = LHS->qual_end();
5022 LHSPI != LHSPE; LHSPI++) {
5023 bool SuperImplementsProtocol = false;
5024 ObjCProtocolDecl *LHSProto = (*LHSPI);
5025
5026 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5027 SuperClassInheritedProtocols.begin(),
5028 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5029 ObjCProtocolDecl *SuperClassProto = (*I);
5030 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5031 SuperImplementsProtocol = true;
5032 break;
5033 }
5034 }
5035 if (!SuperImplementsProtocol)
5036 return false;
5037 }
5038 return true;
5039 }
5040 return false;
5041 }
Mike Stump1eb44332009-09-09 15:08:12 +00005042
John McCallc12c5bb2010-05-15 11:32:37 +00005043 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5044 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005045 LHSPI != LHSPE; LHSPI++) {
5046 bool RHSImplementsProtocol = false;
5047
5048 // If the RHS doesn't implement the protocol on the left, the types
5049 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005050 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5051 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005052 RHSPI != RHSPE; RHSPI++) {
5053 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005054 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005055 break;
5056 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005057 }
5058 // FIXME: For better diagnostics, consider passing back the protocol name.
5059 if (!RHSImplementsProtocol)
5060 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005061 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005062 // The RHS implements all protocols listed on the LHS.
5063 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005064}
5065
Steve Naroff389bf462009-02-12 17:52:19 +00005066bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5067 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005068 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5069 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005070
Steve Naroff14108da2009-07-10 23:34:53 +00005071 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005072 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005073
5074 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5075 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005076}
5077
Douglas Gregor569c3162010-08-07 11:51:51 +00005078bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5079 return canAssignObjCInterfaces(
5080 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5081 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5082}
5083
Mike Stump1eb44332009-09-09 15:08:12 +00005084/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005085/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005086/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005087/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005088bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5089 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005090 if (getLangOptions().CPlusPlus)
5091 return hasSameType(LHS, RHS);
5092
Douglas Gregor447234d2010-07-29 15:18:02 +00005093 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005094}
5095
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005096bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5097 return !mergeTypes(LHS, RHS, true).isNull();
5098}
5099
Peter Collingbourne48466752010-10-24 18:30:18 +00005100/// mergeTransparentUnionType - if T is a transparent union type and a member
5101/// of T is compatible with SubType, return the merged type, else return
5102/// QualType()
5103QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5104 bool OfBlockPointer,
5105 bool Unqualified) {
5106 if (const RecordType *UT = T->getAsUnionType()) {
5107 RecordDecl *UD = UT->getDecl();
5108 if (UD->hasAttr<TransparentUnionAttr>()) {
5109 for (RecordDecl::field_iterator it = UD->field_begin(),
5110 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005111 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005112 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5113 if (!MT.isNull())
5114 return MT;
5115 }
5116 }
5117 }
5118
5119 return QualType();
5120}
5121
5122/// mergeFunctionArgumentTypes - merge two types which appear as function
5123/// argument types
5124QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5125 bool OfBlockPointer,
5126 bool Unqualified) {
5127 // GNU extension: two types are compatible if they appear as a function
5128 // argument, one of the types is a transparent union type and the other
5129 // type is compatible with a union member
5130 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5131 Unqualified);
5132 if (!lmerge.isNull())
5133 return lmerge;
5134
5135 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5136 Unqualified);
5137 if (!rmerge.isNull())
5138 return rmerge;
5139
5140 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5141}
5142
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005143QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005144 bool OfBlockPointer,
5145 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005146 const FunctionType *lbase = lhs->getAs<FunctionType>();
5147 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005148 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5149 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005150 bool allLTypes = true;
5151 bool allRTypes = true;
5152
5153 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005154 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005155 if (OfBlockPointer) {
5156 QualType RHS = rbase->getResultType();
5157 QualType LHS = lbase->getResultType();
5158 bool UnqualifiedResult = Unqualified;
5159 if (!UnqualifiedResult)
5160 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005161 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005162 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005163 else
John McCall8cc246c2010-12-15 01:06:38 +00005164 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5165 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005166 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005167
5168 if (Unqualified)
5169 retType = retType.getUnqualifiedType();
5170
5171 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5172 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5173 if (Unqualified) {
5174 LRetType = LRetType.getUnqualifiedType();
5175 RRetType = RRetType.getUnqualifiedType();
5176 }
5177
5178 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005179 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005180 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005181 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005182
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005183 // FIXME: double check this
5184 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5185 // rbase->getRegParmAttr() != 0 &&
5186 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005187 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5188 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005189
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005190 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005191 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005192 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005193
John McCall8cc246c2010-12-15 01:06:38 +00005194 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005195 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5196 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005197 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5198 return QualType();
5199
5200 // It's noreturn if either type is.
5201 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5202 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5203 if (NoReturn != lbaseInfo.getNoReturn())
5204 allLTypes = false;
5205 if (NoReturn != rbaseInfo.getNoReturn())
5206 allRTypes = false;
5207
5208 FunctionType::ExtInfo einfo(NoReturn,
Eli Friedmana49218e2011-04-09 08:18:08 +00005209 lbaseInfo.getHasRegParm(),
John McCall8cc246c2010-12-15 01:06:38 +00005210 lbaseInfo.getRegParm(),
5211 lbaseInfo.getCC());
John McCalle23cf432010-12-14 08:05:40 +00005212
Eli Friedman3d815e72008-08-22 00:56:42 +00005213 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005214 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5215 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005216 unsigned lproto_nargs = lproto->getNumArgs();
5217 unsigned rproto_nargs = rproto->getNumArgs();
5218
5219 // Compatible functions must have the same number of arguments
5220 if (lproto_nargs != rproto_nargs)
5221 return QualType();
5222
5223 // Variadic and non-variadic functions aren't compatible
5224 if (lproto->isVariadic() != rproto->isVariadic())
5225 return QualType();
5226
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005227 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5228 return QualType();
5229
Eli Friedman3d815e72008-08-22 00:56:42 +00005230 // Check argument compatibility
5231 llvm::SmallVector<QualType, 10> types;
5232 for (unsigned i = 0; i < lproto_nargs; i++) {
5233 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5234 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005235 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5236 OfBlockPointer,
5237 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005238 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005239
5240 if (Unqualified)
5241 argtype = argtype.getUnqualifiedType();
5242
Eli Friedman3d815e72008-08-22 00:56:42 +00005243 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005244 if (Unqualified) {
5245 largtype = largtype.getUnqualifiedType();
5246 rargtype = rargtype.getUnqualifiedType();
5247 }
5248
Chris Lattner61710852008-10-05 17:34:18 +00005249 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5250 allLTypes = false;
5251 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5252 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005253 }
5254 if (allLTypes) return lhs;
5255 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005256
5257 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5258 EPI.ExtInfo = einfo;
5259 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005260 }
5261
5262 if (lproto) allRTypes = false;
5263 if (rproto) allLTypes = false;
5264
Douglas Gregor72564e72009-02-26 23:50:07 +00005265 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005266 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005267 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005268 if (proto->isVariadic()) return QualType();
5269 // Check that the types are compatible with the types that
5270 // would result from default argument promotions (C99 6.7.5.3p15).
5271 // The only types actually affected are promotable integer
5272 // types and floats, which would be passed as a different
5273 // type depending on whether the prototype is visible.
5274 unsigned proto_nargs = proto->getNumArgs();
5275 for (unsigned i = 0; i < proto_nargs; ++i) {
5276 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005277
5278 // Look at the promotion type of enum types, since that is the type used
5279 // to pass enum values.
5280 if (const EnumType *Enum = argTy->getAs<EnumType>())
5281 argTy = Enum->getDecl()->getPromotionType();
5282
Eli Friedman3d815e72008-08-22 00:56:42 +00005283 if (argTy->isPromotableIntegerType() ||
5284 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5285 return QualType();
5286 }
5287
5288 if (allLTypes) return lhs;
5289 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005290
5291 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5292 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005293 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005294 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005295 }
5296
5297 if (allLTypes) return lhs;
5298 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005299 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005300}
5301
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005302QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005303 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005304 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005305 // C++ [expr]: If an expression initially has the type "reference to T", the
5306 // type is adjusted to "T" prior to any further analysis, the expression
5307 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005308 // expression is an lvalue unless the reference is an rvalue reference and
5309 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005310 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5311 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005312
5313 if (Unqualified) {
5314 LHS = LHS.getUnqualifiedType();
5315 RHS = RHS.getUnqualifiedType();
5316 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005317
Eli Friedman3d815e72008-08-22 00:56:42 +00005318 QualType LHSCan = getCanonicalType(LHS),
5319 RHSCan = getCanonicalType(RHS);
5320
5321 // If two types are identical, they are compatible.
5322 if (LHSCan == RHSCan)
5323 return LHS;
5324
John McCall0953e762009-09-24 19:53:00 +00005325 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005326 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5327 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005328 if (LQuals != RQuals) {
5329 // If any of these qualifiers are different, we have a type
5330 // mismatch.
5331 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5332 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5333 return QualType();
5334
5335 // Exactly one GC qualifier difference is allowed: __strong is
5336 // okay if the other type has no GC qualifier but is an Objective
5337 // C object pointer (i.e. implicitly strong by default). We fix
5338 // this by pretending that the unqualified type was actually
5339 // qualified __strong.
5340 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5341 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5342 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5343
5344 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5345 return QualType();
5346
5347 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5348 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5349 }
5350 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5351 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5352 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005353 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005354 }
5355
5356 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005357
Eli Friedman852d63b2009-06-01 01:22:52 +00005358 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5359 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005360
Chris Lattner1adb8832008-01-14 05:45:46 +00005361 // We want to consider the two function types to be the same for these
5362 // comparisons, just force one to the other.
5363 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5364 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005365
5366 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005367 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5368 LHSClass = Type::ConstantArray;
5369 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5370 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005371
John McCallc12c5bb2010-05-15 11:32:37 +00005372 // ObjCInterfaces are just specialized ObjCObjects.
5373 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5374 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5375
Nate Begeman213541a2008-04-18 23:10:10 +00005376 // Canonicalize ExtVector -> Vector.
5377 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5378 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005379
Chris Lattnera36a61f2008-04-07 05:43:21 +00005380 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005381 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005382 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005383 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005384 // Compatibility is based on the underlying type, not the promotion
5385 // type.
John McCall183700f2009-09-21 23:43:11 +00005386 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005387 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5388 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005389 }
John McCall183700f2009-09-21 23:43:11 +00005390 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005391 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5392 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005393 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005394
Eli Friedman3d815e72008-08-22 00:56:42 +00005395 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005396 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005397
Steve Naroff4a746782008-01-09 22:43:08 +00005398 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005399 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005400#define TYPE(Class, Base)
5401#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005402#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005403#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5404#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5405#include "clang/AST/TypeNodes.def"
5406 assert(false && "Non-canonical and dependent types shouldn't get here");
5407 return QualType();
5408
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005409 case Type::LValueReference:
5410 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005411 case Type::MemberPointer:
5412 assert(false && "C++ should never be in mergeTypes");
5413 return QualType();
5414
John McCallc12c5bb2010-05-15 11:32:37 +00005415 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005416 case Type::IncompleteArray:
5417 case Type::VariableArray:
5418 case Type::FunctionProto:
5419 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005420 assert(false && "Types are eliminated above");
5421 return QualType();
5422
Chris Lattner1adb8832008-01-14 05:45:46 +00005423 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005424 {
5425 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005426 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5427 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005428 if (Unqualified) {
5429 LHSPointee = LHSPointee.getUnqualifiedType();
5430 RHSPointee = RHSPointee.getUnqualifiedType();
5431 }
5432 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5433 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005434 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005435 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005436 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005437 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005438 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005439 return getPointerType(ResultType);
5440 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005441 case Type::BlockPointer:
5442 {
5443 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005444 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5445 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005446 if (Unqualified) {
5447 LHSPointee = LHSPointee.getUnqualifiedType();
5448 RHSPointee = RHSPointee.getUnqualifiedType();
5449 }
5450 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5451 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005452 if (ResultType.isNull()) return QualType();
5453 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5454 return LHS;
5455 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5456 return RHS;
5457 return getBlockPointerType(ResultType);
5458 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005459 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005460 {
5461 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5462 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5463 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5464 return QualType();
5465
5466 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5467 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005468 if (Unqualified) {
5469 LHSElem = LHSElem.getUnqualifiedType();
5470 RHSElem = RHSElem.getUnqualifiedType();
5471 }
5472
5473 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005474 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005475 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5476 return LHS;
5477 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5478 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005479 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5480 ArrayType::ArraySizeModifier(), 0);
5481 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5482 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005483 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5484 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005485 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5486 return LHS;
5487 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5488 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005489 if (LVAT) {
5490 // FIXME: This isn't correct! But tricky to implement because
5491 // the array's size has to be the size of LHS, but the type
5492 // has to be different.
5493 return LHS;
5494 }
5495 if (RVAT) {
5496 // FIXME: This isn't correct! But tricky to implement because
5497 // the array's size has to be the size of RHS, but the type
5498 // has to be different.
5499 return RHS;
5500 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005501 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5502 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005503 return getIncompleteArrayType(ResultType,
5504 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005505 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005506 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005507 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005508 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005509 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005510 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005511 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005512 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005513 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005514 case Type::Complex:
5515 // Distinct complex types are incompatible.
5516 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005517 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005518 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005519 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5520 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005521 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005522 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005523 case Type::ObjCObject: {
5524 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005525 // FIXME: This should be type compatibility, e.g. whether
5526 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005527 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5528 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5529 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005530 return LHS;
5531
Eli Friedman3d815e72008-08-22 00:56:42 +00005532 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005533 }
Steve Naroff14108da2009-07-10 23:34:53 +00005534 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005535 if (OfBlockPointer) {
5536 if (canAssignObjCInterfacesInBlockPointer(
5537 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005538 RHS->getAs<ObjCObjectPointerType>(),
5539 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005540 return LHS;
5541 return QualType();
5542 }
John McCall183700f2009-09-21 23:43:11 +00005543 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5544 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005545 return LHS;
5546
Steve Naroffbc76dd02008-12-10 22:14:21 +00005547 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005548 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005549 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005550
5551 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005552}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005553
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005554/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5555/// 'RHS' attributes and returns the merged version; including for function
5556/// return types.
5557QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5558 QualType LHSCan = getCanonicalType(LHS),
5559 RHSCan = getCanonicalType(RHS);
5560 // If two types are identical, they are compatible.
5561 if (LHSCan == RHSCan)
5562 return LHS;
5563 if (RHSCan->isFunctionType()) {
5564 if (!LHSCan->isFunctionType())
5565 return QualType();
5566 QualType OldReturnType =
5567 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5568 QualType NewReturnType =
5569 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5570 QualType ResReturnType =
5571 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5572 if (ResReturnType.isNull())
5573 return QualType();
5574 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5575 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5576 // In either case, use OldReturnType to build the new function type.
5577 const FunctionType *F = LHS->getAs<FunctionType>();
5578 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005579 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5580 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005581 QualType ResultType
5582 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005583 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005584 return ResultType;
5585 }
5586 }
5587 return QualType();
5588 }
5589
5590 // If the qualifiers are different, the types can still be merged.
5591 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5592 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5593 if (LQuals != RQuals) {
5594 // If any of these qualifiers are different, we have a type mismatch.
5595 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5596 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5597 return QualType();
5598
5599 // Exactly one GC qualifier difference is allowed: __strong is
5600 // okay if the other type has no GC qualifier but is an Objective
5601 // C object pointer (i.e. implicitly strong by default). We fix
5602 // this by pretending that the unqualified type was actually
5603 // qualified __strong.
5604 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5605 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5606 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5607
5608 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5609 return QualType();
5610
5611 if (GC_L == Qualifiers::Strong)
5612 return LHS;
5613 if (GC_R == Qualifiers::Strong)
5614 return RHS;
5615 return QualType();
5616 }
5617
5618 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5619 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5620 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5621 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5622 if (ResQT == LHSBaseQT)
5623 return LHS;
5624 if (ResQT == RHSBaseQT)
5625 return RHS;
5626 }
5627 return QualType();
5628}
5629
Chris Lattner5426bf62008-04-07 07:01:58 +00005630//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005631// Integer Predicates
5632//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005633
Jay Foad4ba2a172011-01-12 09:06:06 +00005634unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00005635 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005636 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005637 if (T->isBooleanType())
5638 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005639 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005640 return (unsigned)getTypeSize(T);
5641}
5642
5643QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005644 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005645
5646 // Turn <4 x signed int> -> <4 x unsigned int>
5647 if (const VectorType *VTy = T->getAs<VectorType>())
5648 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005649 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005650
5651 // For enums, we return the unsigned version of the base type.
5652 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005653 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005654
5655 const BuiltinType *BTy = T->getAs<BuiltinType>();
5656 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005657 switch (BTy->getKind()) {
5658 case BuiltinType::Char_S:
5659 case BuiltinType::SChar:
5660 return UnsignedCharTy;
5661 case BuiltinType::Short:
5662 return UnsignedShortTy;
5663 case BuiltinType::Int:
5664 return UnsignedIntTy;
5665 case BuiltinType::Long:
5666 return UnsignedLongTy;
5667 case BuiltinType::LongLong:
5668 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005669 case BuiltinType::Int128:
5670 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005671 default:
5672 assert(0 && "Unexpected signed integer type");
5673 return QualType();
5674 }
5675}
5676
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005677ASTMutationListener::~ASTMutationListener() { }
5678
Chris Lattner86df27b2009-06-14 00:45:47 +00005679
5680//===----------------------------------------------------------------------===//
5681// Builtin Type Computation
5682//===----------------------------------------------------------------------===//
5683
5684/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00005685/// pointer over the consumed characters. This returns the resultant type. If
5686/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5687/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5688/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00005689///
5690/// RequiresICE is filled in on return to indicate whether the value is required
5691/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00005692static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005693 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00005694 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00005695 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005696 // Modifiers.
5697 int HowLong = 0;
5698 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00005699 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005700
Chris Lattner33daae62010-10-01 22:42:38 +00005701 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00005702 bool Done = false;
5703 while (!Done) {
5704 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005705 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005706 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00005707 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005708 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005709 case 'S':
5710 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5711 assert(!Signed && "Can't use 'S' modifier multiple times!");
5712 Signed = true;
5713 break;
5714 case 'U':
5715 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5716 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5717 Unsigned = true;
5718 break;
5719 case 'L':
5720 assert(HowLong <= 2 && "Can't have LLLL modifier");
5721 ++HowLong;
5722 break;
5723 }
5724 }
5725
5726 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005727
Chris Lattner86df27b2009-06-14 00:45:47 +00005728 // Read the base type.
5729 switch (*Str++) {
5730 default: assert(0 && "Unknown builtin type letter!");
5731 case 'v':
5732 assert(HowLong == 0 && !Signed && !Unsigned &&
5733 "Bad modifiers used with 'v'!");
5734 Type = Context.VoidTy;
5735 break;
5736 case 'f':
5737 assert(HowLong == 0 && !Signed && !Unsigned &&
5738 "Bad modifiers used with 'f'!");
5739 Type = Context.FloatTy;
5740 break;
5741 case 'd':
5742 assert(HowLong < 2 && !Signed && !Unsigned &&
5743 "Bad modifiers used with 'd'!");
5744 if (HowLong)
5745 Type = Context.LongDoubleTy;
5746 else
5747 Type = Context.DoubleTy;
5748 break;
5749 case 's':
5750 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5751 if (Unsigned)
5752 Type = Context.UnsignedShortTy;
5753 else
5754 Type = Context.ShortTy;
5755 break;
5756 case 'i':
5757 if (HowLong == 3)
5758 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5759 else if (HowLong == 2)
5760 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5761 else if (HowLong == 1)
5762 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5763 else
5764 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5765 break;
5766 case 'c':
5767 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5768 if (Signed)
5769 Type = Context.SignedCharTy;
5770 else if (Unsigned)
5771 Type = Context.UnsignedCharTy;
5772 else
5773 Type = Context.CharTy;
5774 break;
5775 case 'b': // boolean
5776 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5777 Type = Context.BoolTy;
5778 break;
5779 case 'z': // size_t.
5780 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5781 Type = Context.getSizeType();
5782 break;
5783 case 'F':
5784 Type = Context.getCFConstantStringType();
5785 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00005786 case 'G':
5787 Type = Context.getObjCIdType();
5788 break;
5789 case 'H':
5790 Type = Context.getObjCSelType();
5791 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005792 case 'a':
5793 Type = Context.getBuiltinVaListType();
5794 assert(!Type.isNull() && "builtin va list type not initialized!");
5795 break;
5796 case 'A':
5797 // This is a "reference" to a va_list; however, what exactly
5798 // this means depends on how va_list is defined. There are two
5799 // different kinds of va_list: ones passed by value, and ones
5800 // passed by reference. An example of a by-value va_list is
5801 // x86, where va_list is a char*. An example of by-ref va_list
5802 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5803 // we want this argument to be a char*&; for x86-64, we want
5804 // it to be a __va_list_tag*.
5805 Type = Context.getBuiltinVaListType();
5806 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00005807 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00005808 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00005809 else
Chris Lattner86df27b2009-06-14 00:45:47 +00005810 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005811 break;
5812 case 'V': {
5813 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005814 unsigned NumElements = strtoul(Str, &End, 10);
5815 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00005816 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005817
Chris Lattner14e0e742010-10-01 22:53:11 +00005818 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5819 RequiresICE, false);
5820 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00005821
5822 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005823 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00005824 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00005825 break;
5826 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005827 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00005828 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5829 false);
5830 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00005831 Type = Context.getComplexType(ElementType);
5832 break;
5833 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005834 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005835 Type = Context.getFILEType();
5836 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005837 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005838 return QualType();
5839 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005840 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005841 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005842 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005843 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005844 else
5845 Type = Context.getjmp_bufType();
5846
Mike Stumpfd612db2009-07-28 23:47:15 +00005847 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005848 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005849 return QualType();
5850 }
5851 break;
Mike Stump782fa302009-07-28 02:25:19 +00005852 }
Mike Stump1eb44332009-09-09 15:08:12 +00005853
Chris Lattner33daae62010-10-01 22:42:38 +00005854 // If there are modifiers and if we're allowed to parse them, go for it.
5855 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00005856 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005857 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00005858 default: Done = true; --Str; break;
5859 case '*':
5860 case '&': {
5861 // Both pointers and references can have their pointee types
5862 // qualified with an address space.
5863 char *End;
5864 unsigned AddrSpace = strtoul(Str, &End, 10);
5865 if (End != Str && AddrSpace != 0) {
5866 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5867 Str = End;
5868 }
5869 if (c == '*')
5870 Type = Context.getPointerType(Type);
5871 else
5872 Type = Context.getLValueReferenceType(Type);
5873 break;
5874 }
5875 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5876 case 'C':
5877 Type = Type.withConst();
5878 break;
5879 case 'D':
5880 Type = Context.getVolatileType(Type);
5881 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005882 }
5883 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00005884
Chris Lattner14e0e742010-10-01 22:53:11 +00005885 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00005886 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00005887
Chris Lattner86df27b2009-06-14 00:45:47 +00005888 return Type;
5889}
5890
5891/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00005892QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00005893 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00005894 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00005895 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00005896
Chris Lattner86df27b2009-06-14 00:45:47 +00005897 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005898
Chris Lattner14e0e742010-10-01 22:53:11 +00005899 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00005900 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00005901 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5902 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005903 if (Error != GE_None)
5904 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00005905
5906 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5907
Chris Lattner86df27b2009-06-14 00:45:47 +00005908 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00005909 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005910 if (Error != GE_None)
5911 return QualType();
5912
Chris Lattner14e0e742010-10-01 22:53:11 +00005913 // If this argument is required to be an IntegerConstantExpression and the
5914 // caller cares, fill in the bitmask we return.
5915 if (RequiresICE && IntegerConstantArgs)
5916 *IntegerConstantArgs |= 1 << ArgTypes.size();
5917
Chris Lattner86df27b2009-06-14 00:45:47 +00005918 // Do array -> pointer decay. The builtin should use the decayed type.
5919 if (Ty->isArrayType())
5920 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005921
Chris Lattner86df27b2009-06-14 00:45:47 +00005922 ArgTypes.push_back(Ty);
5923 }
5924
5925 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5926 "'.' should only occur at end of builtin type list!");
5927
John McCall00ccbef2010-12-21 00:44:39 +00005928 FunctionType::ExtInfo EI;
5929 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5930
5931 bool Variadic = (TypeStr[0] == '.');
5932
5933 // We really shouldn't be making a no-proto type here, especially in C++.
5934 if (ArgTypes.empty() && Variadic)
5935 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005936
John McCalle23cf432010-12-14 08:05:40 +00005937 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00005938 EPI.ExtInfo = EI;
5939 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00005940
5941 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00005942}
Eli Friedmana95d7572009-08-19 07:44:53 +00005943
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005944GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5945 GVALinkage External = GVA_StrongExternal;
5946
5947 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005948 switch (L) {
5949 case NoLinkage:
5950 case InternalLinkage:
5951 case UniqueExternalLinkage:
5952 return GVA_Internal;
5953
5954 case ExternalLinkage:
5955 switch (FD->getTemplateSpecializationKind()) {
5956 case TSK_Undeclared:
5957 case TSK_ExplicitSpecialization:
5958 External = GVA_StrongExternal;
5959 break;
5960
5961 case TSK_ExplicitInstantiationDefinition:
5962 return GVA_ExplicitTemplateInstantiation;
5963
5964 case TSK_ExplicitInstantiationDeclaration:
5965 case TSK_ImplicitInstantiation:
5966 External = GVA_TemplateInstantiation;
5967 break;
5968 }
5969 }
5970
5971 if (!FD->isInlined())
5972 return External;
5973
5974 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5975 // GNU or C99 inline semantics. Determine whether this symbol should be
5976 // externally visible.
5977 if (FD->isInlineDefinitionExternallyVisible())
5978 return External;
5979
5980 // C99 inline semantics, where the symbol is not externally visible.
5981 return GVA_C99Inline;
5982 }
5983
5984 // C++0x [temp.explicit]p9:
5985 // [ Note: The intent is that an inline function that is the subject of
5986 // an explicit instantiation declaration will still be implicitly
5987 // instantiated when used so that the body can be considered for
5988 // inlining, but that no out-of-line copy of the inline function would be
5989 // generated in the translation unit. -- end note ]
5990 if (FD->getTemplateSpecializationKind()
5991 == TSK_ExplicitInstantiationDeclaration)
5992 return GVA_C99Inline;
5993
5994 return GVA_CXXInline;
5995}
5996
5997GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5998 // If this is a static data member, compute the kind of template
5999 // specialization. Otherwise, this variable is not part of a
6000 // template.
6001 TemplateSpecializationKind TSK = TSK_Undeclared;
6002 if (VD->isStaticDataMember())
6003 TSK = VD->getTemplateSpecializationKind();
6004
6005 Linkage L = VD->getLinkage();
6006 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6007 VD->getType()->getLinkage() == UniqueExternalLinkage)
6008 L = UniqueExternalLinkage;
6009
6010 switch (L) {
6011 case NoLinkage:
6012 case InternalLinkage:
6013 case UniqueExternalLinkage:
6014 return GVA_Internal;
6015
6016 case ExternalLinkage:
6017 switch (TSK) {
6018 case TSK_Undeclared:
6019 case TSK_ExplicitSpecialization:
6020 return GVA_StrongExternal;
6021
6022 case TSK_ExplicitInstantiationDeclaration:
6023 llvm_unreachable("Variable should not be instantiated");
6024 // Fall through to treat this like any other instantiation.
6025
6026 case TSK_ExplicitInstantiationDefinition:
6027 return GVA_ExplicitTemplateInstantiation;
6028
6029 case TSK_ImplicitInstantiation:
6030 return GVA_TemplateInstantiation;
6031 }
6032 }
6033
6034 return GVA_StrongExternal;
6035}
6036
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006037bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006038 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6039 if (!VD->isFileVarDecl())
6040 return false;
6041 } else if (!isa<FunctionDecl>(D))
6042 return false;
6043
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006044 // Weak references don't produce any output by themselves.
6045 if (D->hasAttr<WeakRefAttr>())
6046 return false;
6047
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006048 // Aliases and used decls are required.
6049 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6050 return true;
6051
6052 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6053 // Forward declarations aren't required.
6054 if (!FD->isThisDeclarationADefinition())
6055 return false;
6056
6057 // Constructors and destructors are required.
6058 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6059 return true;
6060
6061 // The key function for a class is required.
6062 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6063 const CXXRecordDecl *RD = MD->getParent();
6064 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6065 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6066 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6067 return true;
6068 }
6069 }
6070
6071 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6072
6073 // static, static inline, always_inline, and extern inline functions can
6074 // always be deferred. Normal inline functions can be deferred in C99/C++.
6075 // Implicit template instantiations can also be deferred in C++.
6076 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6077 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6078 return false;
6079 return true;
6080 }
6081
6082 const VarDecl *VD = cast<VarDecl>(D);
6083 assert(VD->isFileVarDecl() && "Expected file scoped var");
6084
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006085 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6086 return false;
6087
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006088 // Structs that have non-trivial constructors or destructors are required.
6089
6090 // FIXME: Handle references.
6091 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6092 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00006093 if (RD->hasDefinition() &&
6094 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006095 return true;
6096 }
6097 }
6098
6099 GVALinkage L = GetGVALinkageForVariable(VD);
6100 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6101 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6102 return false;
6103 }
6104
6105 return true;
6106}
Charles Davis071cc7d2010-08-16 03:33:14 +00006107
Charles Davisee743f92010-11-09 18:04:24 +00006108CallingConv ASTContext::getDefaultMethodCallConv() {
6109 // Pass through to the C++ ABI object
6110 return ABI->getDefaultMethodCallConv();
6111}
6112
Jay Foad4ba2a172011-01-12 09:06:06 +00006113bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006114 // Pass through to the C++ ABI object
6115 return ABI->isNearlyEmpty(RD);
6116}
6117
Peter Collingbourne14110472011-01-13 18:57:25 +00006118MangleContext *ASTContext::createMangleContext() {
6119 switch (Target.getCXXABI()) {
6120 case CXXABI_ARM:
6121 case CXXABI_Itanium:
6122 return createItaniumMangleContext(*this, getDiagnostics());
6123 case CXXABI_Microsoft:
6124 return createMicrosoftMangleContext(*this, getDiagnostics());
6125 }
6126 assert(0 && "Unsupported ABI");
6127 return 0;
6128}
6129
Charles Davis071cc7d2010-08-16 03:33:14 +00006130CXXABI::~CXXABI() {}