blob: 4c42393365b7a35f3598ed08a254722d53d3bcdd [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"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000034#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000035
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
37
Douglas Gregor18274032010-07-03 00:47:00 +000038unsigned ASTContext::NumImplicitDefaultConstructors;
39unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000040unsigned ASTContext::NumImplicitCopyConstructors;
41unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000042unsigned ASTContext::NumImplicitMoveConstructors;
43unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000044unsigned ASTContext::NumImplicitCopyAssignmentOperators;
45unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveAssignmentOperators;
47unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000048unsigned ASTContext::NumImplicitDestructors;
49unsigned ASTContext::NumImplicitDestructorsDeclared;
50
Reid Spencer5f016e22007-07-11 17:01:13 +000051enum FloatingRank {
52 FloatRank, DoubleRank, LongDoubleRank
53};
54
Douglas Gregor3e1274f2010-06-16 21:09:37 +000055void
56ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
57 TemplateTemplateParmDecl *Parm) {
58 ID.AddInteger(Parm->getDepth());
59 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +000060 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000061
62 TemplateParameterList *Params = Parm->getTemplateParameters();
63 ID.AddInteger(Params->size());
64 for (TemplateParameterList::const_iterator P = Params->begin(),
65 PEnd = Params->end();
66 P != PEnd; ++P) {
67 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
68 ID.AddInteger(0);
69 ID.AddBoolean(TTP->isParameterPack());
70 continue;
71 }
72
73 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
74 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +000075 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000076 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000077 if (NTTP->isExpandedParameterPack()) {
78 ID.AddBoolean(true);
79 ID.AddInteger(NTTP->getNumExpansionTypes());
80 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
81 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
82 } else
83 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000084 continue;
85 }
86
87 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
88 ID.AddInteger(2);
89 Profile(ID, TTP);
90 }
91}
92
93TemplateTemplateParmDecl *
94ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000095 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000096 // Check if we already have a canonical template template parameter.
97 llvm::FoldingSetNodeID ID;
98 CanonicalTemplateTemplateParm::Profile(ID, TTP);
99 void *InsertPos = 0;
100 CanonicalTemplateTemplateParm *Canonical
101 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
102 if (Canonical)
103 return Canonical->getParam();
104
105 // Build a canonical template parameter list.
106 TemplateParameterList *Params = TTP->getTemplateParameters();
107 llvm::SmallVector<NamedDecl *, 4> CanonParams;
108 CanonParams.reserve(Params->size());
109 for (TemplateParameterList::const_iterator P = Params->begin(),
110 PEnd = Params->end();
111 P != PEnd; ++P) {
112 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
113 CanonParams.push_back(
114 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000115 SourceLocation(),
116 SourceLocation(),
117 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000118 TTP->getIndex(), 0, false,
119 TTP->isParameterPack()));
120 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000121 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
122 QualType T = getCanonicalType(NTTP->getType());
123 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
124 NonTypeTemplateParmDecl *Param;
125 if (NTTP->isExpandedParameterPack()) {
126 llvm::SmallVector<QualType, 2> ExpandedTypes;
127 llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
128 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
129 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
130 ExpandedTInfos.push_back(
131 getTrivialTypeSourceInfo(ExpandedTypes.back()));
132 }
133
134 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000135 SourceLocation(),
136 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000137 NTTP->getDepth(),
138 NTTP->getPosition(), 0,
139 T,
140 TInfo,
141 ExpandedTypes.data(),
142 ExpandedTypes.size(),
143 ExpandedTInfos.data());
144 } else {
145 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000146 SourceLocation(),
147 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000148 NTTP->getDepth(),
149 NTTP->getPosition(), 0,
150 T,
151 NTTP->isParameterPack(),
152 TInfo);
153 }
154 CanonParams.push_back(Param);
155
156 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000157 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
158 cast<TemplateTemplateParmDecl>(*P)));
159 }
160
161 TemplateTemplateParmDecl *CanonTTP
162 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
163 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000164 TTP->getPosition(),
165 TTP->isParameterPack(),
166 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000167 TemplateParameterList::Create(*this, SourceLocation(),
168 SourceLocation(),
169 CanonParams.data(),
170 CanonParams.size(),
171 SourceLocation()));
172
173 // Get the new insert position for the node we care about.
174 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
175 assert(Canonical == 0 && "Shouldn't be in the map!");
176 (void)Canonical;
177
178 // Create the canonical template template parameter entry.
179 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
180 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
181 return CanonTTP;
182}
183
Charles Davis071cc7d2010-08-16 03:33:14 +0000184CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000185 if (!LangOpts.CPlusPlus) return 0;
186
Charles Davis20cf7172010-08-19 02:18:14 +0000187 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000188 case CXXABI_ARM:
189 return CreateARMCXXABI(*this);
190 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000191 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000192 case CXXABI_Microsoft:
193 return CreateMicrosoftCXXABI(*this);
194 }
John McCallee79a4c2010-08-21 22:46:04 +0000195 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000196}
197
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000198static const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
199 const LangOptions &LOpts) {
200 if (LOpts.FakeAddressSpaceMap) {
201 // The fake address space map must have a distinct entry for each
202 // language-specific address space.
203 static const unsigned FakeAddrSpaceMap[] = {
204 1, // opencl_global
205 2, // opencl_local
206 3 // opencl_constant
207 };
208 return FakeAddrSpaceMap;
209 } else {
210 return T.getAddressSpaceMap();
211 }
212}
213
Chris Lattner61710852008-10-05 17:34:18 +0000214ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000215 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000216 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000217 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000218 unsigned size_reserve) :
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000219 FunctionProtoTypes(this_()),
John McCallef990012010-06-11 11:07:21 +0000220 TemplateSpecializationTypes(this_()),
221 DependentTemplateSpecializationTypes(this_()),
John McCall14606042011-06-30 08:33:18 +0000222 SubstTemplateTemplateParmPacks(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000223 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
224 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
John McCallf85e1932011-06-15 23:02:42 +0000225 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
226 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
227 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
John McCallbf1a0282010-06-04 23:28:52 +0000228 NullTypeSourceInfo(QualType()),
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000229 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
230 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000231 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000232 BuiltinInfo(builtins),
233 DeclarationNames(*this),
Argyrios Kyrtzidis9a44b5f2010-10-28 09:29:35 +0000234 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000235 LastSDM(0, 0),
John McCall8178df32011-02-22 22:38:33 +0000236 UniqueBlockByRefTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000237 ObjCIdRedefinitionType = QualType();
238 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000239 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000240 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000241 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000242 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000243}
244
Reid Spencer5f016e22007-07-11 17:01:13 +0000245ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000246 // Release the DenseMaps associated with DeclContext objects.
247 // FIXME: Is this the ideal solution?
248 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000249
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000250 // Call all of the deallocation functions.
251 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
252 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000253
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000254 // Release all of the memory associated with overridden C++ methods.
255 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
256 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
257 OM != OMEnd; ++OM)
258 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000259
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000260 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000261 // because they can contain DenseMaps.
262 for (llvm::DenseMap<const ObjCContainerDecl*,
263 const ASTRecordLayout*>::iterator
264 I = ObjCLayouts.begin(), E = ObjCLayouts.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
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000269 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
270 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
271 // Increment in loop to prevent using deallocated memory.
272 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
273 R->Destroy(*this);
274 }
Douglas Gregor63200642010-08-30 16:49:28 +0000275
276 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
277 AEnd = DeclAttrs.end();
278 A != AEnd; ++A)
279 A->second->~AttrVec();
280}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000281
Douglas Gregor00545312010-05-23 18:26:36 +0000282void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
283 Deallocations.push_back(std::make_pair(Callback, Data));
284}
285
Mike Stump1eb44332009-09-09 15:08:12 +0000286void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000287ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
288 ExternalSource.reset(Source.take());
289}
290
Reid Spencer5f016e22007-07-11 17:01:13 +0000291void ASTContext::PrintStats() const {
292 fprintf(stderr, "*** AST Context Stats:\n");
293 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000294
Douglas Gregordbe833d2009-05-26 14:40:08 +0000295 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000296#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000297#define ABSTRACT_TYPE(Name, Parent)
298#include "clang/AST/TypeNodes.def"
299 0 // Extra
300 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000301
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
303 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000304 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000305 }
306
Douglas Gregordbe833d2009-05-26 14:40:08 +0000307 unsigned Idx = 0;
308 unsigned TotalBytes = 0;
309#define TYPE(Name, Parent) \
310 if (counts[Idx]) \
311 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
312 TotalBytes += counts[Idx] * sizeof(Name##Type); \
313 ++Idx;
314#define ABSTRACT_TYPE(Name, Parent)
315#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Douglas Gregordbe833d2009-05-26 14:40:08 +0000317 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000318
Douglas Gregor4923aa22010-07-02 20:37:36 +0000319 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000320 fprintf(stderr, " %u/%u implicit default constructors created\n",
321 NumImplicitDefaultConstructorsDeclared,
322 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000323 fprintf(stderr, " %u/%u implicit copy constructors created\n",
324 NumImplicitCopyConstructorsDeclared,
325 NumImplicitCopyConstructors);
Sean Huntffe37fd2011-05-25 20:50:04 +0000326 if (getLangOptions().CPlusPlus)
327 fprintf(stderr, " %u/%u implicit move constructors created\n",
328 NumImplicitMoveConstructorsDeclared,
329 NumImplicitMoveConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000330 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
331 NumImplicitCopyAssignmentOperatorsDeclared,
332 NumImplicitCopyAssignmentOperators);
Sean Huntffe37fd2011-05-25 20:50:04 +0000333 if (getLangOptions().CPlusPlus)
334 fprintf(stderr, " %u/%u implicit move assignment operators created\n",
335 NumImplicitMoveAssignmentOperatorsDeclared,
336 NumImplicitMoveAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000337 fprintf(stderr, " %u/%u implicit destructors created\n",
338 NumImplicitDestructorsDeclared, NumImplicitDestructors);
339
Douglas Gregor2cf26342009-04-09 22:27:44 +0000340 if (ExternalSource.get()) {
341 fprintf(stderr, "\n");
342 ExternalSource->PrintStats();
343 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000344
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000345 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000346}
347
348
John McCalle27ec8a2009-10-23 23:03:21 +0000349void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000350 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000351 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000352 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000353}
354
Reid Spencer5f016e22007-07-11 17:01:13 +0000355void ASTContext::InitBuiltinTypes() {
356 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 // C99 6.2.5p19.
359 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // C99 6.2.5p2.
362 InitBuiltinType(BoolTy, BuiltinType::Bool);
363 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000364 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 InitBuiltinType(CharTy, BuiltinType::Char_S);
366 else
367 InitBuiltinType(CharTy, BuiltinType::Char_U);
368 // C99 6.2.5p4.
369 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
370 InitBuiltinType(ShortTy, BuiltinType::Short);
371 InitBuiltinType(IntTy, BuiltinType::Int);
372 InitBuiltinType(LongTy, BuiltinType::Long);
373 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 // C99 6.2.5p6.
376 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
377 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
378 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
379 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
380 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 // C99 6.2.5p10.
383 InitBuiltinType(FloatTy, BuiltinType::Float);
384 InitBuiltinType(DoubleTy, BuiltinType::Double);
385 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000386
Chris Lattner2df9ced2009-04-30 02:43:43 +0000387 // GNU extension, 128-bit integers.
388 InitBuiltinType(Int128Ty, BuiltinType::Int128);
389 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
390
Chris Lattner3f59c972010-12-25 23:25:43 +0000391 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000392 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000393 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
394 else // -fshort-wchar makes wchar_t be unsigned.
395 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
396 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000397 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000398
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000399 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
400 InitBuiltinType(Char16Ty, BuiltinType::Char16);
401 else // C99
402 Char16Ty = getFromTargetType(Target.getChar16Type());
403
404 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
405 InitBuiltinType(Char32Ty, BuiltinType::Char32);
406 else // C99
407 Char32Ty = getFromTargetType(Target.getChar32Type());
408
Douglas Gregor898574e2008-12-05 23:32:09 +0000409 // Placeholder type for type-dependent expressions whose type is
410 // completely unknown. No code should ever check a type against
411 // DependentTy and users should never see it; however, it is here to
412 // help diagnose failures to properly check for type-dependent
413 // expressions.
414 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000415
John McCall2a984ca2010-10-12 00:20:44 +0000416 // Placeholder type for functions.
417 InitBuiltinType(OverloadTy, BuiltinType::Overload);
418
John McCall864c0412011-04-26 20:42:42 +0000419 // Placeholder type for bound members.
420 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
421
John McCall1de4d4e2011-04-07 08:22:57 +0000422 // "any" type; useful for debugger-like clients.
423 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
424
Reid Spencer5f016e22007-07-11 17:01:13 +0000425 // C99 6.2.5p11.
426 FloatComplexTy = getComplexType(FloatTy);
427 DoubleComplexTy = getComplexType(DoubleTy);
428 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000429
Steve Naroff7e219e42007-10-15 14:41:52 +0000430 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Steve Naroffde2e22d2009-07-15 18:40:39 +0000432 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
433 ObjCIdTypedefType = QualType();
434 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000435 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000437 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000438 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
439 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000440 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000441
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000442 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000444 // void * type
445 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000446
447 // nullptr type (C++0x 2.14.7)
448 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000449}
450
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000451Diagnostic &ASTContext::getDiagnostics() const {
452 return SourceMgr.getDiagnostics();
453}
454
Douglas Gregor63200642010-08-30 16:49:28 +0000455AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
456 AttrVec *&Result = DeclAttrs[D];
457 if (!Result) {
458 void *Mem = Allocate(sizeof(AttrVec));
459 Result = new (Mem) AttrVec;
460 }
461
462 return *Result;
463}
464
465/// \brief Erase the attributes corresponding to the given declaration.
466void ASTContext::eraseDeclAttrs(const Decl *D) {
467 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
468 if (Pos != DeclAttrs.end()) {
469 Pos->second->~AttrVec();
470 DeclAttrs.erase(Pos);
471 }
472}
473
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000474MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000475ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000476 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000477 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000478 = InstantiatedFromStaticDataMember.find(Var);
479 if (Pos == InstantiatedFromStaticDataMember.end())
480 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Douglas Gregor7caa6822009-07-24 20:34:43 +0000482 return Pos->second;
483}
484
Mike Stump1eb44332009-09-09 15:08:12 +0000485void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000486ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000487 TemplateSpecializationKind TSK,
488 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000489 assert(Inst->isStaticDataMember() && "Not a static data member");
490 assert(Tmpl->isStaticDataMember() && "Not a static data member");
491 assert(!InstantiatedFromStaticDataMember[Inst] &&
492 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000493 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000494 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000495}
496
John McCall7ba107a2009-11-18 02:36:19 +0000497NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000498ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000499 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000500 = InstantiatedFromUsingDecl.find(UUD);
501 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000502 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Anders Carlsson0d8df782009-08-29 19:37:28 +0000504 return Pos->second;
505}
506
507void
John McCalled976492009-12-04 22:46:56 +0000508ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
509 assert((isa<UsingDecl>(Pattern) ||
510 isa<UnresolvedUsingValueDecl>(Pattern) ||
511 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
512 "pattern decl is not a using decl");
513 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
514 InstantiatedFromUsingDecl[Inst] = Pattern;
515}
516
517UsingShadowDecl *
518ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
519 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
520 = InstantiatedFromUsingShadowDecl.find(Inst);
521 if (Pos == InstantiatedFromUsingShadowDecl.end())
522 return 0;
523
524 return Pos->second;
525}
526
527void
528ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
529 UsingShadowDecl *Pattern) {
530 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
531 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000532}
533
Anders Carlssond8b285f2009-09-01 04:26:58 +0000534FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
535 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
536 = InstantiatedFromUnnamedFieldDecl.find(Field);
537 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
538 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Anders Carlssond8b285f2009-09-01 04:26:58 +0000540 return Pos->second;
541}
542
543void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
544 FieldDecl *Tmpl) {
545 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
546 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
547 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
548 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Anders Carlssond8b285f2009-09-01 04:26:58 +0000550 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
551}
552
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000553bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
554 const FieldDecl *LastFD) const {
555 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
556 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0);
557
558}
559
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000560bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
561 const FieldDecl *LastFD) const {
562 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Fariborz Jahaniancc0f9f12011-05-03 22:07:14 +0000563 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0 &&
564 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000565
566}
567
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000568bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
569 const FieldDecl *LastFD) const {
570 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
571 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() &&
572 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
573}
574
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000575bool ASTContext::NoneBitfieldFollowsBitfield(const FieldDecl *FD,
576 const FieldDecl *LastFD) const {
577 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
578 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
579}
580
581bool ASTContext::BitfieldFollowsNoneBitfield(const FieldDecl *FD,
582 const FieldDecl *LastFD) const {
583 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
584 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
585}
586
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000587ASTContext::overridden_cxx_method_iterator
588ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
589 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
590 = OverriddenMethods.find(Method);
591 if (Pos == OverriddenMethods.end())
592 return 0;
593
594 return Pos->second.begin();
595}
596
597ASTContext::overridden_cxx_method_iterator
598ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
599 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
600 = OverriddenMethods.find(Method);
601 if (Pos == OverriddenMethods.end())
602 return 0;
603
604 return Pos->second.end();
605}
606
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000607unsigned
608ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
609 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
610 = OverriddenMethods.find(Method);
611 if (Pos == OverriddenMethods.end())
612 return 0;
613
614 return Pos->second.size();
615}
616
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000617void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
618 const CXXMethodDecl *Overridden) {
619 OverriddenMethods[Method].push_back(Overridden);
620}
621
Chris Lattner464175b2007-07-18 17:52:12 +0000622//===----------------------------------------------------------------------===//
623// Type Sizing and Analysis
624//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000625
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000626/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
627/// scalar floating point type.
628const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000629 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000630 assert(BT && "Not a floating point type!");
631 switch (BT->getKind()) {
632 default: assert(0 && "Not a floating point type!");
633 case BuiltinType::Float: return Target.getFloatFormat();
634 case BuiltinType::Double: return Target.getDoubleFormat();
635 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
636 }
637}
638
Ken Dyck8b752f12010-01-27 17:10:57 +0000639/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000640/// specified decl. Note that bitfields do not have a valid alignment, so
641/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000642/// If @p RefAsPointee, references are treated like their underlying type
643/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000644CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000645 unsigned Align = Target.getCharWidth();
646
John McCall4081a5c2010-10-08 18:24:19 +0000647 bool UseAlignAttrOnly = false;
648 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
649 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000650
John McCall4081a5c2010-10-08 18:24:19 +0000651 // __attribute__((aligned)) can increase or decrease alignment
652 // *except* on a struct or struct member, where it only increases
653 // alignment unless 'packed' is also specified.
654 //
655 // It is an error for [[align]] to decrease alignment, so we can
656 // ignore that possibility; Sema should diagnose it.
657 if (isa<FieldDecl>(D)) {
658 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
659 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
660 } else {
661 UseAlignAttrOnly = true;
662 }
663 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000664 else if (isa<FieldDecl>(D))
665 UseAlignAttrOnly =
666 D->hasAttr<PackedAttr>() ||
667 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000668
John McCallba4f5d52011-01-20 07:57:12 +0000669 // If we're using the align attribute only, just ignore everything
670 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000671 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000672 // do nothing
673
John McCall4081a5c2010-10-08 18:24:19 +0000674 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000675 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000676 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000677 if (RefAsPointee)
678 T = RT->getPointeeType();
679 else
680 T = getPointerType(RT->getPointeeType());
681 }
682 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000683 // Adjust alignments of declarations with array type by the
684 // large-array alignment on the target.
Rafael Espindola6deecb02010-06-04 23:15:27 +0000685 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000686 const ArrayType *arrayType;
687 if (MinWidth && (arrayType = getAsArrayType(T))) {
688 if (isa<VariableArrayType>(arrayType))
689 Align = std::max(Align, Target.getLargeArrayAlign());
690 else if (isa<ConstantArrayType>(arrayType) &&
691 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
692 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000693
John McCall3b657512011-01-19 10:06:00 +0000694 // Walk through any array types while we're at it.
695 T = getBaseElementType(arrayType);
696 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000697 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
698 }
John McCallba4f5d52011-01-20 07:57:12 +0000699
700 // Fields can be subject to extra alignment constraints, like if
701 // the field is packed, the struct is packed, or the struct has a
702 // a max-field-alignment constraint (#pragma pack). So calculate
703 // the actual alignment of the field within the struct, and then
704 // (as we're expected to) constrain that by the alignment of the type.
705 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
706 // So calculate the alignment of the field.
707 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
708
709 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000710 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000711
712 // Use the GCD of that and the offset within the record.
713 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
714 if (offset > 0) {
715 // Alignment is always a power of 2, so the GCD will be a power of 2,
716 // which means we get to do this crazy thing instead of Euclid's.
717 uint64_t lowBitOfOffset = offset & (~offset + 1);
718 if (lowBitOfOffset < fieldAlign)
719 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
720 }
721
722 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000723 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000724 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000725
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000726 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000727}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000728
John McCallea1471e2010-05-20 01:18:31 +0000729std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000730ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000731 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000732 return std::make_pair(toCharUnitsFromBits(Info.first),
733 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000734}
735
736std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000737ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000738 return getTypeInfoInChars(T.getTypePtr());
739}
740
Chris Lattnera7674d82007-07-13 22:13:22 +0000741/// getTypeSize - Return the size of the specified type, in bits. This method
742/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000743///
744/// FIXME: Pointers into different addr spaces could have different sizes and
745/// alignment requirements: getPointerInfo should take an AddrSpace, this
746/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000747std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000748ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000749 uint64_t Width=0;
750 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000751 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000752#define TYPE(Class, Base)
753#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000754#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000755#define DEPENDENT_TYPE(Class, Base) case Type::Class:
756#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000757 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000758 break;
759
Chris Lattner692233e2007-07-13 22:27:08 +0000760 case Type::FunctionNoProto:
761 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000762 // GCC extension: alignof(function) = 32 bits
763 Width = 0;
764 Align = 32;
765 break;
766
Douglas Gregor72564e72009-02-26 23:50:07 +0000767 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000768 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000769 Width = 0;
770 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
771 break;
772
Steve Narofffb22d962007-08-30 01:06:46 +0000773 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000774 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Chris Lattner98be4942008-03-05 18:54:05 +0000776 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000777 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000778 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000779 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000780 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000781 }
Nate Begeman213541a2008-04-18 23:10:10 +0000782 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000783 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000784 const VectorType *VT = cast<VectorType>(T);
785 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
786 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000787 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000788 // If the alignment is not a power of 2, round up to the next power of 2.
789 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000790 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000791 Align = llvm::NextPowerOf2(Align);
792 Width = llvm::RoundUpToAlignment(Width, Align);
793 }
Chris Lattner030d8842007-07-19 22:06:24 +0000794 break;
795 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000796
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000797 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000798 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000799 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000800 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000801 // GCC extension: alignof(void) = 8 bits.
802 Width = 0;
803 Align = 8;
804 break;
805
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000806 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000807 Width = Target.getBoolWidth();
808 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000809 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000810 case BuiltinType::Char_S:
811 case BuiltinType::Char_U:
812 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000813 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000814 Width = Target.getCharWidth();
815 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000816 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000817 case BuiltinType::WChar_S:
818 case BuiltinType::WChar_U:
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000819 Width = Target.getWCharWidth();
820 Align = Target.getWCharAlign();
821 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000822 case BuiltinType::Char16:
823 Width = Target.getChar16Width();
824 Align = Target.getChar16Align();
825 break;
826 case BuiltinType::Char32:
827 Width = Target.getChar32Width();
828 Align = Target.getChar32Align();
829 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000830 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000831 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000832 Width = Target.getShortWidth();
833 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000834 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000835 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000836 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000837 Width = Target.getIntWidth();
838 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000839 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000840 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000841 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000842 Width = Target.getLongWidth();
843 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000844 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000845 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000846 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000847 Width = Target.getLongLongWidth();
848 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000849 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000850 case BuiltinType::Int128:
851 case BuiltinType::UInt128:
852 Width = 128;
853 Align = 128; // int128_t is 128-bit aligned on all targets.
854 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000855 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000856 Width = Target.getFloatWidth();
857 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000858 break;
859 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000860 Width = Target.getDoubleWidth();
861 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000862 break;
863 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000864 Width = Target.getLongDoubleWidth();
865 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000866 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000867 case BuiltinType::NullPtr:
868 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
869 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000870 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000871 case BuiltinType::ObjCId:
872 case BuiltinType::ObjCClass:
873 case BuiltinType::ObjCSel:
874 Width = Target.getPointerWidth(0);
875 Align = Target.getPointerAlign(0);
876 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000877 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000878 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000879 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000880 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000881 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000882 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000883 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000884 unsigned AS = getTargetAddressSpace(
885 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff485eeff2008-09-24 15:05:44 +0000886 Width = Target.getPointerWidth(AS);
887 Align = Target.getPointerAlign(AS);
888 break;
889 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000890 case Type::LValueReference:
891 case Type::RValueReference: {
892 // alignof and sizeof should never enter this code path here, so we go
893 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000894 unsigned AS = getTargetAddressSpace(
895 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl5d484e82009-11-23 17:18:46 +0000896 Width = Target.getPointerWidth(AS);
897 Align = Target.getPointerAlign(AS);
898 break;
899 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000900 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000901 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner5426bf62008-04-07 07:01:58 +0000902 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000903 Align = Target.getPointerAlign(AS);
904 break;
905 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000906 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000907 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000908 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000909 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000910 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000911 Align = PtrDiffInfo.second;
912 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000913 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000914 case Type::Complex: {
915 // Complex types have the same alignment as their elements, but twice the
916 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000917 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000918 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000919 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000920 Align = EltInfo.second;
921 break;
922 }
John McCallc12c5bb2010-05-15 11:32:37 +0000923 case Type::ObjCObject:
924 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000925 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000926 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000927 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000928 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000929 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +0000930 break;
931 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000932 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000933 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000934 const TagType *TT = cast<TagType>(T);
935
936 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +0000937 Width = 8;
938 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +0000939 break;
940 }
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Daniel Dunbar1d751182008-11-08 05:48:37 +0000942 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000943 return getTypeInfo(ET->getDecl()->getIntegerType());
944
Daniel Dunbar1d751182008-11-08 05:48:37 +0000945 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000946 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000947 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000948 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000949 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000950 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000951
Chris Lattner9fcfe922009-10-22 05:17:15 +0000952 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000953 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
954 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000955
Richard Smith34b41d92011-02-20 03:19:35 +0000956 case Type::Auto: {
957 const AutoType *A = cast<AutoType>(T);
958 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +0000959 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +0000960 }
961
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000962 case Type::Paren:
963 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
964
Douglas Gregor18857642009-04-30 17:32:17 +0000965 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +0000966 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000967 std::pair<uint64_t, unsigned> Info
968 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +0000969 // If the typedef has an aligned attribute on it, it overrides any computed
970 // alignment we have. This violates the GCC documentation (which says that
971 // attribute(aligned) can only round up) but matches its implementation.
972 if (unsigned AttrAlign = Typedef->getMaxAlignment())
973 Align = AttrAlign;
974 else
975 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +0000976 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000977 break;
Chris Lattner71763312008-04-06 22:05:18 +0000978 }
Douglas Gregor18857642009-04-30 17:32:17 +0000979
980 case Type::TypeOfExpr:
981 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
982 .getTypePtr());
983
984 case Type::TypeOf:
985 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
986
Anders Carlsson395b4752009-06-24 19:06:50 +0000987 case Type::Decltype:
988 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
989 .getTypePtr());
990
Sean Huntca63c202011-05-24 22:41:36 +0000991 case Type::UnaryTransform:
992 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
993
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000994 case Type::Elaborated:
995 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000996
John McCall9d156a72011-01-06 01:58:22 +0000997 case Type::Attributed:
998 return getTypeInfo(
999 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1000
Richard Smith3e4c6c42011-05-05 21:57:07 +00001001 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001002 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001003 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001004 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1005 // A type alias template specialization may refer to a typedef with the
1006 // aligned attribute on it.
1007 if (TST->isTypeAlias())
1008 return getTypeInfo(TST->getAliasedType().getTypePtr());
1009 else
1010 return getTypeInfo(getCanonicalType(T));
1011 }
1012
Douglas Gregor18857642009-04-30 17:32:17 +00001013 }
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Chris Lattner464175b2007-07-18 17:52:12 +00001015 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001016 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001017}
1018
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001019/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1020CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1021 return CharUnits::fromQuantity(BitSize / getCharWidth());
1022}
1023
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001024/// toBits - Convert a size in characters to a size in characters.
1025int64_t ASTContext::toBits(CharUnits CharSize) const {
1026 return CharSize.getQuantity() * getCharWidth();
1027}
1028
Ken Dyckbdc601b2009-12-22 14:23:30 +00001029/// getTypeSizeInChars - Return the size of the specified type, in characters.
1030/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001031CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001032 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001033}
Jay Foad4ba2a172011-01-12 09:06:06 +00001034CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001035 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001036}
1037
Ken Dyck16e20cc2010-01-26 17:25:18 +00001038/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001039/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001040CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001041 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001042}
Jay Foad4ba2a172011-01-12 09:06:06 +00001043CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001044 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001045}
1046
Chris Lattner34ebde42009-01-27 18:08:34 +00001047/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1048/// type for the current target in bits. This can be different than the ABI
1049/// alignment in cases where it is beneficial for performance to overalign
1050/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001051unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001052 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001053
1054 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001055 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001056 T = CT->getElementType().getTypePtr();
1057 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1058 T->isSpecificBuiltinType(BuiltinType::LongLong))
1059 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1060
Chris Lattner34ebde42009-01-27 18:08:34 +00001061 return ABIAlign;
1062}
1063
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001064/// ShallowCollectObjCIvars -
1065/// Collect all ivars, including those synthesized, in the current class.
1066///
1067void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad4ba2a172011-01-12 09:06:06 +00001068 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001069 // FIXME. This need be removed but there are two many places which
1070 // assume const-ness of ObjCInterfaceDecl
1071 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1072 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1073 Iv= Iv->getNextIvar())
1074 Ivars.push_back(Iv);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001075}
1076
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001077/// DeepCollectObjCIvars -
1078/// This routine first collects all declared, but not synthesized, ivars in
1079/// super class and then collects all ivars, including those synthesized for
1080/// current class. This routine is used for implementation of current class
1081/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001082///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001083void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1084 bool leafClass,
Jay Foad4ba2a172011-01-12 09:06:06 +00001085 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001086 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1087 DeepCollectObjCIvars(SuperClass, false, Ivars);
1088 if (!leafClass) {
1089 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1090 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001091 Ivars.push_back(*I);
1092 }
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001093 else {
1094 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1095 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1096 Iv= Iv->getNextIvar())
1097 Ivars.push_back(Iv);
1098 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001099}
1100
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001101/// CollectInheritedProtocols - Collect all protocols in current class and
1102/// those inherited by it.
1103void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001104 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001105 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001106 // We can use protocol_iterator here instead of
1107 // all_referenced_protocol_iterator since we are walking all categories.
1108 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1109 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001110 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001111 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001112 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001113 PE = Proto->protocol_end(); P != PE; ++P) {
1114 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001115 CollectInheritedProtocols(*P, Protocols);
1116 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001117 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001118
1119 // Categories of this Interface.
1120 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1121 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1122 CollectInheritedProtocols(CDeclChain, Protocols);
1123 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1124 while (SD) {
1125 CollectInheritedProtocols(SD, Protocols);
1126 SD = SD->getSuperClass();
1127 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001128 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001129 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001130 PE = OC->protocol_end(); P != PE; ++P) {
1131 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001132 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001133 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1134 PE = Proto->protocol_end(); P != PE; ++P)
1135 CollectInheritedProtocols(*P, Protocols);
1136 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001137 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001138 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1139 PE = OP->protocol_end(); P != PE; ++P) {
1140 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001141 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001142 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1143 PE = Proto->protocol_end(); P != PE; ++P)
1144 CollectInheritedProtocols(*P, Protocols);
1145 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001146 }
1147}
1148
Jay Foad4ba2a172011-01-12 09:06:06 +00001149unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001150 unsigned count = 0;
1151 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001152 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1153 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001154 count += CDecl->ivar_size();
1155
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001156 // Count ivar defined in this class's implementation. This
1157 // includes synthesized ivars.
1158 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001159 count += ImplDecl->ivar_size();
1160
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001161 return count;
1162}
1163
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001164/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1165ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1166 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1167 I = ObjCImpls.find(D);
1168 if (I != ObjCImpls.end())
1169 return cast<ObjCImplementationDecl>(I->second);
1170 return 0;
1171}
1172/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1173ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1174 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1175 I = ObjCImpls.find(D);
1176 if (I != ObjCImpls.end())
1177 return cast<ObjCCategoryImplDecl>(I->second);
1178 return 0;
1179}
1180
1181/// \brief Set the implementation of ObjCInterfaceDecl.
1182void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1183 ObjCImplementationDecl *ImplD) {
1184 assert(IFaceD && ImplD && "Passed null params");
1185 ObjCImpls[IFaceD] = ImplD;
1186}
1187/// \brief Set the implementation of ObjCCategoryDecl.
1188void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1189 ObjCCategoryImplDecl *ImplD) {
1190 assert(CatD && ImplD && "Passed null params");
1191 ObjCImpls[CatD] = ImplD;
1192}
1193
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001194/// \brief Get the copy initialization expression of VarDecl,or NULL if
1195/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001196Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001197 assert(VD && "Passed null params");
1198 assert(VD->hasAttr<BlocksAttr>() &&
1199 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001200 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001201 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001202 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1203}
1204
1205/// \brief Set the copy inialization expression of a block var decl.
1206void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1207 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001208 assert(VD->hasAttr<BlocksAttr>() &&
1209 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001210 BlockVarCopyInits[VD] = Init;
1211}
1212
John McCalla93c9342009-12-07 02:54:59 +00001213/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001214///
John McCalla93c9342009-12-07 02:54:59 +00001215/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001216/// the TypeLoc wrappers.
1217///
1218/// \param T the type that will be the basis for type source info. This type
1219/// should refer to how the declarator was written in source code, not to
1220/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001221TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001222 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001223 if (!DataSize)
1224 DataSize = TypeLoc::getFullDataSizeForType(T);
1225 else
1226 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001227 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001228
John McCalla93c9342009-12-07 02:54:59 +00001229 TypeSourceInfo *TInfo =
1230 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1231 new (TInfo) TypeSourceInfo(T);
1232 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001233}
1234
John McCalla93c9342009-12-07 02:54:59 +00001235TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001236 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001237 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001238 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001239 return DI;
1240}
1241
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001242const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001243ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001244 return getObjCLayout(D, 0);
1245}
1246
1247const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001248ASTContext::getASTObjCImplementationLayout(
1249 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001250 return getObjCLayout(D->getClassInterface(), D);
1251}
1252
Chris Lattnera7674d82007-07-13 22:13:22 +00001253//===----------------------------------------------------------------------===//
1254// Type creation/memoization methods
1255//===----------------------------------------------------------------------===//
1256
Jay Foad4ba2a172011-01-12 09:06:06 +00001257QualType
John McCall3b657512011-01-19 10:06:00 +00001258ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1259 unsigned fastQuals = quals.getFastQualifiers();
1260 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001261
1262 // Check if we've already instantiated this type.
1263 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001264 ExtQuals::Profile(ID, baseType, quals);
1265 void *insertPos = 0;
1266 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1267 assert(eq->getQualifiers() == quals);
1268 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001269 }
1270
John McCall3b657512011-01-19 10:06:00 +00001271 // If the base type is not canonical, make the appropriate canonical type.
1272 QualType canon;
1273 if (!baseType->isCanonicalUnqualified()) {
1274 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1275 canonSplit.second.addConsistentQualifiers(quals);
1276 canon = getExtQualType(canonSplit.first, canonSplit.second);
1277
1278 // Re-find the insert position.
1279 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1280 }
1281
1282 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1283 ExtQualNodes.InsertNode(eq, insertPos);
1284 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001285}
1286
Jay Foad4ba2a172011-01-12 09:06:06 +00001287QualType
1288ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001289 QualType CanT = getCanonicalType(T);
1290 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001291 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001292
John McCall0953e762009-09-24 19:53:00 +00001293 // If we are composing extended qualifiers together, merge together
1294 // into one ExtQuals node.
1295 QualifierCollector Quals;
1296 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001297
John McCall0953e762009-09-24 19:53:00 +00001298 // If this type already has an address space specified, it cannot get
1299 // another one.
1300 assert(!Quals.hasAddressSpace() &&
1301 "Type cannot be in multiple addr spaces!");
1302 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001303
John McCall0953e762009-09-24 19:53:00 +00001304 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001305}
1306
Chris Lattnerb7d25532009-02-18 22:53:11 +00001307QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001308 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001309 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001310 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001311 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001312
John McCall7f040a92010-12-24 02:08:15 +00001313 if (const PointerType *ptr = T->getAs<PointerType>()) {
1314 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001315 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001316 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1317 return getPointerType(ResultType);
1318 }
1319 }
Mike Stump1eb44332009-09-09 15:08:12 +00001320
John McCall0953e762009-09-24 19:53:00 +00001321 // If we are composing extended qualifiers together, merge together
1322 // into one ExtQuals node.
1323 QualifierCollector Quals;
1324 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001325
John McCall0953e762009-09-24 19:53:00 +00001326 // If this type already has an ObjCGC specified, it cannot get
1327 // another one.
1328 assert(!Quals.hasObjCGCAttr() &&
1329 "Type cannot have multiple ObjCGCs!");
1330 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001331
John McCall0953e762009-09-24 19:53:00 +00001332 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001333}
Chris Lattnera7674d82007-07-13 22:13:22 +00001334
John McCalle6a365d2010-12-19 02:44:49 +00001335const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1336 FunctionType::ExtInfo Info) {
1337 if (T->getExtInfo() == Info)
1338 return T;
1339
1340 QualType Result;
1341 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1342 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1343 } else {
1344 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1345 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1346 EPI.ExtInfo = Info;
1347 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1348 FPT->getNumArgs(), EPI);
1349 }
1350
1351 return cast<FunctionType>(Result.getTypePtr());
1352}
1353
Reid Spencer5f016e22007-07-11 17:01:13 +00001354/// getComplexType - Return the uniqued reference to the type for a complex
1355/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001356QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 // Unique pointers, to guarantee there is only one pointer of a particular
1358 // structure.
1359 llvm::FoldingSetNodeID ID;
1360 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 void *InsertPos = 0;
1363 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1364 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 // If the pointee type isn't canonical, this won't be a canonical type either,
1367 // so fill in the canonical type field.
1368 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001369 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001370 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Reid Spencer5f016e22007-07-11 17:01:13 +00001372 // Get the new insert position for the node we care about.
1373 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001374 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 }
John McCall6b304a02009-09-24 23:30:46 +00001376 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 Types.push_back(New);
1378 ComplexTypes.InsertNode(New, InsertPos);
1379 return QualType(New, 0);
1380}
1381
Reid Spencer5f016e22007-07-11 17:01:13 +00001382/// getPointerType - Return the uniqued reference to the type for a pointer to
1383/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001384QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 // Unique pointers, to guarantee there is only one pointer of a particular
1386 // structure.
1387 llvm::FoldingSetNodeID ID;
1388 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001389
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 void *InsertPos = 0;
1391 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1392 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 // If the pointee type isn't canonical, this won't be a canonical type either,
1395 // so fill in the canonical type field.
1396 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001397 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001398 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 // Get the new insert position for the node we care about.
1401 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001402 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 }
John McCall6b304a02009-09-24 23:30:46 +00001404 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 Types.push_back(New);
1406 PointerTypes.InsertNode(New, InsertPos);
1407 return QualType(New, 0);
1408}
1409
Mike Stump1eb44332009-09-09 15:08:12 +00001410/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001411/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001412QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001413 assert(T->isFunctionType() && "block of function types only");
1414 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001415 // structure.
1416 llvm::FoldingSetNodeID ID;
1417 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Steve Naroff5618bd42008-08-27 16:04:49 +00001419 void *InsertPos = 0;
1420 if (BlockPointerType *PT =
1421 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1422 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001423
1424 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001425 // type either so fill in the canonical type field.
1426 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001427 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001428 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Steve Naroff5618bd42008-08-27 16:04:49 +00001430 // Get the new insert position for the node we care about.
1431 BlockPointerType *NewIP =
1432 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001433 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001434 }
John McCall6b304a02009-09-24 23:30:46 +00001435 BlockPointerType *New
1436 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001437 Types.push_back(New);
1438 BlockPointerTypes.InsertNode(New, InsertPos);
1439 return QualType(New, 0);
1440}
1441
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001442/// getLValueReferenceType - Return the uniqued reference to the type for an
1443/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001444QualType
1445ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001446 assert(getCanonicalType(T) != OverloadTy &&
1447 "Unresolved overloaded function type");
1448
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 // Unique pointers, to guarantee there is only one pointer of a particular
1450 // structure.
1451 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001452 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001453
1454 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001455 if (LValueReferenceType *RT =
1456 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001457 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001458
John McCall54e14c42009-10-22 22:37:11 +00001459 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1460
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 // If the referencee type isn't canonical, this won't be a canonical type
1462 // either, so fill in the canonical type field.
1463 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001464 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1465 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1466 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001467
Reid Spencer5f016e22007-07-11 17:01:13 +00001468 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001469 LValueReferenceType *NewIP =
1470 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001471 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 }
1473
John McCall6b304a02009-09-24 23:30:46 +00001474 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001475 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1476 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001477 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001478 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001479
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001480 return QualType(New, 0);
1481}
1482
1483/// getRValueReferenceType - Return the uniqued reference to the type for an
1484/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001485QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001486 // Unique pointers, to guarantee there is only one pointer of a particular
1487 // structure.
1488 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001489 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001490
1491 void *InsertPos = 0;
1492 if (RValueReferenceType *RT =
1493 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1494 return QualType(RT, 0);
1495
John McCall54e14c42009-10-22 22:37:11 +00001496 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1497
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001498 // If the referencee type isn't canonical, this won't be a canonical type
1499 // either, so fill in the canonical type field.
1500 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001501 if (InnerRef || !T.isCanonical()) {
1502 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1503 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001504
1505 // Get the new insert position for the node we care about.
1506 RValueReferenceType *NewIP =
1507 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001508 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001509 }
1510
John McCall6b304a02009-09-24 23:30:46 +00001511 RValueReferenceType *New
1512 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001513 Types.push_back(New);
1514 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 return QualType(New, 0);
1516}
1517
Sebastian Redlf30208a2009-01-24 21:16:55 +00001518/// getMemberPointerType - Return the uniqued reference to the type for a
1519/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001520QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001521 // Unique pointers, to guarantee there is only one pointer of a particular
1522 // structure.
1523 llvm::FoldingSetNodeID ID;
1524 MemberPointerType::Profile(ID, T, Cls);
1525
1526 void *InsertPos = 0;
1527 if (MemberPointerType *PT =
1528 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1529 return QualType(PT, 0);
1530
1531 // If the pointee or class type isn't canonical, this won't be a canonical
1532 // type either, so fill in the canonical type field.
1533 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001534 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001535 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1536
1537 // Get the new insert position for the node we care about.
1538 MemberPointerType *NewIP =
1539 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001540 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001541 }
John McCall6b304a02009-09-24 23:30:46 +00001542 MemberPointerType *New
1543 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001544 Types.push_back(New);
1545 MemberPointerTypes.InsertNode(New, InsertPos);
1546 return QualType(New, 0);
1547}
1548
Mike Stump1eb44332009-09-09 15:08:12 +00001549/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001550/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001551QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001552 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001553 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001554 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001555 assert((EltTy->isDependentType() ||
1556 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001557 "Constant array of VLAs is illegal!");
1558
Chris Lattner38aeec72009-05-13 04:12:56 +00001559 // Convert the array size into a canonical width matching the pointer size for
1560 // the target.
1561 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001562 ArySize =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001563 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001566 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Reid Spencer5f016e22007-07-11 17:01:13 +00001568 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001569 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001570 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001572
John McCall3b657512011-01-19 10:06:00 +00001573 // If the element type isn't canonical or has qualifiers, this won't
1574 // be a canonical type either, so fill in the canonical type field.
1575 QualType Canon;
1576 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1577 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1578 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001579 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001580 Canon = getQualifiedType(Canon, canonSplit.second);
1581
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001583 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001584 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001585 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 }
Mike Stump1eb44332009-09-09 15:08:12 +00001587
John McCall6b304a02009-09-24 23:30:46 +00001588 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001589 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001590 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 Types.push_back(New);
1592 return QualType(New, 0);
1593}
1594
John McCallce889032011-01-18 08:40:38 +00001595/// getVariableArrayDecayedType - Turns the given type, which may be
1596/// variably-modified, into the corresponding type with all the known
1597/// sizes replaced with [*].
1598QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1599 // Vastly most common case.
1600 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001601
John McCallce889032011-01-18 08:40:38 +00001602 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001603
John McCallce889032011-01-18 08:40:38 +00001604 SplitQualType split = type.getSplitDesugaredType();
1605 const Type *ty = split.first;
1606 switch (ty->getTypeClass()) {
1607#define TYPE(Class, Base)
1608#define ABSTRACT_TYPE(Class, Base)
1609#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1610#include "clang/AST/TypeNodes.def"
1611 llvm_unreachable("didn't desugar past all non-canonical types?");
1612
1613 // These types should never be variably-modified.
1614 case Type::Builtin:
1615 case Type::Complex:
1616 case Type::Vector:
1617 case Type::ExtVector:
1618 case Type::DependentSizedExtVector:
1619 case Type::ObjCObject:
1620 case Type::ObjCInterface:
1621 case Type::ObjCObjectPointer:
1622 case Type::Record:
1623 case Type::Enum:
1624 case Type::UnresolvedUsing:
1625 case Type::TypeOfExpr:
1626 case Type::TypeOf:
1627 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001628 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001629 case Type::DependentName:
1630 case Type::InjectedClassName:
1631 case Type::TemplateSpecialization:
1632 case Type::DependentTemplateSpecialization:
1633 case Type::TemplateTypeParm:
1634 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001635 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001636 case Type::PackExpansion:
1637 llvm_unreachable("type should never be variably-modified");
1638
1639 // These types can be variably-modified but should never need to
1640 // further decay.
1641 case Type::FunctionNoProto:
1642 case Type::FunctionProto:
1643 case Type::BlockPointer:
1644 case Type::MemberPointer:
1645 return type;
1646
1647 // These types can be variably-modified. All these modifications
1648 // preserve structure except as noted by comments.
1649 // TODO: if we ever care about optimizing VLAs, there are no-op
1650 // optimizations available here.
1651 case Type::Pointer:
1652 result = getPointerType(getVariableArrayDecayedType(
1653 cast<PointerType>(ty)->getPointeeType()));
1654 break;
1655
1656 case Type::LValueReference: {
1657 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1658 result = getLValueReferenceType(
1659 getVariableArrayDecayedType(lv->getPointeeType()),
1660 lv->isSpelledAsLValue());
1661 break;
1662 }
1663
1664 case Type::RValueReference: {
1665 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1666 result = getRValueReferenceType(
1667 getVariableArrayDecayedType(lv->getPointeeType()));
1668 break;
1669 }
1670
1671 case Type::ConstantArray: {
1672 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1673 result = getConstantArrayType(
1674 getVariableArrayDecayedType(cat->getElementType()),
1675 cat->getSize(),
1676 cat->getSizeModifier(),
1677 cat->getIndexTypeCVRQualifiers());
1678 break;
1679 }
1680
1681 case Type::DependentSizedArray: {
1682 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1683 result = getDependentSizedArrayType(
1684 getVariableArrayDecayedType(dat->getElementType()),
1685 dat->getSizeExpr(),
1686 dat->getSizeModifier(),
1687 dat->getIndexTypeCVRQualifiers(),
1688 dat->getBracketsRange());
1689 break;
1690 }
1691
1692 // Turn incomplete types into [*] types.
1693 case Type::IncompleteArray: {
1694 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1695 result = getVariableArrayType(
1696 getVariableArrayDecayedType(iat->getElementType()),
1697 /*size*/ 0,
1698 ArrayType::Normal,
1699 iat->getIndexTypeCVRQualifiers(),
1700 SourceRange());
1701 break;
1702 }
1703
1704 // Turn VLA types into [*] types.
1705 case Type::VariableArray: {
1706 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1707 result = getVariableArrayType(
1708 getVariableArrayDecayedType(vat->getElementType()),
1709 /*size*/ 0,
1710 ArrayType::Star,
1711 vat->getIndexTypeCVRQualifiers(),
1712 vat->getBracketsRange());
1713 break;
1714 }
1715 }
1716
1717 // Apply the top-level qualifiers from the original.
1718 return getQualifiedType(result, split.second);
1719}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001720
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001721/// getVariableArrayType - Returns a non-unique reference to the type for a
1722/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001723QualType ASTContext::getVariableArrayType(QualType EltTy,
1724 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001725 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001726 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001727 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001728 // Since we don't unique expressions, it isn't possible to unique VLA's
1729 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001730 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001731
John McCall3b657512011-01-19 10:06:00 +00001732 // Be sure to pull qualifiers off the element type.
1733 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1734 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1735 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001736 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001737 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001738 }
1739
John McCall6b304a02009-09-24 23:30:46 +00001740 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001741 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001742
1743 VariableArrayTypes.push_back(New);
1744 Types.push_back(New);
1745 return QualType(New, 0);
1746}
1747
Douglas Gregor898574e2008-12-05 23:32:09 +00001748/// getDependentSizedArrayType - Returns a non-unique reference to
1749/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001750/// type.
John McCall3b657512011-01-19 10:06:00 +00001751QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1752 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001753 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001754 unsigned elementTypeQuals,
1755 SourceRange brackets) const {
1756 assert((!numElements || numElements->isTypeDependent() ||
1757 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001758 "Size must be type- or value-dependent!");
1759
John McCall3b657512011-01-19 10:06:00 +00001760 // Dependently-sized array types that do not have a specified number
1761 // of elements will have their sizes deduced from a dependent
1762 // initializer. We do no canonicalization here at all, which is okay
1763 // because they can't be used in most locations.
1764 if (!numElements) {
1765 DependentSizedArrayType *newType
1766 = new (*this, TypeAlignment)
1767 DependentSizedArrayType(*this, elementType, QualType(),
1768 numElements, ASM, elementTypeQuals,
1769 brackets);
1770 Types.push_back(newType);
1771 return QualType(newType, 0);
1772 }
1773
1774 // Otherwise, we actually build a new type every time, but we
1775 // also build a canonical type.
1776
1777 SplitQualType canonElementType = getCanonicalType(elementType).split();
1778
1779 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001780 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001781 DependentSizedArrayType::Profile(ID, *this,
1782 QualType(canonElementType.first, 0),
1783 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001784
John McCall3b657512011-01-19 10:06:00 +00001785 // Look for an existing type with these properties.
1786 DependentSizedArrayType *canonTy =
1787 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001788
John McCall3b657512011-01-19 10:06:00 +00001789 // If we don't have one, build one.
1790 if (!canonTy) {
1791 canonTy = new (*this, TypeAlignment)
1792 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1793 QualType(), numElements, ASM, elementTypeQuals,
1794 brackets);
1795 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1796 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001797 }
1798
John McCall3b657512011-01-19 10:06:00 +00001799 // Apply qualifiers from the element type to the array.
1800 QualType canon = getQualifiedType(QualType(canonTy,0),
1801 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001802
John McCall3b657512011-01-19 10:06:00 +00001803 // If we didn't need extra canonicalization for the element type,
1804 // then just use that as our result.
1805 if (QualType(canonElementType.first, 0) == elementType)
1806 return canon;
1807
1808 // Otherwise, we need to build a type which follows the spelling
1809 // of the element type.
1810 DependentSizedArrayType *sugaredType
1811 = new (*this, TypeAlignment)
1812 DependentSizedArrayType(*this, elementType, canon, numElements,
1813 ASM, elementTypeQuals, brackets);
1814 Types.push_back(sugaredType);
1815 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001816}
1817
John McCall3b657512011-01-19 10:06:00 +00001818QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001819 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001820 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001821 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001822 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001823
John McCall3b657512011-01-19 10:06:00 +00001824 void *insertPos = 0;
1825 if (IncompleteArrayType *iat =
1826 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1827 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001828
1829 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001830 // either, so fill in the canonical type field. We also have to pull
1831 // qualifiers off the element type.
1832 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001833
John McCall3b657512011-01-19 10:06:00 +00001834 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1835 SplitQualType canonSplit = getCanonicalType(elementType).split();
1836 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1837 ASM, elementTypeQuals);
1838 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001839
1840 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001841 IncompleteArrayType *existing =
1842 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1843 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001844 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001845
John McCall3b657512011-01-19 10:06:00 +00001846 IncompleteArrayType *newType = new (*this, TypeAlignment)
1847 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001848
John McCall3b657512011-01-19 10:06:00 +00001849 IncompleteArrayTypes.InsertNode(newType, insertPos);
1850 Types.push_back(newType);
1851 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001852}
1853
Steve Naroff73322922007-07-18 18:00:27 +00001854/// getVectorType - Return the unique reference to a vector type of
1855/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001856QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001857 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001858 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Reid Spencer5f016e22007-07-11 17:01:13 +00001860 // Check if we've already instantiated a vector of this type.
1861 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001862 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001863
Reid Spencer5f016e22007-07-11 17:01:13 +00001864 void *InsertPos = 0;
1865 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1866 return QualType(VTP, 0);
1867
1868 // If the element type isn't canonical, this won't be a canonical type either,
1869 // so fill in the canonical type field.
1870 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001871 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001872 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Reid Spencer5f016e22007-07-11 17:01:13 +00001874 // Get the new insert position for the node we care about.
1875 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001876 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001877 }
John McCall6b304a02009-09-24 23:30:46 +00001878 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001879 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001880 VectorTypes.InsertNode(New, InsertPos);
1881 Types.push_back(New);
1882 return QualType(New, 0);
1883}
1884
Nate Begeman213541a2008-04-18 23:10:10 +00001885/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001886/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001887QualType
1888ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00001889 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Steve Naroff73322922007-07-18 18:00:27 +00001891 // Check if we've already instantiated a vector of this type.
1892 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001893 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001894 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001895 void *InsertPos = 0;
1896 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1897 return QualType(VTP, 0);
1898
1899 // If the element type isn't canonical, this won't be a canonical type either,
1900 // so fill in the canonical type field.
1901 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001902 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001903 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Steve Naroff73322922007-07-18 18:00:27 +00001905 // Get the new insert position for the node we care about.
1906 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001907 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001908 }
John McCall6b304a02009-09-24 23:30:46 +00001909 ExtVectorType *New = new (*this, TypeAlignment)
1910 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001911 VectorTypes.InsertNode(New, InsertPos);
1912 Types.push_back(New);
1913 return QualType(New, 0);
1914}
1915
Jay Foad4ba2a172011-01-12 09:06:06 +00001916QualType
1917ASTContext::getDependentSizedExtVectorType(QualType vecType,
1918 Expr *SizeExpr,
1919 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001920 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001921 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001922 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001924 void *InsertPos = 0;
1925 DependentSizedExtVectorType *Canon
1926 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1927 DependentSizedExtVectorType *New;
1928 if (Canon) {
1929 // We already have a canonical version of this array type; use it as
1930 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001931 New = new (*this, TypeAlignment)
1932 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1933 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001934 } else {
1935 QualType CanonVecTy = getCanonicalType(vecType);
1936 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001937 New = new (*this, TypeAlignment)
1938 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1939 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001940
1941 DependentSizedExtVectorType *CanonCheck
1942 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1943 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1944 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001945 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1946 } else {
1947 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1948 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001949 New = new (*this, TypeAlignment)
1950 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001951 }
1952 }
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001954 Types.push_back(New);
1955 return QualType(New, 0);
1956}
1957
Douglas Gregor72564e72009-02-26 23:50:07 +00001958/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001959///
Jay Foad4ba2a172011-01-12 09:06:06 +00001960QualType
1961ASTContext::getFunctionNoProtoType(QualType ResultTy,
1962 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00001963 const CallingConv DefaultCC = Info.getCC();
1964 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1965 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00001966 // Unique functions, to guarantee there is only one function of a particular
1967 // structure.
1968 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001969 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Reid Spencer5f016e22007-07-11 17:01:13 +00001971 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001972 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001973 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001974 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Reid Spencer5f016e22007-07-11 17:01:13 +00001976 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001977 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001978 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001979 Canonical =
1980 getFunctionNoProtoType(getCanonicalType(ResultTy),
1981 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001984 FunctionNoProtoType *NewIP =
1985 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001986 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001987 }
Mike Stump1eb44332009-09-09 15:08:12 +00001988
Roman Divackycfe9af22011-03-01 17:40:53 +00001989 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00001990 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00001991 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001993 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001994 return QualType(New, 0);
1995}
1996
1997/// getFunctionType - Return a normal function type with a typed argument
1998/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00001999QualType
2000ASTContext::getFunctionType(QualType ResultTy,
2001 const QualType *ArgArray, unsigned NumArgs,
2002 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 // Unique functions, to guarantee there is only one function of a particular
2004 // structure.
2005 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002006 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002007
2008 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002009 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002010 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002012
2013 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002014 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00002015 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002016 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002017 isCanonical = false;
2018
Roman Divackycfe9af22011-03-01 17:40:53 +00002019 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2020 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2021 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002022
Reid Spencer5f016e22007-07-11 17:01:13 +00002023 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002024 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002026 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002027 llvm::SmallVector<QualType, 16> CanonicalArgs;
2028 CanonicalArgs.reserve(NumArgs);
2029 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002030 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002031
John McCalle23cf432010-12-14 08:05:40 +00002032 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002033 CanonicalEPI.ExceptionSpecType = EST_None;
2034 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002035 CanonicalEPI.ExtInfo
2036 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2037
Chris Lattnerf52ab252008-04-06 22:59:24 +00002038 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002039 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002040 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002041
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002043 FunctionProtoType *NewIP =
2044 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002045 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002046 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002047
John McCallf85e1932011-06-15 23:02:42 +00002048 // FunctionProtoType objects are allocated with extra bytes after
2049 // them for three variable size arrays at the end:
2050 // - parameter types
2051 // - exception types
2052 // - consumed-arguments flags
2053 // Instead of the exception types, there could be a noexcept
2054 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002055 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002056 NumArgs * sizeof(QualType);
2057 if (EPI.ExceptionSpecType == EST_Dynamic)
2058 Size += EPI.NumExceptions * sizeof(QualType);
2059 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002060 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002061 }
John McCallf85e1932011-06-15 23:02:42 +00002062 if (EPI.ConsumedArguments)
2063 Size += NumArgs * sizeof(bool);
2064
John McCalle23cf432010-12-14 08:05:40 +00002065 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002066 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2067 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002068 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002069 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002070 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 return QualType(FTP, 0);
2072}
2073
John McCall3cb0ebd2010-03-10 03:28:59 +00002074#ifndef NDEBUG
2075static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2076 if (!isa<CXXRecordDecl>(D)) return false;
2077 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2078 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2079 return true;
2080 if (RD->getDescribedClassTemplate() &&
2081 !isa<ClassTemplateSpecializationDecl>(RD))
2082 return true;
2083 return false;
2084}
2085#endif
2086
2087/// getInjectedClassNameType - Return the unique reference to the
2088/// injected class name type for the specified templated declaration.
2089QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002090 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002091 assert(NeedsInjectedClassNameType(Decl));
2092 if (Decl->TypeForDecl) {
2093 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00002094 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002095 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2096 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2097 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2098 } else {
John McCallf4c73712011-01-19 06:33:43 +00002099 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002100 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002101 Decl->TypeForDecl = newType;
2102 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002103 }
2104 return QualType(Decl->TypeForDecl, 0);
2105}
2106
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002107/// getTypeDeclType - Return the unique reference to the type for the
2108/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002109QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002110 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002111 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Richard Smith162e1c12011-04-15 14:24:37 +00002113 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002114 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002115
John McCallbecb8d52010-03-10 06:48:02 +00002116 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2117 "Template type parameter types are always available.");
2118
John McCall19c85762010-02-16 03:57:14 +00002119 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002120 assert(!Record->getPreviousDeclaration() &&
2121 "struct/union has previous declaration");
2122 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002123 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002124 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002125 assert(!Enum->getPreviousDeclaration() &&
2126 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002127 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002128 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002129 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002130 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2131 Decl->TypeForDecl = newType;
2132 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002133 } else
John McCallbecb8d52010-03-10 06:48:02 +00002134 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002135
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002136 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002137}
2138
Reid Spencer5f016e22007-07-11 17:01:13 +00002139/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002140/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002141QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002142ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2143 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002144 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002146 if (Canonical.isNull())
2147 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002148 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002149 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002150 Decl->TypeForDecl = newType;
2151 Types.push_back(newType);
2152 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002153}
2154
Jay Foad4ba2a172011-01-12 09:06:06 +00002155QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002156 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2157
2158 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2159 if (PrevDecl->TypeForDecl)
2160 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2161
John McCallf4c73712011-01-19 06:33:43 +00002162 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2163 Decl->TypeForDecl = newType;
2164 Types.push_back(newType);
2165 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002166}
2167
Jay Foad4ba2a172011-01-12 09:06:06 +00002168QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002169 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2170
2171 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2172 if (PrevDecl->TypeForDecl)
2173 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2174
John McCallf4c73712011-01-19 06:33:43 +00002175 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2176 Decl->TypeForDecl = newType;
2177 Types.push_back(newType);
2178 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002179}
2180
John McCall9d156a72011-01-06 01:58:22 +00002181QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2182 QualType modifiedType,
2183 QualType equivalentType) {
2184 llvm::FoldingSetNodeID id;
2185 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2186
2187 void *insertPos = 0;
2188 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2189 if (type) return QualType(type, 0);
2190
2191 QualType canon = getCanonicalType(equivalentType);
2192 type = new (*this, TypeAlignment)
2193 AttributedType(canon, attrKind, modifiedType, equivalentType);
2194
2195 Types.push_back(type);
2196 AttributedTypes.InsertNode(type, insertPos);
2197
2198 return QualType(type, 0);
2199}
2200
2201
John McCall49a832b2009-10-18 09:09:24 +00002202/// \brief Retrieve a substitution-result type.
2203QualType
2204ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002205 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002206 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002207 && "replacement types must always be canonical");
2208
2209 llvm::FoldingSetNodeID ID;
2210 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2211 void *InsertPos = 0;
2212 SubstTemplateTypeParmType *SubstParm
2213 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2214
2215 if (!SubstParm) {
2216 SubstParm = new (*this, TypeAlignment)
2217 SubstTemplateTypeParmType(Parm, Replacement);
2218 Types.push_back(SubstParm);
2219 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2220 }
2221
2222 return QualType(SubstParm, 0);
2223}
2224
Douglas Gregorc3069d62011-01-14 02:55:32 +00002225/// \brief Retrieve a
2226QualType ASTContext::getSubstTemplateTypeParmPackType(
2227 const TemplateTypeParmType *Parm,
2228 const TemplateArgument &ArgPack) {
2229#ifndef NDEBUG
2230 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2231 PEnd = ArgPack.pack_end();
2232 P != PEnd; ++P) {
2233 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2234 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2235 }
2236#endif
2237
2238 llvm::FoldingSetNodeID ID;
2239 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2240 void *InsertPos = 0;
2241 if (SubstTemplateTypeParmPackType *SubstParm
2242 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2243 return QualType(SubstParm, 0);
2244
2245 QualType Canon;
2246 if (!Parm->isCanonicalUnqualified()) {
2247 Canon = getCanonicalType(QualType(Parm, 0));
2248 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2249 ArgPack);
2250 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2251 }
2252
2253 SubstTemplateTypeParmPackType *SubstParm
2254 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2255 ArgPack);
2256 Types.push_back(SubstParm);
2257 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2258 return QualType(SubstParm, 0);
2259}
2260
Douglas Gregorfab9d672009-02-05 23:33:38 +00002261/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002262/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002263/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002264QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002265 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002266 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002267 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002268 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002269 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002270 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002271 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2272
2273 if (TypeParm)
2274 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002275
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002276 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002277 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002278 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002279
2280 TemplateTypeParmType *TypeCheck
2281 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2282 assert(!TypeCheck && "Template type parameter canonical type broken");
2283 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002284 } else
John McCall6b304a02009-09-24 23:30:46 +00002285 TypeParm = new (*this, TypeAlignment)
2286 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002287
2288 Types.push_back(TypeParm);
2289 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2290
2291 return QualType(TypeParm, 0);
2292}
2293
John McCall3cb0ebd2010-03-10 03:28:59 +00002294TypeSourceInfo *
2295ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2296 SourceLocation NameLoc,
2297 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002298 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002299 assert(!Name.getAsDependentTemplateName() &&
2300 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002301 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002302
2303 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2304 TemplateSpecializationTypeLoc TL
2305 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2306 TL.setTemplateNameLoc(NameLoc);
2307 TL.setLAngleLoc(Args.getLAngleLoc());
2308 TL.setRAngleLoc(Args.getRAngleLoc());
2309 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2310 TL.setArgLocInfo(i, Args[i].getLocInfo());
2311 return DI;
2312}
2313
Mike Stump1eb44332009-09-09 15:08:12 +00002314QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002315ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002316 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002317 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002318 assert(!Template.getAsDependentTemplateName() &&
2319 "No dependent template names here!");
2320
John McCalld5532b62009-11-23 01:53:49 +00002321 unsigned NumArgs = Args.size();
2322
John McCall833ca992009-10-29 08:12:44 +00002323 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2324 ArgVec.reserve(NumArgs);
2325 for (unsigned i = 0; i != NumArgs; ++i)
2326 ArgVec.push_back(Args[i].getArgument());
2327
John McCall31f17ec2010-04-27 00:57:59 +00002328 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002329 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002330}
2331
2332QualType
2333ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002334 const TemplateArgument *Args,
2335 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002336 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002337 assert(!Template.getAsDependentTemplateName() &&
2338 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002339 // Look through qualified template names.
2340 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2341 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002342
Richard Smith3e4c6c42011-05-05 21:57:07 +00002343 bool isTypeAlias =
2344 Template.getAsTemplateDecl() &&
2345 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2346
2347 QualType CanonType;
2348 if (!Underlying.isNull())
2349 CanonType = getCanonicalType(Underlying);
2350 else {
2351 assert(!isTypeAlias &&
2352 "Underlying type for template alias must be computed by caller");
2353 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2354 NumArgs);
2355 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002356
Douglas Gregor1275ae02009-07-28 23:00:59 +00002357 // Allocate the (non-canonical) template specialization type, but don't
2358 // try to unique it: these types typically have location information that
2359 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002360 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2361 sizeof(TemplateArgument) * NumArgs +
2362 (isTypeAlias ? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002363 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002364 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002365 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002366 Args, NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002367 CanonType,
2368 isTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Douglas Gregor55f6b142009-02-09 18:46:07 +00002370 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002371 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002372}
2373
Mike Stump1eb44332009-09-09 15:08:12 +00002374QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002375ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2376 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002377 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002378 assert(!Template.getAsDependentTemplateName() &&
2379 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002380 assert((!Template.getAsTemplateDecl() ||
2381 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2382 "Underlying type for template alias must be computed by caller");
2383
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002384 // Look through qualified template names.
2385 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2386 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002387
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002388 // Build the canonical template specialization type.
2389 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2390 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2391 CanonArgs.reserve(NumArgs);
2392 for (unsigned I = 0; I != NumArgs; ++I)
2393 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2394
2395 // Determine whether this canonical template specialization type already
2396 // exists.
2397 llvm::FoldingSetNodeID ID;
2398 TemplateSpecializationType::Profile(ID, CanonTemplate,
2399 CanonArgs.data(), NumArgs, *this);
2400
2401 void *InsertPos = 0;
2402 TemplateSpecializationType *Spec
2403 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2404
2405 if (!Spec) {
2406 // Allocate a new canonical template specialization type.
2407 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2408 sizeof(TemplateArgument) * NumArgs),
2409 TypeAlignment);
2410 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2411 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002412 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002413 Types.push_back(Spec);
2414 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2415 }
2416
2417 assert(Spec->isDependentType() &&
2418 "Non-dependent template-id type must have a canonical type");
2419 return QualType(Spec, 0);
2420}
2421
2422QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002423ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2424 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002425 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002426 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002427 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002428
2429 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002430 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002431 if (T)
2432 return QualType(T, 0);
2433
Douglas Gregor789b1f62010-02-04 18:10:26 +00002434 QualType Canon = NamedType;
2435 if (!Canon.isCanonical()) {
2436 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002437 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2438 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002439 (void)CheckT;
2440 }
2441
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002442 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002443 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002444 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002445 return QualType(T, 0);
2446}
2447
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002448QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002449ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002450 llvm::FoldingSetNodeID ID;
2451 ParenType::Profile(ID, InnerType);
2452
2453 void *InsertPos = 0;
2454 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2455 if (T)
2456 return QualType(T, 0);
2457
2458 QualType Canon = InnerType;
2459 if (!Canon.isCanonical()) {
2460 Canon = getCanonicalType(InnerType);
2461 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2462 assert(!CheckT && "Paren canonical type broken");
2463 (void)CheckT;
2464 }
2465
2466 T = new (*this) ParenType(InnerType, Canon);
2467 Types.push_back(T);
2468 ParenTypes.InsertNode(T, InsertPos);
2469 return QualType(T, 0);
2470}
2471
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002472QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2473 NestedNameSpecifier *NNS,
2474 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002475 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002476 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2477
2478 if (Canon.isNull()) {
2479 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002480 ElaboratedTypeKeyword CanonKeyword = Keyword;
2481 if (Keyword == ETK_None)
2482 CanonKeyword = ETK_Typename;
2483
2484 if (CanonNNS != NNS || CanonKeyword != Keyword)
2485 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002486 }
2487
2488 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002489 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002490
2491 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002492 DependentNameType *T
2493 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002494 if (T)
2495 return QualType(T, 0);
2496
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002497 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002498 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002499 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002500 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002501}
2502
Mike Stump1eb44332009-09-09 15:08:12 +00002503QualType
John McCall33500952010-06-11 00:33:02 +00002504ASTContext::getDependentTemplateSpecializationType(
2505 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002506 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002507 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002508 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002509 // TODO: avoid this copy
2510 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2511 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2512 ArgCopy.push_back(Args[I].getArgument());
2513 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2514 ArgCopy.size(),
2515 ArgCopy.data());
2516}
2517
2518QualType
2519ASTContext::getDependentTemplateSpecializationType(
2520 ElaboratedTypeKeyword Keyword,
2521 NestedNameSpecifier *NNS,
2522 const IdentifierInfo *Name,
2523 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002524 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002525 assert((!NNS || NNS->isDependent()) &&
2526 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002527
Douglas Gregor789b1f62010-02-04 18:10:26 +00002528 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002529 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2530 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002531
2532 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002533 DependentTemplateSpecializationType *T
2534 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002535 if (T)
2536 return QualType(T, 0);
2537
John McCall33500952010-06-11 00:33:02 +00002538 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002539
John McCall33500952010-06-11 00:33:02 +00002540 ElaboratedTypeKeyword CanonKeyword = Keyword;
2541 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2542
2543 bool AnyNonCanonArgs = false;
2544 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2545 for (unsigned I = 0; I != NumArgs; ++I) {
2546 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2547 if (!CanonArgs[I].structurallyEquals(Args[I]))
2548 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002549 }
2550
John McCall33500952010-06-11 00:33:02 +00002551 QualType Canon;
2552 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2553 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2554 Name, NumArgs,
2555 CanonArgs.data());
2556
2557 // Find the insert position again.
2558 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2559 }
2560
2561 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2562 sizeof(TemplateArgument) * NumArgs),
2563 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002564 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002565 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002566 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002567 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002568 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002569}
2570
Douglas Gregorcded4f62011-01-14 17:04:44 +00002571QualType ASTContext::getPackExpansionType(QualType Pattern,
2572 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002573 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002574 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002575
2576 assert(Pattern->containsUnexpandedParameterPack() &&
2577 "Pack expansions must expand one or more parameter packs");
2578 void *InsertPos = 0;
2579 PackExpansionType *T
2580 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2581 if (T)
2582 return QualType(T, 0);
2583
2584 QualType Canon;
2585 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002586 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002587
2588 // Find the insert position again.
2589 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2590 }
2591
Douglas Gregorcded4f62011-01-14 17:04:44 +00002592 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002593 Types.push_back(T);
2594 PackExpansionTypes.InsertNode(T, InsertPos);
2595 return QualType(T, 0);
2596}
2597
Chris Lattner88cb27a2008-04-07 04:56:42 +00002598/// CmpProtocolNames - Comparison predicate for sorting protocols
2599/// alphabetically.
2600static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2601 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002602 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002603}
2604
John McCallc12c5bb2010-05-15 11:32:37 +00002605static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002606 unsigned NumProtocols) {
2607 if (NumProtocols == 0) return true;
2608
2609 for (unsigned i = 1; i != NumProtocols; ++i)
2610 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2611 return false;
2612 return true;
2613}
2614
2615static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002616 unsigned &NumProtocols) {
2617 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002618
Chris Lattner88cb27a2008-04-07 04:56:42 +00002619 // Sort protocols, keyed by name.
2620 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2621
2622 // Remove duplicates.
2623 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2624 NumProtocols = ProtocolsEnd-Protocols;
2625}
2626
John McCallc12c5bb2010-05-15 11:32:37 +00002627QualType ASTContext::getObjCObjectType(QualType BaseType,
2628 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002629 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002630 // If the base type is an interface and there aren't any protocols
2631 // to add, then the interface type will do just fine.
2632 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2633 return BaseType;
2634
2635 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002636 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002637 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002638 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002639 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2640 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002641
John McCallc12c5bb2010-05-15 11:32:37 +00002642 // Build the canonical type, which has the canonical base type and
2643 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002644 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002645 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2646 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2647 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002648 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2649 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002650 unsigned UniqueCount = NumProtocols;
2651
John McCall54e14c42009-10-22 22:37:11 +00002652 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002653 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2654 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002655 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002656 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2657 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002658 }
2659
2660 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002661 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2662 }
2663
2664 unsigned Size = sizeof(ObjCObjectTypeImpl);
2665 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2666 void *Mem = Allocate(Size, TypeAlignment);
2667 ObjCObjectTypeImpl *T =
2668 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2669
2670 Types.push_back(T);
2671 ObjCObjectTypes.InsertNode(T, InsertPos);
2672 return QualType(T, 0);
2673}
2674
2675/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2676/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002677QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002678 llvm::FoldingSetNodeID ID;
2679 ObjCObjectPointerType::Profile(ID, ObjectT);
2680
2681 void *InsertPos = 0;
2682 if (ObjCObjectPointerType *QT =
2683 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2684 return QualType(QT, 0);
2685
2686 // Find the canonical object type.
2687 QualType Canonical;
2688 if (!ObjectT.isCanonical()) {
2689 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2690
2691 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002692 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2693 }
2694
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002695 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002696 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2697 ObjCObjectPointerType *QType =
2698 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002699
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002700 Types.push_back(QType);
2701 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002702 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002703}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002704
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002705/// getObjCInterfaceType - Return the unique reference to the type for the
2706/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002707QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002708 if (Decl->TypeForDecl)
2709 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002710
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002711 // FIXME: redeclarations?
2712 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2713 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2714 Decl->TypeForDecl = T;
2715 Types.push_back(T);
2716 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002717}
2718
Douglas Gregor72564e72009-02-26 23:50:07 +00002719/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2720/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002721/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002722/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002723/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002724QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002725 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002726 if (tofExpr->isTypeDependent()) {
2727 llvm::FoldingSetNodeID ID;
2728 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Douglas Gregorb1975722009-07-30 23:18:24 +00002730 void *InsertPos = 0;
2731 DependentTypeOfExprType *Canon
2732 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2733 if (Canon) {
2734 // We already have a "canonical" version of an identical, dependent
2735 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002736 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002737 QualType((TypeOfExprType*)Canon, 0));
2738 }
2739 else {
2740 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002741 Canon
2742 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002743 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2744 toe = Canon;
2745 }
2746 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002747 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002748 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002749 }
Steve Naroff9752f252007-08-01 18:02:17 +00002750 Types.push_back(toe);
2751 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002752}
2753
Steve Naroff9752f252007-08-01 18:02:17 +00002754/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2755/// TypeOfType AST's. The only motivation to unique these nodes would be
2756/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002757/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002758/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002759QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002760 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002761 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002762 Types.push_back(tot);
2763 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002764}
2765
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002766/// getDecltypeForExpr - Given an expr, will return the decltype for that
2767/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002768static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002769 if (e->isTypeDependent())
2770 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002771
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002772 // If e is an id expression or a class member access, decltype(e) is defined
2773 // as the type of the entity named by e.
2774 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2775 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2776 return VD->getType();
2777 }
2778 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2779 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2780 return FD->getType();
2781 }
2782 // If e is a function call or an invocation of an overloaded operator,
2783 // (parentheses around e are ignored), decltype(e) is defined as the
2784 // return type of that function.
2785 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2786 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002787
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002788 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002789
2790 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002791 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002792 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002793 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002794
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002795 return T;
2796}
2797
Anders Carlsson395b4752009-06-24 19:06:50 +00002798/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2799/// DecltypeType AST's. The only motivation to unique these nodes would be
2800/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002801/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002802/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002803QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002804 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002805
2806 // C++0x [temp.type]p2:
2807 // If an expression e involves a template parameter, decltype(e) denotes a
2808 // unique dependent type. Two such decltype-specifiers refer to the same
2809 // type only if their expressions are equivalent (14.5.6.1).
2810 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002811 llvm::FoldingSetNodeID ID;
2812 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002813
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002814 void *InsertPos = 0;
2815 DependentDecltypeType *Canon
2816 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2817 if (Canon) {
2818 // We already have a "canonical" version of an equivalent, dependent
2819 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002820 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002821 QualType((DecltypeType*)Canon, 0));
2822 }
2823 else {
2824 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002825 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002826 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2827 dt = Canon;
2828 }
2829 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002830 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002831 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002832 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002833 Types.push_back(dt);
2834 return QualType(dt, 0);
2835}
2836
Sean Huntca63c202011-05-24 22:41:36 +00002837/// getUnaryTransformationType - We don't unique these, since the memory
2838/// savings are minimal and these are rare.
2839QualType ASTContext::getUnaryTransformType(QualType BaseType,
2840 QualType UnderlyingType,
2841 UnaryTransformType::UTTKind Kind)
2842 const {
2843 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002844 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2845 Kind,
2846 UnderlyingType->isDependentType() ?
2847 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00002848 Types.push_back(Ty);
2849 return QualType(Ty, 0);
2850}
2851
Richard Smith483b9f32011-02-21 20:05:19 +00002852/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002853QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002854 void *InsertPos = 0;
2855 if (!DeducedType.isNull()) {
2856 // Look in the folding set for an existing type.
2857 llvm::FoldingSetNodeID ID;
2858 AutoType::Profile(ID, DeducedType);
2859 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2860 return QualType(AT, 0);
2861 }
2862
2863 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2864 Types.push_back(AT);
2865 if (InsertPos)
2866 AutoTypes.InsertNode(AT, InsertPos);
2867 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002868}
2869
Richard Smithad762fc2011-04-14 22:09:26 +00002870/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2871QualType ASTContext::getAutoDeductType() const {
2872 if (AutoDeductTy.isNull())
2873 AutoDeductTy = getAutoType(QualType());
2874 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2875 return AutoDeductTy;
2876}
2877
2878/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2879QualType ASTContext::getAutoRRefDeductType() const {
2880 if (AutoRRefDeductTy.isNull())
2881 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2882 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2883 return AutoRRefDeductTy;
2884}
2885
Reid Spencer5f016e22007-07-11 17:01:13 +00002886/// getTagDeclType - Return the unique reference to the type for the
2887/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00002888QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00002889 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002890 // FIXME: What is the design on getTagDeclType when it requires casting
2891 // away const? mutable?
2892 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002893}
2894
Mike Stump1eb44332009-09-09 15:08:12 +00002895/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2896/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2897/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002898CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002899 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002900}
2901
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002902/// getSignedWCharType - Return the type of "signed wchar_t".
2903/// Used when in C++, as a GCC extension.
2904QualType ASTContext::getSignedWCharType() const {
2905 // FIXME: derive from "Target" ?
2906 return WCharTy;
2907}
2908
2909/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2910/// Used when in C++, as a GCC extension.
2911QualType ASTContext::getUnsignedWCharType() const {
2912 // FIXME: derive from "Target" ?
2913 return UnsignedIntTy;
2914}
2915
Chris Lattner8b9023b2007-07-13 03:05:23 +00002916/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2917/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2918QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002919 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002920}
2921
Chris Lattnere6327742008-04-02 05:18:44 +00002922//===----------------------------------------------------------------------===//
2923// Type Operators
2924//===----------------------------------------------------------------------===//
2925
Jay Foad4ba2a172011-01-12 09:06:06 +00002926CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00002927 // Push qualifiers into arrays, and then discard any remaining
2928 // qualifiers.
2929 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002930 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002931 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002932 QualType Result;
2933 if (isa<ArrayType>(Ty)) {
2934 Result = getArrayDecayedType(QualType(Ty,0));
2935 } else if (isa<FunctionType>(Ty)) {
2936 Result = getPointerType(QualType(Ty, 0));
2937 } else {
2938 Result = QualType(Ty, 0);
2939 }
2940
2941 return CanQualType::CreateUnsafe(Result);
2942}
2943
John McCall62c28c82011-01-18 07:41:22 +00002944QualType ASTContext::getUnqualifiedArrayType(QualType type,
2945 Qualifiers &quals) {
2946 SplitQualType splitType = type.getSplitUnqualifiedType();
2947
2948 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2949 // the unqualified desugared type and then drops it on the floor.
2950 // We then have to strip that sugar back off with
2951 // getUnqualifiedDesugaredType(), which is silly.
2952 const ArrayType *AT =
2953 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2954
2955 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00002956 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00002957 quals = splitType.second;
2958 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002959 }
2960
John McCall62c28c82011-01-18 07:41:22 +00002961 // Otherwise, recurse on the array's element type.
2962 QualType elementType = AT->getElementType();
2963 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2964
2965 // If that didn't change the element type, AT has no qualifiers, so we
2966 // can just use the results in splitType.
2967 if (elementType == unqualElementType) {
2968 assert(quals.empty()); // from the recursive call
2969 quals = splitType.second;
2970 return QualType(splitType.first, 0);
2971 }
2972
2973 // Otherwise, add in the qualifiers from the outermost type, then
2974 // build the type back up.
2975 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002976
Douglas Gregor9dadd942010-05-17 18:45:21 +00002977 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002978 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002979 CAT->getSizeModifier(), 0);
2980 }
2981
Douglas Gregor9dadd942010-05-17 18:45:21 +00002982 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002983 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002984 }
2985
Douglas Gregor9dadd942010-05-17 18:45:21 +00002986 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002987 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00002988 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00002989 VAT->getSizeModifier(),
2990 VAT->getIndexTypeCVRQualifiers(),
2991 VAT->getBracketsRange());
2992 }
2993
2994 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00002995 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002996 DSAT->getSizeModifier(), 0,
2997 SourceRange());
2998}
2999
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003000/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3001/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3002/// they point to and return true. If T1 and T2 aren't pointer types
3003/// or pointer-to-member types, or if they are not similar at this
3004/// level, returns false and leaves T1 and T2 unchanged. Top-level
3005/// qualifiers on T1 and T2 are ignored. This function will typically
3006/// be called in a loop that successively "unwraps" pointer and
3007/// pointer-to-member types to compare them at each level.
3008bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3009 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3010 *T2PtrType = T2->getAs<PointerType>();
3011 if (T1PtrType && T2PtrType) {
3012 T1 = T1PtrType->getPointeeType();
3013 T2 = T2PtrType->getPointeeType();
3014 return true;
3015 }
3016
3017 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3018 *T2MPType = T2->getAs<MemberPointerType>();
3019 if (T1MPType && T2MPType &&
3020 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3021 QualType(T2MPType->getClass(), 0))) {
3022 T1 = T1MPType->getPointeeType();
3023 T2 = T2MPType->getPointeeType();
3024 return true;
3025 }
3026
3027 if (getLangOptions().ObjC1) {
3028 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3029 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3030 if (T1OPType && T2OPType) {
3031 T1 = T1OPType->getPointeeType();
3032 T2 = T2OPType->getPointeeType();
3033 return true;
3034 }
3035 }
3036
3037 // FIXME: Block pointers, too?
3038
3039 return false;
3040}
3041
Jay Foad4ba2a172011-01-12 09:06:06 +00003042DeclarationNameInfo
3043ASTContext::getNameForTemplate(TemplateName Name,
3044 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003045 switch (Name.getKind()) {
3046 case TemplateName::QualifiedTemplate:
3047 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003048 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003049 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3050 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003051
John McCall14606042011-06-30 08:33:18 +00003052 case TemplateName::OverloadedTemplate: {
3053 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3054 // DNInfo work in progress: CHECKME: what about DNLoc?
3055 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3056 }
3057
3058 case TemplateName::DependentTemplate: {
3059 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003060 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003061 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003062 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3063 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003064 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003065 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3066 // DNInfo work in progress: FIXME: source locations?
3067 DeclarationNameLoc DNLoc;
3068 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3069 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3070 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003071 }
3072 }
3073
John McCall14606042011-06-30 08:33:18 +00003074 case TemplateName::SubstTemplateTemplateParm: {
3075 SubstTemplateTemplateParmStorage *subst
3076 = Name.getAsSubstTemplateTemplateParm();
3077 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3078 NameLoc);
3079 }
3080
3081 case TemplateName::SubstTemplateTemplateParmPack: {
3082 SubstTemplateTemplateParmPackStorage *subst
3083 = Name.getAsSubstTemplateTemplateParmPack();
3084 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3085 NameLoc);
3086 }
3087 }
3088
3089 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003090}
3091
Jay Foad4ba2a172011-01-12 09:06:06 +00003092TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003093 switch (Name.getKind()) {
3094 case TemplateName::QualifiedTemplate:
3095 case TemplateName::Template: {
3096 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003097 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003098 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003099 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3100
3101 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003102 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003103 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003104
John McCall14606042011-06-30 08:33:18 +00003105 case TemplateName::OverloadedTemplate:
3106 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003107
John McCall14606042011-06-30 08:33:18 +00003108 case TemplateName::DependentTemplate: {
3109 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3110 assert(DTN && "Non-dependent template names must refer to template decls.");
3111 return DTN->CanonicalTemplateName;
3112 }
3113
3114 case TemplateName::SubstTemplateTemplateParm: {
3115 SubstTemplateTemplateParmStorage *subst
3116 = Name.getAsSubstTemplateTemplateParm();
3117 return getCanonicalTemplateName(subst->getReplacement());
3118 }
3119
3120 case TemplateName::SubstTemplateTemplateParmPack: {
3121 SubstTemplateTemplateParmPackStorage *subst
3122 = Name.getAsSubstTemplateTemplateParmPack();
3123 TemplateTemplateParmDecl *canonParameter
3124 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3125 TemplateArgument canonArgPack
3126 = getCanonicalTemplateArgument(subst->getArgumentPack());
3127 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3128 }
3129 }
3130
3131 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003132}
3133
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003134bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3135 X = getCanonicalTemplateName(X);
3136 Y = getCanonicalTemplateName(Y);
3137 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3138}
3139
Mike Stump1eb44332009-09-09 15:08:12 +00003140TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003141ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003142 switch (Arg.getKind()) {
3143 case TemplateArgument::Null:
3144 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003145
Douglas Gregor1275ae02009-07-28 23:00:59 +00003146 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003147 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003148
Douglas Gregor1275ae02009-07-28 23:00:59 +00003149 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003150 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003151
Douglas Gregor788cd062009-11-11 01:00:40 +00003152 case TemplateArgument::Template:
3153 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003154
3155 case TemplateArgument::TemplateExpansion:
3156 return TemplateArgument(getCanonicalTemplateName(
3157 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003158 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003159
Douglas Gregor1275ae02009-07-28 23:00:59 +00003160 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003161 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003162 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003163
Douglas Gregor1275ae02009-07-28 23:00:59 +00003164 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003165 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003166
Douglas Gregor1275ae02009-07-28 23:00:59 +00003167 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003168 if (Arg.pack_size() == 0)
3169 return Arg;
3170
Douglas Gregor910f8002010-11-07 23:05:16 +00003171 TemplateArgument *CanonArgs
3172 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003173 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003174 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003175 AEnd = Arg.pack_end();
3176 A != AEnd; (void)++A, ++Idx)
3177 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003178
Douglas Gregor910f8002010-11-07 23:05:16 +00003179 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003180 }
3181 }
3182
3183 // Silence GCC warning
3184 assert(false && "Unhandled template argument kind");
3185 return TemplateArgument();
3186}
3187
Douglas Gregord57959a2009-03-27 23:10:48 +00003188NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003189ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003190 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003191 return 0;
3192
3193 switch (NNS->getKind()) {
3194 case NestedNameSpecifier::Identifier:
3195 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003196 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003197 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3198 NNS->getAsIdentifier());
3199
3200 case NestedNameSpecifier::Namespace:
3201 // A namespace is canonical; build a nested-name-specifier with
3202 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003203 return NestedNameSpecifier::Create(*this, 0,
3204 NNS->getAsNamespace()->getOriginalNamespace());
3205
3206 case NestedNameSpecifier::NamespaceAlias:
3207 // A namespace is canonical; build a nested-name-specifier with
3208 // this namespace and no prefix.
3209 return NestedNameSpecifier::Create(*this, 0,
3210 NNS->getAsNamespaceAlias()->getNamespace()
3211 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003212
3213 case NestedNameSpecifier::TypeSpec:
3214 case NestedNameSpecifier::TypeSpecWithTemplate: {
3215 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003216
3217 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3218 // break it apart into its prefix and identifier, then reconsititute those
3219 // as the canonical nested-name-specifier. This is required to canonicalize
3220 // a dependent nested-name-specifier involving typedefs of dependent-name
3221 // types, e.g.,
3222 // typedef typename T::type T1;
3223 // typedef typename T1::type T2;
3224 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3225 NestedNameSpecifier *Prefix
3226 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3227 return NestedNameSpecifier::Create(*this, Prefix,
3228 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3229 }
3230
Douglas Gregor643f8432010-11-04 00:14:23 +00003231 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003232 if (const DependentTemplateSpecializationType *DTST
3233 = T->getAs<DependentTemplateSpecializationType>()) {
3234 NestedNameSpecifier *Prefix
3235 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003236
3237 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3238 Prefix, DTST->getIdentifier(),
3239 DTST->getNumArgs(),
3240 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003241 T = getCanonicalType(T);
3242 }
3243
John McCall3b657512011-01-19 10:06:00 +00003244 return NestedNameSpecifier::Create(*this, 0, false,
3245 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003246 }
3247
3248 case NestedNameSpecifier::Global:
3249 // The global specifier is canonical and unique.
3250 return NNS;
3251 }
3252
3253 // Required to silence a GCC warning
3254 return 0;
3255}
3256
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003257
Jay Foad4ba2a172011-01-12 09:06:06 +00003258const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003259 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003260 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003261 // Handle the common positive case fast.
3262 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3263 return AT;
3264 }
Mike Stump1eb44332009-09-09 15:08:12 +00003265
John McCall0953e762009-09-24 19:53:00 +00003266 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003267 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003268 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003269
John McCall0953e762009-09-24 19:53:00 +00003270 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003271 // implements C99 6.7.3p8: "If the specification of an array type includes
3272 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003273
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003274 // If we get here, we either have type qualifiers on the type, or we have
3275 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003276 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003277
John McCall3b657512011-01-19 10:06:00 +00003278 SplitQualType split = T.getSplitDesugaredType();
3279 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003280
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003281 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003282 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3283 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003284 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003285
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003286 // Otherwise, we have an array and we have qualifiers on it. Push the
3287 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003288 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003289
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003290 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3291 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3292 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003293 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003294 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3295 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3296 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003297 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003298
Mike Stump1eb44332009-09-09 15:08:12 +00003299 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003300 = dyn_cast<DependentSizedArrayType>(ATy))
3301 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003302 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003303 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003304 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003305 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003306 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003307
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003308 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003309 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003310 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003311 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003312 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003313 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003314}
3315
Chris Lattnere6327742008-04-02 05:18:44 +00003316/// getArrayDecayedType - Return the properly qualified result of decaying the
3317/// specified array type to a pointer. This operation is non-trivial when
3318/// handling typedefs etc. The canonical type of "T" must be an array type,
3319/// this returns a pointer to a properly qualified element of the array.
3320///
3321/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003322QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003323 // Get the element type with 'getAsArrayType' so that we don't lose any
3324 // typedefs in the element type of the array. This also handles propagation
3325 // of type qualifiers from the array type into the element type if present
3326 // (C99 6.7.3p8).
3327 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3328 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003329
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003330 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003331
3332 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003333 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003334}
3335
John McCall3b657512011-01-19 10:06:00 +00003336QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3337 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003338}
3339
John McCall3b657512011-01-19 10:06:00 +00003340QualType ASTContext::getBaseElementType(QualType type) const {
3341 Qualifiers qs;
3342 while (true) {
3343 SplitQualType split = type.getSplitDesugaredType();
3344 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3345 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003346
John McCall3b657512011-01-19 10:06:00 +00003347 type = array->getElementType();
3348 qs.addConsistentQualifiers(split.second);
3349 }
Mike Stump1eb44332009-09-09 15:08:12 +00003350
John McCall3b657512011-01-19 10:06:00 +00003351 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003352}
3353
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003354/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003355uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003356ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3357 uint64_t ElementCount = 1;
3358 do {
3359 ElementCount *= CA->getSize().getZExtValue();
3360 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3361 } while (CA);
3362 return ElementCount;
3363}
3364
Reid Spencer5f016e22007-07-11 17:01:13 +00003365/// getFloatingRank - Return a relative rank for floating point types.
3366/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003367static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003368 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003369 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003370
John McCall183700f2009-09-21 23:43:11 +00003371 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3372 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00003373 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003374 case BuiltinType::Float: return FloatRank;
3375 case BuiltinType::Double: return DoubleRank;
3376 case BuiltinType::LongDouble: return LongDoubleRank;
3377 }
3378}
3379
Mike Stump1eb44332009-09-09 15:08:12 +00003380/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3381/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003382/// 'typeDomain' is a real floating point or complex type.
3383/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003384QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3385 QualType Domain) const {
3386 FloatingRank EltRank = getFloatingRank(Size);
3387 if (Domain->isComplexType()) {
3388 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00003389 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003390 case FloatRank: return FloatComplexTy;
3391 case DoubleRank: return DoubleComplexTy;
3392 case LongDoubleRank: return LongDoubleComplexTy;
3393 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003394 }
Chris Lattner1361b112008-04-06 23:58:54 +00003395
3396 assert(Domain->isRealFloatingType() && "Unknown domain!");
3397 switch (EltRank) {
3398 default: assert(0 && "getFloatingRank(): illegal value for rank");
3399 case FloatRank: return FloatTy;
3400 case DoubleRank: return DoubleTy;
3401 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003402 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003403}
3404
Chris Lattner7cfeb082008-04-06 23:55:33 +00003405/// getFloatingTypeOrder - Compare the rank of the two specified floating
3406/// point types, ignoring the domain of the type (i.e. 'double' ==
3407/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003408/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003409int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003410 FloatingRank LHSR = getFloatingRank(LHS);
3411 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Chris Lattnera75cea32008-04-06 23:38:49 +00003413 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003414 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003415 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003416 return 1;
3417 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003418}
3419
Chris Lattnerf52ab252008-04-06 22:59:24 +00003420/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3421/// routine will assert if passed a built-in type that isn't an integer or enum,
3422/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003423unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003424 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCallf4c73712011-01-19 06:33:43 +00003425 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00003426 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00003427
Chris Lattner3f59c972010-12-25 23:25:43 +00003428 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3429 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmana3426752009-07-05 23:44:27 +00003430 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3431
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003432 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3433 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3434
3435 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3436 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3437
Chris Lattnerf52ab252008-04-06 22:59:24 +00003438 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00003439 default: assert(0 && "getIntegerRank(): not a built-in integer");
3440 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003441 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003442 case BuiltinType::Char_S:
3443 case BuiltinType::Char_U:
3444 case BuiltinType::SChar:
3445 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003446 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003447 case BuiltinType::Short:
3448 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003449 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003450 case BuiltinType::Int:
3451 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003452 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003453 case BuiltinType::Long:
3454 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003455 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003456 case BuiltinType::LongLong:
3457 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003458 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003459 case BuiltinType::Int128:
3460 case BuiltinType::UInt128:
3461 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003462 }
3463}
3464
Eli Friedman04e83572009-08-20 04:21:42 +00003465/// \brief Whether this is a promotable bitfield reference according
3466/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3467///
3468/// \returns the type this bit-field will promote to, or NULL if no
3469/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003470QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003471 if (E->isTypeDependent() || E->isValueDependent())
3472 return QualType();
3473
Eli Friedman04e83572009-08-20 04:21:42 +00003474 FieldDecl *Field = E->getBitField();
3475 if (!Field)
3476 return QualType();
3477
3478 QualType FT = Field->getType();
3479
3480 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3481 uint64_t BitWidth = BitWidthAP.getZExtValue();
3482 uint64_t IntSize = getTypeSize(IntTy);
3483 // GCC extension compatibility: if the bit-field size is less than or equal
3484 // to the size of int, it gets promoted no matter what its type is.
3485 // For instance, unsigned long bf : 4 gets promoted to signed int.
3486 if (BitWidth < IntSize)
3487 return IntTy;
3488
3489 if (BitWidth == IntSize)
3490 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3491
3492 // Types bigger than int are not subject to promotions, and therefore act
3493 // like the base type.
3494 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3495 // is ridiculous.
3496 return QualType();
3497}
3498
Eli Friedmana95d7572009-08-19 07:44:53 +00003499/// getPromotedIntegerType - Returns the type that Promotable will
3500/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3501/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003502QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003503 assert(!Promotable.isNull());
3504 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003505 if (const EnumType *ET = Promotable->getAs<EnumType>())
3506 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003507 if (Promotable->isSignedIntegerType())
3508 return IntTy;
3509 uint64_t PromotableSize = getTypeSize(Promotable);
3510 uint64_t IntSize = getTypeSize(IntTy);
3511 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3512 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3513}
3514
Mike Stump1eb44332009-09-09 15:08:12 +00003515/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003516/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003517/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003518int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003519 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3520 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003521 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003522
Chris Lattnerf52ab252008-04-06 22:59:24 +00003523 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3524 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003525
Chris Lattner7cfeb082008-04-06 23:55:33 +00003526 unsigned LHSRank = getIntegerRank(LHSC);
3527 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003528
Chris Lattner7cfeb082008-04-06 23:55:33 +00003529 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3530 if (LHSRank == RHSRank) return 0;
3531 return LHSRank > RHSRank ? 1 : -1;
3532 }
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Chris Lattner7cfeb082008-04-06 23:55:33 +00003534 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3535 if (LHSUnsigned) {
3536 // If the unsigned [LHS] type is larger, return it.
3537 if (LHSRank >= RHSRank)
3538 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003539
Chris Lattner7cfeb082008-04-06 23:55:33 +00003540 // If the signed type can represent all values of the unsigned type, it
3541 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003542 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003543 return -1;
3544 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003545
Chris Lattner7cfeb082008-04-06 23:55:33 +00003546 // If the unsigned [RHS] type is larger, return it.
3547 if (RHSRank >= LHSRank)
3548 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003549
Chris Lattner7cfeb082008-04-06 23:55:33 +00003550 // If the signed type can represent all values of the unsigned type, it
3551 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003552 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003553 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003554}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003555
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003556static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003557CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3558 DeclContext *DC, IdentifierInfo *Id) {
3559 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003560 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003561 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003562 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003563 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003564}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003565
Mike Stump1eb44332009-09-09 15:08:12 +00003566// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003567QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003568 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003569 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003570 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003571 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003572 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003573
Anders Carlssonf06273f2007-11-19 00:25:30 +00003574 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003575
Anders Carlsson71993dd2007-08-17 05:31:46 +00003576 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003577 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003578 // int flags;
3579 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003580 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003581 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003582 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003583 FieldTypes[3] = LongTy;
3584
Anders Carlsson71993dd2007-08-17 05:31:46 +00003585 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003586 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003587 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003588 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003589 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003590 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003591 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003592 /*Mutable=*/false,
3593 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003594 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003595 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003596 }
3597
Douglas Gregor838db382010-02-11 01:19:42 +00003598 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003599 }
Mike Stump1eb44332009-09-09 15:08:12 +00003600
Anders Carlsson71993dd2007-08-17 05:31:46 +00003601 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003602}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003603
Douglas Gregor319ac892009-04-23 22:29:11 +00003604void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003605 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003606 assert(Rec && "Invalid CFConstantStringType");
3607 CFConstantStringTypeDecl = Rec->getDecl();
3608}
3609
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003610// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003611QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003612 if (!NSConstantStringTypeDecl) {
3613 NSConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003614 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003615 &Idents.get("__builtin_NSString"));
3616 NSConstantStringTypeDecl->startDefinition();
3617
3618 QualType FieldTypes[3];
3619
3620 // const int *isa;
3621 FieldTypes[0] = getPointerType(IntTy.withConst());
3622 // const char *str;
3623 FieldTypes[1] = getPointerType(CharTy.withConst());
3624 // unsigned int length;
3625 FieldTypes[2] = UnsignedIntTy;
3626
3627 // Create fields
3628 for (unsigned i = 0; i < 3; ++i) {
3629 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003630 SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003631 SourceLocation(), 0,
3632 FieldTypes[i], /*TInfo=*/0,
3633 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003634 /*Mutable=*/false,
3635 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003636 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003637 NSConstantStringTypeDecl->addDecl(Field);
3638 }
3639
3640 NSConstantStringTypeDecl->completeDefinition();
3641 }
3642
3643 return getTagDeclType(NSConstantStringTypeDecl);
3644}
3645
3646void ASTContext::setNSConstantStringType(QualType T) {
3647 const RecordType *Rec = T->getAs<RecordType>();
3648 assert(Rec && "Invalid NSConstantStringType");
3649 NSConstantStringTypeDecl = Rec->getDecl();
3650}
3651
Jay Foad4ba2a172011-01-12 09:06:06 +00003652QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003653 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003654 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003655 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003656 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003657 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003658
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003659 QualType FieldTypes[] = {
3660 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003661 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003662 getPointerType(UnsignedLongTy),
3663 getConstantArrayType(UnsignedLongTy,
3664 llvm::APInt(32, 5), ArrayType::Normal, 0)
3665 };
Mike Stump1eb44332009-09-09 15:08:12 +00003666
Douglas Gregor44b43212008-12-11 16:49:14 +00003667 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003668 FieldDecl *Field = FieldDecl::Create(*this,
3669 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003670 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003671 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003672 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003673 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003674 /*Mutable=*/false,
3675 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003676 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003677 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003678 }
Mike Stump1eb44332009-09-09 15:08:12 +00003679
Douglas Gregor838db382010-02-11 01:19:42 +00003680 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003681 }
Mike Stump1eb44332009-09-09 15:08:12 +00003682
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003683 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3684}
3685
Jay Foad4ba2a172011-01-12 09:06:06 +00003686QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003687 if (BlockDescriptorType)
3688 return getTagDeclType(BlockDescriptorType);
3689
3690 RecordDecl *T;
3691 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003692 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003693 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003694 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003695
3696 QualType FieldTypes[] = {
3697 UnsignedLongTy,
3698 UnsignedLongTy,
3699 };
3700
3701 const char *FieldNames[] = {
3702 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003703 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003704 };
3705
3706 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003707 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003708 SourceLocation(),
3709 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003710 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003711 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003712 /*Mutable=*/false,
3713 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003714 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003715 T->addDecl(Field);
3716 }
3717
Douglas Gregor838db382010-02-11 01:19:42 +00003718 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003719
3720 BlockDescriptorType = T;
3721
3722 return getTagDeclType(BlockDescriptorType);
3723}
3724
3725void ASTContext::setBlockDescriptorType(QualType T) {
3726 const RecordType *Rec = T->getAs<RecordType>();
3727 assert(Rec && "Invalid BlockDescriptorType");
3728 BlockDescriptorType = Rec->getDecl();
3729}
3730
Jay Foad4ba2a172011-01-12 09:06:06 +00003731QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003732 if (BlockDescriptorExtendedType)
3733 return getTagDeclType(BlockDescriptorExtendedType);
3734
3735 RecordDecl *T;
3736 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003737 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003738 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003739 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003740
3741 QualType FieldTypes[] = {
3742 UnsignedLongTy,
3743 UnsignedLongTy,
3744 getPointerType(VoidPtrTy),
3745 getPointerType(VoidPtrTy)
3746 };
3747
3748 const char *FieldNames[] = {
3749 "reserved",
3750 "Size",
3751 "CopyFuncPtr",
3752 "DestroyFuncPtr"
3753 };
3754
3755 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003756 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003757 SourceLocation(),
3758 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003759 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003760 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003761 /*Mutable=*/false,
3762 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003763 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003764 T->addDecl(Field);
3765 }
3766
Douglas Gregor838db382010-02-11 01:19:42 +00003767 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003768
3769 BlockDescriptorExtendedType = T;
3770
3771 return getTagDeclType(BlockDescriptorExtendedType);
3772}
3773
3774void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3775 const RecordType *Rec = T->getAs<RecordType>();
3776 assert(Rec && "Invalid BlockDescriptorType");
3777 BlockDescriptorExtendedType = Rec->getDecl();
3778}
3779
Jay Foad4ba2a172011-01-12 09:06:06 +00003780bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003781 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003782 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003783 if (getLangOptions().CPlusPlus) {
3784 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3785 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003786 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003787
3788 }
3789 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003790 return false;
3791}
3792
Jay Foad4ba2a172011-01-12 09:06:06 +00003793QualType
3794ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003795 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003796 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003797 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003798 // unsigned int __flags;
3799 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003800 // void *__copy_helper; // as needed
3801 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003802 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003803 // } *
3804
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003805 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3806
3807 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003808 llvm::SmallString<36> Name;
3809 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3810 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003811 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003812 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003813 T->startDefinition();
3814 QualType Int32Ty = IntTy;
3815 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3816 QualType FieldTypes[] = {
3817 getPointerType(VoidPtrTy),
3818 getPointerType(getTagDeclType(T)),
3819 Int32Ty,
3820 Int32Ty,
3821 getPointerType(VoidPtrTy),
3822 getPointerType(VoidPtrTy),
3823 Ty
3824 };
3825
Daniel Dunbar4087f272010-08-17 22:39:59 +00003826 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003827 "__isa",
3828 "__forwarding",
3829 "__flags",
3830 "__size",
3831 "__copy_helper",
3832 "__destroy_helper",
3833 DeclName,
3834 };
3835
3836 for (size_t i = 0; i < 7; ++i) {
3837 if (!HasCopyAndDispose && i >=4 && i <= 5)
3838 continue;
3839 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003840 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003841 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003842 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003843 /*BitWidth=*/0, /*Mutable=*/false,
3844 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003845 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003846 T->addDecl(Field);
3847 }
3848
Douglas Gregor838db382010-02-11 01:19:42 +00003849 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003850
3851 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003852}
3853
Douglas Gregor319ac892009-04-23 22:29:11 +00003854void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003855 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003856 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3857 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3858}
3859
Anders Carlssone8c49532007-10-29 06:33:42 +00003860// This returns true if a type has been typedefed to BOOL:
3861// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003862static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003863 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003864 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3865 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003866
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003867 return false;
3868}
3869
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003870/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003871/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003872CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00003873 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3874 return CharUnits::Zero();
3875
Ken Dyck199c3d62010-01-11 17:06:35 +00003876 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003877
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003878 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003879 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003880 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003881 // Treat arrays as pointers, since that's how they're passed in.
3882 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003883 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003884 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003885}
3886
3887static inline
3888std::string charUnitsToString(const CharUnits &CU) {
3889 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003890}
3891
John McCall6b5a61b2011-02-07 10:33:21 +00003892/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003893/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00003894std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3895 std::string S;
3896
David Chisnall5e530af2009-11-17 19:33:30 +00003897 const BlockDecl *Decl = Expr->getBlockDecl();
3898 QualType BlockTy =
3899 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3900 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003901 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003902 // Compute size of all parameters.
3903 // Start with computing size of a pointer in number of bytes.
3904 // FIXME: There might(should) be a better way of doing this computation!
3905 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003906 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3907 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003908 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003909 E = Decl->param_end(); PI != E; ++PI) {
3910 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003911 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003912 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003913 ParmOffset += sz;
3914 }
3915 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003916 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003917 // Block pointer and offset.
3918 S += "@?0";
3919 ParmOffset = PtrSize;
3920
3921 // Argument types.
3922 ParmOffset = PtrSize;
3923 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3924 Decl->param_end(); PI != E; ++PI) {
3925 ParmVarDecl *PVDecl = *PI;
3926 QualType PType = PVDecl->getOriginalType();
3927 if (const ArrayType *AT =
3928 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3929 // Use array's original type only if it has known number of
3930 // elements.
3931 if (!isa<ConstantArrayType>(AT))
3932 PType = PVDecl->getType();
3933 } else if (PType->isFunctionType())
3934 PType = PVDecl->getType();
3935 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003936 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003937 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003938 }
John McCall6b5a61b2011-02-07 10:33:21 +00003939
3940 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00003941}
3942
Douglas Gregorf968d832011-05-27 01:19:52 +00003943bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00003944 std::string& S) {
3945 // Encode result type.
3946 getObjCEncodingForType(Decl->getResultType(), S);
3947 CharUnits ParmOffset;
3948 // Compute size of all parameters.
3949 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3950 E = Decl->param_end(); PI != E; ++PI) {
3951 QualType PType = (*PI)->getType();
3952 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00003953 if (sz.isZero())
3954 return true;
3955
David Chisnall5389f482010-12-30 14:05:53 +00003956 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00003957 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00003958 ParmOffset += sz;
3959 }
3960 S += charUnitsToString(ParmOffset);
3961 ParmOffset = CharUnits::Zero();
3962
3963 // Argument types.
3964 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3965 E = Decl->param_end(); PI != E; ++PI) {
3966 ParmVarDecl *PVDecl = *PI;
3967 QualType PType = PVDecl->getOriginalType();
3968 if (const ArrayType *AT =
3969 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3970 // Use array's original type only if it has known number of
3971 // elements.
3972 if (!isa<ConstantArrayType>(AT))
3973 PType = PVDecl->getType();
3974 } else if (PType->isFunctionType())
3975 PType = PVDecl->getType();
3976 getObjCEncodingForType(PType, S);
3977 S += charUnitsToString(ParmOffset);
3978 ParmOffset += getObjCEncodingTypeSize(PType);
3979 }
Douglas Gregorf968d832011-05-27 01:19:52 +00003980
3981 return false;
David Chisnall5389f482010-12-30 14:05:53 +00003982}
3983
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003984/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003985/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00003986bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00003987 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003988 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003989 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003990 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003991 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003992 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003993 // Compute size of all parameters.
3994 // Start with computing size of a pointer in number of bytes.
3995 // FIXME: There might(should) be a better way of doing this computation!
3996 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003997 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003998 // The first two arguments (self and _cmd) are pointers; account for
3999 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004000 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00004001 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004002 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004003 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004004 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004005 if (sz.isZero())
4006 return true;
4007
Ken Dyck199c3d62010-01-11 17:06:35 +00004008 assert (sz.isPositive() &&
4009 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004010 ParmOffset += sz;
4011 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004012 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004013 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004014 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004015
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004016 // Argument types.
4017 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00004018 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004019 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004020 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004021 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004022 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004023 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4024 // Use array's original type only if it has known number of
4025 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004026 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004027 PType = PVDecl->getType();
4028 } else if (PType->isFunctionType())
4029 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004030 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004031 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004032 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004033 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004034 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004035 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004036 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004037
4038 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004039}
4040
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004041/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004042/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004043/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4044/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004045/// Property attributes are stored as a comma-delimited C string. The simple
4046/// attributes readonly and bycopy are encoded as single characters. The
4047/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4048/// encoded as single characters, followed by an identifier. Property types
4049/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004050/// these attributes are defined by the following enumeration:
4051/// @code
4052/// enum PropertyAttributes {
4053/// kPropertyReadOnly = 'R', // property is read-only.
4054/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4055/// kPropertyByref = '&', // property is a reference to the value last assigned
4056/// kPropertyDynamic = 'D', // property is dynamic
4057/// kPropertyGetter = 'G', // followed by getter selector name
4058/// kPropertySetter = 'S', // followed by setter selector name
4059/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4060/// kPropertyType = 't' // followed by old-style type encoding.
4061/// kPropertyWeak = 'W' // 'weak' property
4062/// kPropertyStrong = 'P' // property GC'able
4063/// kPropertyNonAtomic = 'N' // property non-atomic
4064/// };
4065/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004066void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004067 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004068 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004069 // Collect information from the property implementation decl(s).
4070 bool Dynamic = false;
4071 ObjCPropertyImplDecl *SynthesizePID = 0;
4072
4073 // FIXME: Duplicated code due to poor abstraction.
4074 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004075 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004076 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4077 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004078 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004079 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004080 ObjCPropertyImplDecl *PID = *i;
4081 if (PID->getPropertyDecl() == PD) {
4082 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4083 Dynamic = true;
4084 } else {
4085 SynthesizePID = PID;
4086 }
4087 }
4088 }
4089 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004090 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004091 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004092 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004093 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004094 ObjCPropertyImplDecl *PID = *i;
4095 if (PID->getPropertyDecl() == PD) {
4096 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4097 Dynamic = true;
4098 } else {
4099 SynthesizePID = PID;
4100 }
4101 }
Mike Stump1eb44332009-09-09 15:08:12 +00004102 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004103 }
4104 }
4105
4106 // FIXME: This is not very efficient.
4107 S = "T";
4108
4109 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004110 // GCC has some special rules regarding encoding of properties which
4111 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004112 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004113 true /* outermost type */,
4114 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004115
4116 if (PD->isReadOnly()) {
4117 S += ",R";
4118 } else {
4119 switch (PD->getSetterKind()) {
4120 case ObjCPropertyDecl::Assign: break;
4121 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004122 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004123 }
4124 }
4125
4126 // It really isn't clear at all what this means, since properties
4127 // are "dynamic by default".
4128 if (Dynamic)
4129 S += ",D";
4130
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004131 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4132 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004133
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004134 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4135 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004136 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004137 }
4138
4139 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4140 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004141 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004142 }
4143
4144 if (SynthesizePID) {
4145 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4146 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004147 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004148 }
4149
4150 // FIXME: OBJCGC: weak & strong
4151}
4152
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004153/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004154/// Another legacy compatibility encoding: 32-bit longs are encoded as
4155/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004156/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4157///
4158void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004159 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004160 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004161 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004162 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004163 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004164 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004165 PointeeTy = IntTy;
4166 }
4167 }
4168}
4169
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004170void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004171 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004172 // We follow the behavior of gcc, expanding structures which are
4173 // directly pointed to, and expanding embedded structures. Note that
4174 // these rules are sufficient to prevent recursive encoding of the
4175 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004176 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004177 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004178}
4179
David Chisnall64fd7e82010-06-04 01:10:52 +00004180static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4181 switch (T->getAs<BuiltinType>()->getKind()) {
4182 default: assert(0 && "Unhandled builtin type kind");
4183 case BuiltinType::Void: return 'v';
4184 case BuiltinType::Bool: return 'B';
4185 case BuiltinType::Char_U:
4186 case BuiltinType::UChar: return 'C';
4187 case BuiltinType::UShort: return 'S';
4188 case BuiltinType::UInt: return 'I';
4189 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004190 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004191 case BuiltinType::UInt128: return 'T';
4192 case BuiltinType::ULongLong: return 'Q';
4193 case BuiltinType::Char_S:
4194 case BuiltinType::SChar: return 'c';
4195 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004196 case BuiltinType::WChar_S:
4197 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004198 case BuiltinType::Int: return 'i';
4199 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004200 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004201 case BuiltinType::LongLong: return 'q';
4202 case BuiltinType::Int128: return 't';
4203 case BuiltinType::Float: return 'f';
4204 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004205 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004206 }
4207}
4208
Jay Foad4ba2a172011-01-12 09:06:06 +00004209static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004210 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004211 const Expr *E = FD->getBitWidth();
4212 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004213 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004214 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4215 // The GNU runtime requires more information; bitfields are encoded as b,
4216 // then the offset (in bits) of the first element, then the type of the
4217 // bitfield, then the size in bits. For example, in this structure:
4218 //
4219 // struct
4220 // {
4221 // int integer;
4222 // int flags:2;
4223 // };
4224 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4225 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4226 // information is not especially sensible, but we're stuck with it for
4227 // compatibility with GCC, although providing it breaks anything that
4228 // actually uses runtime introspection and wants to work on both runtimes...
4229 if (!Ctx->getLangOptions().NeXTRuntime) {
4230 const RecordDecl *RD = FD->getParent();
4231 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4232 // FIXME: This same linear search is also used in ExprConstant - it might
4233 // be better if the FieldDecl stored its offset. We'd be increasing the
4234 // size of the object slightly, but saving some time every time it is used.
4235 unsigned i = 0;
4236 for (RecordDecl::field_iterator Field = RD->field_begin(),
4237 FieldEnd = RD->field_end();
4238 Field != FieldEnd; (void)++Field, ++i) {
4239 if (*Field == FD)
4240 break;
4241 }
4242 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnallc7ff82c2010-12-26 20:12:30 +00004243 if (T->isEnumeralType())
4244 S += 'i';
4245 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004246 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004247 }
4248 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004249 S += llvm::utostr(N);
4250}
4251
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004252// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004253void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4254 bool ExpandPointedToStructures,
4255 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004256 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004257 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004258 bool EncodingProperty,
4259 bool StructField) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004260 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004261 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004262 return EncodeBitField(this, S, T, FD);
4263 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004264 return;
4265 }
Mike Stump1eb44332009-09-09 15:08:12 +00004266
John McCall183700f2009-09-21 23:43:11 +00004267 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004268 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004269 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004270 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004271 return;
4272 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004273
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004274 // encoding for pointer or r3eference types.
4275 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004276 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004277 if (PT->isObjCSelType()) {
4278 S += ':';
4279 return;
4280 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004281 PointeeTy = PT->getPointeeType();
4282 }
4283 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4284 PointeeTy = RT->getPointeeType();
4285 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004286 bool isReadOnly = false;
4287 // For historical/compatibility reasons, the read-only qualifier of the
4288 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4289 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004290 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004291 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004292 if (OutermostType && T.isConstQualified()) {
4293 isReadOnly = true;
4294 S += 'r';
4295 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004296 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004297 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004298 while (P->getAs<PointerType>())
4299 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004300 if (P.isConstQualified()) {
4301 isReadOnly = true;
4302 S += 'r';
4303 }
4304 }
4305 if (isReadOnly) {
4306 // Another legacy compatibility encoding. Some ObjC qualifier and type
4307 // combinations need to be rearranged.
4308 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00004309 if (llvm::StringRef(S).endswith("nr"))
4310 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004311 }
Mike Stump1eb44332009-09-09 15:08:12 +00004312
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004313 if (PointeeTy->isCharType()) {
4314 // char pointer types should be encoded as '*' unless it is a
4315 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004316 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004317 S += '*';
4318 return;
4319 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004320 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004321 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4322 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4323 S += '#';
4324 return;
4325 }
4326 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4327 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4328 S += '@';
4329 return;
4330 }
4331 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004332 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004333 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004334 getLegacyIntegralTypeEncoding(PointeeTy);
4335
Mike Stump1eb44332009-09-09 15:08:12 +00004336 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004337 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004338 return;
4339 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004340
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004341 if (const ArrayType *AT =
4342 // Ignore type qualifiers etc.
4343 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004344 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004345 // Incomplete arrays are encoded as a pointer to the array element.
4346 S += '^';
4347
Mike Stump1eb44332009-09-09 15:08:12 +00004348 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004349 false, ExpandStructures, FD);
4350 } else {
4351 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004352
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004353 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4354 if (getTypeSize(CAT->getElementType()) == 0)
4355 S += '0';
4356 else
4357 S += llvm::utostr(CAT->getSize().getZExtValue());
4358 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004359 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004360 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4361 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004362 S += '0';
4363 }
Mike Stump1eb44332009-09-09 15:08:12 +00004364
4365 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004366 false, ExpandStructures, FD);
4367 S += ']';
4368 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004369 return;
4370 }
Mike Stump1eb44332009-09-09 15:08:12 +00004371
John McCall183700f2009-09-21 23:43:11 +00004372 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004373 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004374 return;
4375 }
Mike Stump1eb44332009-09-09 15:08:12 +00004376
Ted Kremenek6217b802009-07-29 21:53:49 +00004377 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004378 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004379 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004380 // Anonymous structures print as '?'
4381 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4382 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004383 if (ClassTemplateSpecializationDecl *Spec
4384 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4385 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4386 std::string TemplateArgsStr
4387 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004388 TemplateArgs.data(),
4389 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004390 (*this).PrintingPolicy);
4391
4392 S += TemplateArgsStr;
4393 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004394 } else {
4395 S += '?';
4396 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004397 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004398 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004399 if (!RDecl->isUnion()) {
4400 getObjCEncodingForStructureImpl(RDecl, S, FD);
4401 } else {
4402 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4403 FieldEnd = RDecl->field_end();
4404 Field != FieldEnd; ++Field) {
4405 if (FD) {
4406 S += '"';
4407 S += Field->getNameAsString();
4408 S += '"';
4409 }
Mike Stump1eb44332009-09-09 15:08:12 +00004410
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004411 // Special case bit-fields.
4412 if (Field->isBitField()) {
4413 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4414 (*Field));
4415 } else {
4416 QualType qt = Field->getType();
4417 getLegacyIntegralTypeEncoding(qt);
4418 getObjCEncodingForTypeImpl(qt, S, false, true,
4419 FD, /*OutermostType*/false,
4420 /*EncodingProperty*/false,
4421 /*StructField*/true);
4422 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004423 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004424 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004425 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004426 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004427 return;
4428 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004429
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004430 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004431 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004432 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004433 else
4434 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004435 return;
4436 }
Mike Stump1eb44332009-09-09 15:08:12 +00004437
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004438 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004439 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004440 return;
4441 }
Mike Stump1eb44332009-09-09 15:08:12 +00004442
John McCallc12c5bb2010-05-15 11:32:37 +00004443 // Ignore protocol qualifiers when mangling at this level.
4444 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4445 T = OT->getBaseType();
4446
John McCall0953e762009-09-24 19:53:00 +00004447 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004448 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004449 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004450 S += '{';
4451 const IdentifierInfo *II = OI->getIdentifier();
4452 S += II->getName();
4453 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004454 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4455 DeepCollectObjCIvars(OI, true, Ivars);
4456 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4457 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4458 if (Field->isBitField())
4459 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004460 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004461 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004462 }
4463 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004464 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004465 }
Mike Stump1eb44332009-09-09 15:08:12 +00004466
John McCall183700f2009-09-21 23:43:11 +00004467 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004468 if (OPT->isObjCIdType()) {
4469 S += '@';
4470 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004471 }
Mike Stump1eb44332009-09-09 15:08:12 +00004472
Steve Naroff27d20a22009-10-28 22:03:49 +00004473 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4474 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4475 // Since this is a binary compatibility issue, need to consult with runtime
4476 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004477 S += '#';
4478 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004479 }
Mike Stump1eb44332009-09-09 15:08:12 +00004480
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004481 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004482 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004483 ExpandPointedToStructures,
4484 ExpandStructures, FD);
4485 if (FD || EncodingProperty) {
4486 // Note that we do extended encoding of protocol qualifer list
4487 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004488 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004489 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4490 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004491 S += '<';
4492 S += (*I)->getNameAsString();
4493 S += '>';
4494 }
4495 S += '"';
4496 }
4497 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004498 }
Mike Stump1eb44332009-09-09 15:08:12 +00004499
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004500 QualType PointeeTy = OPT->getPointeeType();
4501 if (!EncodingProperty &&
4502 isa<TypedefType>(PointeeTy.getTypePtr())) {
4503 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004504 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004505 // {...};
4506 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004507 getObjCEncodingForTypeImpl(PointeeTy, S,
4508 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004509 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004510 return;
4511 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004512
4513 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004514 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004515 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004516 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004517 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4518 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004519 S += '<';
4520 S += (*I)->getNameAsString();
4521 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004522 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004523 S += '"';
4524 }
4525 return;
4526 }
Mike Stump1eb44332009-09-09 15:08:12 +00004527
John McCall532ec7b2010-05-17 23:56:34 +00004528 // gcc just blithely ignores member pointers.
4529 // TODO: maybe there should be a mangling for these
4530 if (T->getAs<MemberPointerType>())
4531 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004532
4533 if (T->isVectorType()) {
4534 // This matches gcc's encoding, even though technically it is
4535 // insufficient.
4536 // FIXME. We should do a better job than gcc.
4537 return;
4538 }
4539
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004540 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004541}
4542
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004543void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4544 std::string &S,
4545 const FieldDecl *FD,
4546 bool includeVBases) const {
4547 assert(RDecl && "Expected non-null RecordDecl");
4548 assert(!RDecl->isUnion() && "Should not be called for unions");
4549 if (!RDecl->getDefinition())
4550 return;
4551
4552 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4553 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4554 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4555
4556 if (CXXRec) {
4557 for (CXXRecordDecl::base_class_iterator
4558 BI = CXXRec->bases_begin(),
4559 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4560 if (!BI->isVirtual()) {
4561 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004562 if (base->isEmpty())
4563 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004564 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4565 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4566 std::make_pair(offs, base));
4567 }
4568 }
4569 }
4570
4571 unsigned i = 0;
4572 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4573 FieldEnd = RDecl->field_end();
4574 Field != FieldEnd; ++Field, ++i) {
4575 uint64_t offs = layout.getFieldOffset(i);
4576 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4577 std::make_pair(offs, *Field));
4578 }
4579
4580 if (CXXRec && includeVBases) {
4581 for (CXXRecordDecl::base_class_iterator
4582 BI = CXXRec->vbases_begin(),
4583 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4584 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004585 if (base->isEmpty())
4586 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004587 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4588 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4589 std::make_pair(offs, base));
4590 }
4591 }
4592
4593 CharUnits size;
4594 if (CXXRec) {
4595 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4596 } else {
4597 size = layout.getSize();
4598 }
4599
4600 uint64_t CurOffs = 0;
4601 std::multimap<uint64_t, NamedDecl *>::iterator
4602 CurLayObj = FieldOrBaseOffsets.begin();
4603
4604 if (CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) {
4605 assert(CXXRec && CXXRec->isDynamicClass() &&
4606 "Offset 0 was empty but no VTable ?");
4607 if (FD) {
4608 S += "\"_vptr$";
4609 std::string recname = CXXRec->getNameAsString();
4610 if (recname.empty()) recname = "?";
4611 S += recname;
4612 S += '"';
4613 }
4614 S += "^^?";
4615 CurOffs += getTypeSize(VoidPtrTy);
4616 }
4617
4618 if (!RDecl->hasFlexibleArrayMember()) {
4619 // Mark the end of the structure.
4620 uint64_t offs = toBits(size);
4621 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4622 std::make_pair(offs, (NamedDecl*)0));
4623 }
4624
4625 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4626 assert(CurOffs <= CurLayObj->first);
4627
4628 if (CurOffs < CurLayObj->first) {
4629 uint64_t padding = CurLayObj->first - CurOffs;
4630 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4631 // packing/alignment of members is different that normal, in which case
4632 // the encoding will be out-of-sync with the real layout.
4633 // If the runtime switches to just consider the size of types without
4634 // taking into account alignment, we could make padding explicit in the
4635 // encoding (e.g. using arrays of chars). The encoding strings would be
4636 // longer then though.
4637 CurOffs += padding;
4638 }
4639
4640 NamedDecl *dcl = CurLayObj->second;
4641 if (dcl == 0)
4642 break; // reached end of structure.
4643
4644 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4645 // We expand the bases without their virtual bases since those are going
4646 // in the initial structure. Note that this differs from gcc which
4647 // expands virtual bases each time one is encountered in the hierarchy,
4648 // making the encoding type bigger than it really is.
4649 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004650 assert(!base->isEmpty());
4651 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004652 } else {
4653 FieldDecl *field = cast<FieldDecl>(dcl);
4654 if (FD) {
4655 S += '"';
4656 S += field->getNameAsString();
4657 S += '"';
4658 }
4659
4660 if (field->isBitField()) {
4661 EncodeBitField(this, S, field->getType(), field);
4662 CurOffs += field->getBitWidth()->EvaluateAsInt(*this).getZExtValue();
4663 } else {
4664 QualType qt = field->getType();
4665 getLegacyIntegralTypeEncoding(qt);
4666 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4667 /*OutermostType*/false,
4668 /*EncodingProperty*/false,
4669 /*StructField*/true);
4670 CurOffs += getTypeSize(field->getType());
4671 }
4672 }
4673 }
4674}
4675
Mike Stump1eb44332009-09-09 15:08:12 +00004676void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004677 std::string& S) const {
4678 if (QT & Decl::OBJC_TQ_In)
4679 S += 'n';
4680 if (QT & Decl::OBJC_TQ_Inout)
4681 S += 'N';
4682 if (QT & Decl::OBJC_TQ_Out)
4683 S += 'o';
4684 if (QT & Decl::OBJC_TQ_Bycopy)
4685 S += 'O';
4686 if (QT & Decl::OBJC_TQ_Byref)
4687 S += 'R';
4688 if (QT & Decl::OBJC_TQ_Oneway)
4689 S += 'V';
4690}
4691
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004692void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004693 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004694
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004695 BuiltinVaListType = T;
4696}
4697
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004698void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004699 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00004700}
4701
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004702void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004703 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004704}
4705
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004706void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004707 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004708}
4709
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004710void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004711 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004712}
4713
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004714void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004715 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004716 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004717
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004718 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004719}
4720
John McCall0bd6feb2009-12-02 08:04:21 +00004721/// \brief Retrieve the template name that corresponds to a non-empty
4722/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004723TemplateName
4724ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4725 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004726 unsigned size = End - Begin;
4727 assert(size > 1 && "set is not overloaded!");
4728
4729 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4730 size * sizeof(FunctionTemplateDecl*));
4731 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4732
4733 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004734 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004735 NamedDecl *D = *I;
4736 assert(isa<FunctionTemplateDecl>(D) ||
4737 (isa<UsingShadowDecl>(D) &&
4738 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4739 *Storage++ = D;
4740 }
4741
4742 return TemplateName(OT);
4743}
4744
Douglas Gregor7532dc62009-03-30 22:58:21 +00004745/// \brief Retrieve the template name that represents a qualified
4746/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004747TemplateName
4748ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4749 bool TemplateKeyword,
4750 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004751 assert(NNS && "Missing nested-name-specifier in qualified template name");
4752
Douglas Gregor789b1f62010-02-04 18:10:26 +00004753 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004754 llvm::FoldingSetNodeID ID;
4755 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4756
4757 void *InsertPos = 0;
4758 QualifiedTemplateName *QTN =
4759 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4760 if (!QTN) {
4761 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4762 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4763 }
4764
4765 return TemplateName(QTN);
4766}
4767
4768/// \brief Retrieve the template name that represents a dependent
4769/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004770TemplateName
4771ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4772 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004773 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004774 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004775
4776 llvm::FoldingSetNodeID ID;
4777 DependentTemplateName::Profile(ID, NNS, Name);
4778
4779 void *InsertPos = 0;
4780 DependentTemplateName *QTN =
4781 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4782
4783 if (QTN)
4784 return TemplateName(QTN);
4785
4786 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4787 if (CanonNNS == NNS) {
4788 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4789 } else {
4790 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4791 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004792 DependentTemplateName *CheckQTN =
4793 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4794 assert(!CheckQTN && "Dependent type name canonicalization broken");
4795 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004796 }
4797
4798 DependentTemplateNames.InsertNode(QTN, InsertPos);
4799 return TemplateName(QTN);
4800}
4801
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004802/// \brief Retrieve the template name that represents a dependent
4803/// template name such as \c MetaFun::template operator+.
4804TemplateName
4805ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004806 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004807 assert((!NNS || NNS->isDependent()) &&
4808 "Nested name specifier must be dependent");
4809
4810 llvm::FoldingSetNodeID ID;
4811 DependentTemplateName::Profile(ID, NNS, Operator);
4812
4813 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004814 DependentTemplateName *QTN
4815 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004816
4817 if (QTN)
4818 return TemplateName(QTN);
4819
4820 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4821 if (CanonNNS == NNS) {
4822 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4823 } else {
4824 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4825 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004826
4827 DependentTemplateName *CheckQTN
4828 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4829 assert(!CheckQTN && "Dependent template name canonicalization broken");
4830 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004831 }
4832
4833 DependentTemplateNames.InsertNode(QTN, InsertPos);
4834 return TemplateName(QTN);
4835}
4836
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004837TemplateName
John McCall14606042011-06-30 08:33:18 +00004838ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4839 TemplateName replacement) const {
4840 llvm::FoldingSetNodeID ID;
4841 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4842
4843 void *insertPos = 0;
4844 SubstTemplateTemplateParmStorage *subst
4845 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4846
4847 if (!subst) {
4848 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4849 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4850 }
4851
4852 return TemplateName(subst);
4853}
4854
4855TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004856ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4857 const TemplateArgument &ArgPack) const {
4858 ASTContext &Self = const_cast<ASTContext &>(*this);
4859 llvm::FoldingSetNodeID ID;
4860 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4861
4862 void *InsertPos = 0;
4863 SubstTemplateTemplateParmPackStorage *Subst
4864 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4865
4866 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00004867 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004868 ArgPack.pack_size(),
4869 ArgPack.pack_begin());
4870 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4871 }
4872
4873 return TemplateName(Subst);
4874}
4875
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004876/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004877/// TargetInfo, produce the corresponding type. The unsigned @p Type
4878/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004879CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004880 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004881 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004882 case TargetInfo::SignedShort: return ShortTy;
4883 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4884 case TargetInfo::SignedInt: return IntTy;
4885 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4886 case TargetInfo::SignedLong: return LongTy;
4887 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4888 case TargetInfo::SignedLongLong: return LongLongTy;
4889 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4890 }
4891
4892 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004893 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004894}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004895
4896//===----------------------------------------------------------------------===//
4897// Type Predicates.
4898//===----------------------------------------------------------------------===//
4899
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004900/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4901/// garbage collection attribute.
4902///
John McCallae278a32011-01-12 00:34:59 +00004903Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4904 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4905 return Qualifiers::GCNone;
4906
4907 assert(getLangOptions().ObjC1);
4908 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4909
4910 // Default behaviour under objective-C's gc is for ObjC pointers
4911 // (or pointers to them) be treated as though they were declared
4912 // as __strong.
4913 if (GCAttrs == Qualifiers::GCNone) {
4914 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4915 return Qualifiers::Strong;
4916 else if (Ty->isPointerType())
4917 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4918 } else {
4919 // It's not valid to set GC attributes on anything that isn't a
4920 // pointer.
4921#ifndef NDEBUG
4922 QualType CT = Ty->getCanonicalTypeInternal();
4923 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4924 CT = AT->getElementType();
4925 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4926#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004927 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004928 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004929}
4930
Chris Lattner6ac46a42008-04-07 06:51:04 +00004931//===----------------------------------------------------------------------===//
4932// Type Compatibility Testing
4933//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004934
Mike Stump1eb44332009-09-09 15:08:12 +00004935/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004936/// compatible.
4937static bool areCompatVectorTypes(const VectorType *LHS,
4938 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004939 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004940 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004941 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004942}
4943
Douglas Gregor255210e2010-08-06 10:14:59 +00004944bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4945 QualType SecondVec) {
4946 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4947 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4948
4949 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4950 return true;
4951
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004952 // Treat Neon vector types and most AltiVec vector types as if they are the
4953 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004954 const VectorType *First = FirstVec->getAs<VectorType>();
4955 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004956 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004957 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004958 First->getVectorKind() != VectorType::AltiVecPixel &&
4959 First->getVectorKind() != VectorType::AltiVecBool &&
4960 Second->getVectorKind() != VectorType::AltiVecPixel &&
4961 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004962 return true;
4963
4964 return false;
4965}
4966
Steve Naroff4084c302009-07-23 01:01:38 +00004967//===----------------------------------------------------------------------===//
4968// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4969//===----------------------------------------------------------------------===//
4970
4971/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4972/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00004973bool
4974ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4975 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00004976 if (lProto == rProto)
4977 return true;
4978 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4979 E = rProto->protocol_end(); PI != E; ++PI)
4980 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4981 return true;
4982 return false;
4983}
4984
Steve Naroff4084c302009-07-23 01:01:38 +00004985/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4986/// return true if lhs's protocols conform to rhs's protocol; false
4987/// otherwise.
4988bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4989 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4990 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4991 return false;
4992}
4993
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004994/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4995/// Class<p1, ...>.
4996bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4997 QualType rhs) {
4998 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4999 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5000 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5001
5002 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5003 E = lhsQID->qual_end(); I != E; ++I) {
5004 bool match = false;
5005 ObjCProtocolDecl *lhsProto = *I;
5006 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5007 E = rhsOPT->qual_end(); J != E; ++J) {
5008 ObjCProtocolDecl *rhsProto = *J;
5009 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5010 match = true;
5011 break;
5012 }
5013 }
5014 if (!match)
5015 return false;
5016 }
5017 return true;
5018}
5019
Steve Naroff4084c302009-07-23 01:01:38 +00005020/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5021/// ObjCQualifiedIDType.
5022bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5023 bool compare) {
5024 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005025 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005026 lhs->isObjCIdType() || lhs->isObjCClassType())
5027 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005028 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005029 rhs->isObjCIdType() || rhs->isObjCClassType())
5030 return true;
5031
5032 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005033 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005034
Steve Naroff4084c302009-07-23 01:01:38 +00005035 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005036
Steve Naroff4084c302009-07-23 01:01:38 +00005037 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005038 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005039 // make sure we check the class hierarchy.
5040 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5041 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5042 E = lhsQID->qual_end(); I != E; ++I) {
5043 // when comparing an id<P> on lhs with a static type on rhs,
5044 // see if static class implements all of id's protocols, directly or
5045 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005046 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005047 return false;
5048 }
5049 }
5050 // If there are no qualifiers and no interface, we have an 'id'.
5051 return true;
5052 }
Mike Stump1eb44332009-09-09 15:08:12 +00005053 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005054 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5055 E = lhsQID->qual_end(); I != E; ++I) {
5056 ObjCProtocolDecl *lhsProto = *I;
5057 bool match = false;
5058
5059 // when comparing an id<P> on lhs with a static type on rhs,
5060 // see if static class implements all of id's protocols, directly or
5061 // through its super class and categories.
5062 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5063 E = rhsOPT->qual_end(); J != E; ++J) {
5064 ObjCProtocolDecl *rhsProto = *J;
5065 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5066 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5067 match = true;
5068 break;
5069 }
5070 }
Mike Stump1eb44332009-09-09 15:08:12 +00005071 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005072 // make sure we check the class hierarchy.
5073 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5074 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5075 E = lhsQID->qual_end(); I != E; ++I) {
5076 // when comparing an id<P> on lhs with a static type on rhs,
5077 // see if static class implements all of id's protocols, directly or
5078 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005079 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005080 match = true;
5081 break;
5082 }
5083 }
5084 }
5085 if (!match)
5086 return false;
5087 }
Mike Stump1eb44332009-09-09 15:08:12 +00005088
Steve Naroff4084c302009-07-23 01:01:38 +00005089 return true;
5090 }
Mike Stump1eb44332009-09-09 15:08:12 +00005091
Steve Naroff4084c302009-07-23 01:01:38 +00005092 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5093 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5094
Mike Stump1eb44332009-09-09 15:08:12 +00005095 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005096 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005097 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005098 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5099 E = lhsOPT->qual_end(); I != E; ++I) {
5100 ObjCProtocolDecl *lhsProto = *I;
5101 bool match = false;
5102
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005103 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005104 // see if static class implements all of id's protocols, directly or
5105 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005106 // First, lhs protocols in the qualifier list must be found, direct
5107 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005108 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5109 E = rhsQID->qual_end(); J != E; ++J) {
5110 ObjCProtocolDecl *rhsProto = *J;
5111 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5112 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5113 match = true;
5114 break;
5115 }
5116 }
5117 if (!match)
5118 return false;
5119 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005120
5121 // Static class's protocols, or its super class or category protocols
5122 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5123 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5124 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5125 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5126 // This is rather dubious but matches gcc's behavior. If lhs has
5127 // no type qualifier and its class has no static protocol(s)
5128 // assume that it is mismatch.
5129 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5130 return false;
5131 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5132 LHSInheritedProtocols.begin(),
5133 E = LHSInheritedProtocols.end(); I != E; ++I) {
5134 bool match = false;
5135 ObjCProtocolDecl *lhsProto = (*I);
5136 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5137 E = rhsQID->qual_end(); J != E; ++J) {
5138 ObjCProtocolDecl *rhsProto = *J;
5139 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5140 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5141 match = true;
5142 break;
5143 }
5144 }
5145 if (!match)
5146 return false;
5147 }
5148 }
Steve Naroff4084c302009-07-23 01:01:38 +00005149 return true;
5150 }
5151 return false;
5152}
5153
Eli Friedman3d815e72008-08-22 00:56:42 +00005154/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005155/// compatible for assignment from RHS to LHS. This handles validation of any
5156/// protocol qualifiers on the LHS or RHS.
5157///
Steve Naroff14108da2009-07-10 23:34:53 +00005158bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5159 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005160 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5161 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5162
Steve Naroffde2e22d2009-07-15 18:40:39 +00005163 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005164 if (LHS->isObjCUnqualifiedIdOrClass() ||
5165 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005166 return true;
5167
John McCallc12c5bb2010-05-15 11:32:37 +00005168 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005169 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5170 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005171 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005172
5173 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5174 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5175 QualType(RHSOPT,0));
5176
John McCallc12c5bb2010-05-15 11:32:37 +00005177 // If we have 2 user-defined types, fall into that path.
5178 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005179 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005180
Steve Naroff4084c302009-07-23 01:01:38 +00005181 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005182}
5183
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005184/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005185/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005186/// arguments in block literals. When passed as arguments, passing 'A*' where
5187/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5188/// not OK. For the return type, the opposite is not OK.
5189bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5190 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005191 const ObjCObjectPointerType *RHSOPT,
5192 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005193 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005194 return true;
5195
5196 if (LHSOPT->isObjCBuiltinType()) {
5197 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5198 }
5199
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005200 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005201 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5202 QualType(RHSOPT,0),
5203 false);
5204
5205 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5206 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5207 if (LHS && RHS) { // We have 2 user-defined types.
5208 if (LHS != RHS) {
5209 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005210 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005211 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005212 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005213 }
5214 else
5215 return true;
5216 }
5217 return false;
5218}
5219
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005220/// getIntersectionOfProtocols - This routine finds the intersection of set
5221/// of protocols inherited from two distinct objective-c pointer objects.
5222/// It is used to build composite qualifier list of the composite type of
5223/// the conditional expression involving two objective-c pointer objects.
5224static
5225void getIntersectionOfProtocols(ASTContext &Context,
5226 const ObjCObjectPointerType *LHSOPT,
5227 const ObjCObjectPointerType *RHSOPT,
5228 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
5229
John McCallc12c5bb2010-05-15 11:32:37 +00005230 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5231 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5232 assert(LHS->getInterface() && "LHS must have an interface base");
5233 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005234
5235 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5236 unsigned LHSNumProtocols = LHS->getNumProtocols();
5237 if (LHSNumProtocols > 0)
5238 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5239 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005240 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005241 Context.CollectInheritedProtocols(LHS->getInterface(),
5242 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005243 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5244 LHSInheritedProtocols.end());
5245 }
5246
5247 unsigned RHSNumProtocols = RHS->getNumProtocols();
5248 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005249 ObjCProtocolDecl **RHSProtocols =
5250 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005251 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5252 if (InheritedProtocolSet.count(RHSProtocols[i]))
5253 IntersectionOfProtocols.push_back(RHSProtocols[i]);
5254 }
5255 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005256 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005257 Context.CollectInheritedProtocols(RHS->getInterface(),
5258 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005259 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5260 RHSInheritedProtocols.begin(),
5261 E = RHSInheritedProtocols.end(); I != E; ++I)
5262 if (InheritedProtocolSet.count((*I)))
5263 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005264 }
5265}
5266
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005267/// areCommonBaseCompatible - Returns common base class of the two classes if
5268/// one found. Note that this is O'2 algorithm. But it will be called as the
5269/// last type comparison in a ?-exp of ObjC pointer types before a
5270/// warning is issued. So, its invokation is extremely rare.
5271QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005272 const ObjCObjectPointerType *Lptr,
5273 const ObjCObjectPointerType *Rptr) {
5274 const ObjCObjectType *LHS = Lptr->getObjectType();
5275 const ObjCObjectType *RHS = Rptr->getObjectType();
5276 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5277 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005278 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005279 return QualType();
5280
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005281 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005282 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005283 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00005284 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
5285 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5286
5287 QualType Result = QualType(LHS, 0);
5288 if (!Protocols.empty())
5289 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5290 Result = getObjCObjectPointerType(Result);
5291 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005292 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005293 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005294
5295 return QualType();
5296}
5297
John McCallc12c5bb2010-05-15 11:32:37 +00005298bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5299 const ObjCObjectType *RHS) {
5300 assert(LHS->getInterface() && "LHS is not an interface type");
5301 assert(RHS->getInterface() && "RHS is not an interface type");
5302
Chris Lattner6ac46a42008-04-07 06:51:04 +00005303 // Verify that the base decls are compatible: the RHS must be a subclass of
5304 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005305 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005306 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005307
Chris Lattner6ac46a42008-04-07 06:51:04 +00005308 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5309 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005310 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005311 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005312
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005313 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5314 // more detailed analysis is required.
5315 if (RHS->getNumProtocols() == 0) {
5316 // OK, if LHS is a superclass of RHS *and*
5317 // this superclass is assignment compatible with LHS.
5318 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005319 bool IsSuperClass =
5320 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5321 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005322 // OK if conversion of LHS to SuperClass results in narrowing of types
5323 // ; i.e., SuperClass may implement at least one of the protocols
5324 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5325 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5326 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005327 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005328 // If super class has no protocols, it is not a match.
5329 if (SuperClassInheritedProtocols.empty())
5330 return false;
5331
5332 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5333 LHSPE = LHS->qual_end();
5334 LHSPI != LHSPE; LHSPI++) {
5335 bool SuperImplementsProtocol = false;
5336 ObjCProtocolDecl *LHSProto = (*LHSPI);
5337
5338 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5339 SuperClassInheritedProtocols.begin(),
5340 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5341 ObjCProtocolDecl *SuperClassProto = (*I);
5342 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5343 SuperImplementsProtocol = true;
5344 break;
5345 }
5346 }
5347 if (!SuperImplementsProtocol)
5348 return false;
5349 }
5350 return true;
5351 }
5352 return false;
5353 }
Mike Stump1eb44332009-09-09 15:08:12 +00005354
John McCallc12c5bb2010-05-15 11:32:37 +00005355 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5356 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005357 LHSPI != LHSPE; LHSPI++) {
5358 bool RHSImplementsProtocol = false;
5359
5360 // If the RHS doesn't implement the protocol on the left, the types
5361 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005362 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5363 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005364 RHSPI != RHSPE; RHSPI++) {
5365 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005366 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005367 break;
5368 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005369 }
5370 // FIXME: For better diagnostics, consider passing back the protocol name.
5371 if (!RHSImplementsProtocol)
5372 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005373 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005374 // The RHS implements all protocols listed on the LHS.
5375 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005376}
5377
Steve Naroff389bf462009-02-12 17:52:19 +00005378bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5379 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005380 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5381 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005382
Steve Naroff14108da2009-07-10 23:34:53 +00005383 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005384 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005385
5386 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5387 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005388}
5389
Douglas Gregor569c3162010-08-07 11:51:51 +00005390bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5391 return canAssignObjCInterfaces(
5392 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5393 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5394}
5395
Mike Stump1eb44332009-09-09 15:08:12 +00005396/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005397/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005398/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005399/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005400bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5401 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005402 if (getLangOptions().CPlusPlus)
5403 return hasSameType(LHS, RHS);
5404
Douglas Gregor447234d2010-07-29 15:18:02 +00005405 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005406}
5407
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005408bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5409 return !mergeTypes(LHS, RHS, true).isNull();
5410}
5411
Peter Collingbourne48466752010-10-24 18:30:18 +00005412/// mergeTransparentUnionType - if T is a transparent union type and a member
5413/// of T is compatible with SubType, return the merged type, else return
5414/// QualType()
5415QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5416 bool OfBlockPointer,
5417 bool Unqualified) {
5418 if (const RecordType *UT = T->getAsUnionType()) {
5419 RecordDecl *UD = UT->getDecl();
5420 if (UD->hasAttr<TransparentUnionAttr>()) {
5421 for (RecordDecl::field_iterator it = UD->field_begin(),
5422 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005423 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005424 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5425 if (!MT.isNull())
5426 return MT;
5427 }
5428 }
5429 }
5430
5431 return QualType();
5432}
5433
5434/// mergeFunctionArgumentTypes - merge two types which appear as function
5435/// argument types
5436QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5437 bool OfBlockPointer,
5438 bool Unqualified) {
5439 // GNU extension: two types are compatible if they appear as a function
5440 // argument, one of the types is a transparent union type and the other
5441 // type is compatible with a union member
5442 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5443 Unqualified);
5444 if (!lmerge.isNull())
5445 return lmerge;
5446
5447 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5448 Unqualified);
5449 if (!rmerge.isNull())
5450 return rmerge;
5451
5452 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5453}
5454
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005455QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005456 bool OfBlockPointer,
5457 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005458 const FunctionType *lbase = lhs->getAs<FunctionType>();
5459 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005460 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5461 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005462 bool allLTypes = true;
5463 bool allRTypes = true;
5464
5465 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005466 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005467 if (OfBlockPointer) {
5468 QualType RHS = rbase->getResultType();
5469 QualType LHS = lbase->getResultType();
5470 bool UnqualifiedResult = Unqualified;
5471 if (!UnqualifiedResult)
5472 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005473 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005474 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005475 else
John McCall8cc246c2010-12-15 01:06:38 +00005476 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5477 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005478 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005479
5480 if (Unqualified)
5481 retType = retType.getUnqualifiedType();
5482
5483 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5484 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5485 if (Unqualified) {
5486 LRetType = LRetType.getUnqualifiedType();
5487 RRetType = RRetType.getUnqualifiedType();
5488 }
5489
5490 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005491 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005492 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005493 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005494
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005495 // FIXME: double check this
5496 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5497 // rbase->getRegParmAttr() != 0 &&
5498 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005499 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5500 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005501
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005502 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005503 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005504 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005505
John McCall8cc246c2010-12-15 01:06:38 +00005506 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005507 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5508 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005509 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5510 return QualType();
5511
John McCallf85e1932011-06-15 23:02:42 +00005512 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5513 return QualType();
5514
John McCall8cc246c2010-12-15 01:06:38 +00005515 // It's noreturn if either type is.
5516 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5517 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5518 if (NoReturn != lbaseInfo.getNoReturn())
5519 allLTypes = false;
5520 if (NoReturn != rbaseInfo.getNoReturn())
5521 allRTypes = false;
5522
John McCallf85e1932011-06-15 23:02:42 +00005523 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005524
Eli Friedman3d815e72008-08-22 00:56:42 +00005525 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005526 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5527 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005528 unsigned lproto_nargs = lproto->getNumArgs();
5529 unsigned rproto_nargs = rproto->getNumArgs();
5530
5531 // Compatible functions must have the same number of arguments
5532 if (lproto_nargs != rproto_nargs)
5533 return QualType();
5534
5535 // Variadic and non-variadic functions aren't compatible
5536 if (lproto->isVariadic() != rproto->isVariadic())
5537 return QualType();
5538
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005539 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5540 return QualType();
5541
Eli Friedman3d815e72008-08-22 00:56:42 +00005542 // Check argument compatibility
5543 llvm::SmallVector<QualType, 10> types;
5544 for (unsigned i = 0; i < lproto_nargs; i++) {
5545 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5546 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005547 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5548 OfBlockPointer,
5549 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005550 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005551
5552 if (Unqualified)
5553 argtype = argtype.getUnqualifiedType();
5554
Eli Friedman3d815e72008-08-22 00:56:42 +00005555 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005556 if (Unqualified) {
5557 largtype = largtype.getUnqualifiedType();
5558 rargtype = rargtype.getUnqualifiedType();
5559 }
5560
Chris Lattner61710852008-10-05 17:34:18 +00005561 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5562 allLTypes = false;
5563 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5564 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005565 }
5566 if (allLTypes) return lhs;
5567 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005568
5569 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5570 EPI.ExtInfo = einfo;
5571 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005572 }
5573
5574 if (lproto) allRTypes = false;
5575 if (rproto) allLTypes = false;
5576
Douglas Gregor72564e72009-02-26 23:50:07 +00005577 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005578 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005579 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005580 if (proto->isVariadic()) return QualType();
5581 // Check that the types are compatible with the types that
5582 // would result from default argument promotions (C99 6.7.5.3p15).
5583 // The only types actually affected are promotable integer
5584 // types and floats, which would be passed as a different
5585 // type depending on whether the prototype is visible.
5586 unsigned proto_nargs = proto->getNumArgs();
5587 for (unsigned i = 0; i < proto_nargs; ++i) {
5588 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005589
5590 // Look at the promotion type of enum types, since that is the type used
5591 // to pass enum values.
5592 if (const EnumType *Enum = argTy->getAs<EnumType>())
5593 argTy = Enum->getDecl()->getPromotionType();
5594
Eli Friedman3d815e72008-08-22 00:56:42 +00005595 if (argTy->isPromotableIntegerType() ||
5596 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5597 return QualType();
5598 }
5599
5600 if (allLTypes) return lhs;
5601 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005602
5603 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5604 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005605 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005606 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005607 }
5608
5609 if (allLTypes) return lhs;
5610 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005611 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005612}
5613
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005614QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005615 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005616 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005617 // C++ [expr]: If an expression initially has the type "reference to T", the
5618 // type is adjusted to "T" prior to any further analysis, the expression
5619 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005620 // expression is an lvalue unless the reference is an rvalue reference and
5621 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005622 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5623 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005624
5625 if (Unqualified) {
5626 LHS = LHS.getUnqualifiedType();
5627 RHS = RHS.getUnqualifiedType();
5628 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005629
Eli Friedman3d815e72008-08-22 00:56:42 +00005630 QualType LHSCan = getCanonicalType(LHS),
5631 RHSCan = getCanonicalType(RHS);
5632
5633 // If two types are identical, they are compatible.
5634 if (LHSCan == RHSCan)
5635 return LHS;
5636
John McCall0953e762009-09-24 19:53:00 +00005637 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005638 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5639 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005640 if (LQuals != RQuals) {
5641 // If any of these qualifiers are different, we have a type
5642 // mismatch.
5643 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005644 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5645 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005646 return QualType();
5647
5648 // Exactly one GC qualifier difference is allowed: __strong is
5649 // okay if the other type has no GC qualifier but is an Objective
5650 // C object pointer (i.e. implicitly strong by default). We fix
5651 // this by pretending that the unqualified type was actually
5652 // qualified __strong.
5653 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5654 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5655 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5656
5657 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5658 return QualType();
5659
5660 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5661 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5662 }
5663 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5664 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5665 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005666 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005667 }
5668
5669 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005670
Eli Friedman852d63b2009-06-01 01:22:52 +00005671 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5672 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005673
Chris Lattner1adb8832008-01-14 05:45:46 +00005674 // We want to consider the two function types to be the same for these
5675 // comparisons, just force one to the other.
5676 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5677 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005678
5679 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005680 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5681 LHSClass = Type::ConstantArray;
5682 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5683 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005684
John McCallc12c5bb2010-05-15 11:32:37 +00005685 // ObjCInterfaces are just specialized ObjCObjects.
5686 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5687 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5688
Nate Begeman213541a2008-04-18 23:10:10 +00005689 // Canonicalize ExtVector -> Vector.
5690 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5691 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005692
Chris Lattnera36a61f2008-04-07 05:43:21 +00005693 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005694 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005695 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005696 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005697 // Compatibility is based on the underlying type, not the promotion
5698 // type.
John McCall183700f2009-09-21 23:43:11 +00005699 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005700 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5701 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005702 }
John McCall183700f2009-09-21 23:43:11 +00005703 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005704 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5705 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005706 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005707
Eli Friedman3d815e72008-08-22 00:56:42 +00005708 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005709 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005710
Steve Naroff4a746782008-01-09 22:43:08 +00005711 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005712 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005713#define TYPE(Class, Base)
5714#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005715#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005716#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5717#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5718#include "clang/AST/TypeNodes.def"
5719 assert(false && "Non-canonical and dependent types shouldn't get here");
5720 return QualType();
5721
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005722 case Type::LValueReference:
5723 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005724 case Type::MemberPointer:
5725 assert(false && "C++ should never be in mergeTypes");
5726 return QualType();
5727
John McCallc12c5bb2010-05-15 11:32:37 +00005728 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005729 case Type::IncompleteArray:
5730 case Type::VariableArray:
5731 case Type::FunctionProto:
5732 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005733 assert(false && "Types are eliminated above");
5734 return QualType();
5735
Chris Lattner1adb8832008-01-14 05:45:46 +00005736 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005737 {
5738 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005739 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5740 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005741 if (Unqualified) {
5742 LHSPointee = LHSPointee.getUnqualifiedType();
5743 RHSPointee = RHSPointee.getUnqualifiedType();
5744 }
5745 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5746 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005747 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005748 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005749 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005750 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005751 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005752 return getPointerType(ResultType);
5753 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005754 case Type::BlockPointer:
5755 {
5756 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005757 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5758 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005759 if (Unqualified) {
5760 LHSPointee = LHSPointee.getUnqualifiedType();
5761 RHSPointee = RHSPointee.getUnqualifiedType();
5762 }
5763 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5764 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005765 if (ResultType.isNull()) return QualType();
5766 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5767 return LHS;
5768 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5769 return RHS;
5770 return getBlockPointerType(ResultType);
5771 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005772 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005773 {
5774 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5775 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5776 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5777 return QualType();
5778
5779 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5780 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005781 if (Unqualified) {
5782 LHSElem = LHSElem.getUnqualifiedType();
5783 RHSElem = RHSElem.getUnqualifiedType();
5784 }
5785
5786 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005787 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005788 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5789 return LHS;
5790 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5791 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005792 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5793 ArrayType::ArraySizeModifier(), 0);
5794 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5795 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005796 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5797 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005798 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5799 return LHS;
5800 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5801 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005802 if (LVAT) {
5803 // FIXME: This isn't correct! But tricky to implement because
5804 // the array's size has to be the size of LHS, but the type
5805 // has to be different.
5806 return LHS;
5807 }
5808 if (RVAT) {
5809 // FIXME: This isn't correct! But tricky to implement because
5810 // the array's size has to be the size of RHS, but the type
5811 // has to be different.
5812 return RHS;
5813 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005814 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5815 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005816 return getIncompleteArrayType(ResultType,
5817 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005818 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005819 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005820 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005821 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005822 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005823 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005824 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005825 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005826 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005827 case Type::Complex:
5828 // Distinct complex types are incompatible.
5829 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005830 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005831 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005832 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5833 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005834 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005835 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005836 case Type::ObjCObject: {
5837 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005838 // FIXME: This should be type compatibility, e.g. whether
5839 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005840 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5841 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5842 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005843 return LHS;
5844
Eli Friedman3d815e72008-08-22 00:56:42 +00005845 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005846 }
Steve Naroff14108da2009-07-10 23:34:53 +00005847 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005848 if (OfBlockPointer) {
5849 if (canAssignObjCInterfacesInBlockPointer(
5850 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005851 RHS->getAs<ObjCObjectPointerType>(),
5852 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005853 return LHS;
5854 return QualType();
5855 }
John McCall183700f2009-09-21 23:43:11 +00005856 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5857 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005858 return LHS;
5859
Steve Naroffbc76dd02008-12-10 22:14:21 +00005860 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005861 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005862 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005863
5864 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005865}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005866
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005867/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5868/// 'RHS' attributes and returns the merged version; including for function
5869/// return types.
5870QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5871 QualType LHSCan = getCanonicalType(LHS),
5872 RHSCan = getCanonicalType(RHS);
5873 // If two types are identical, they are compatible.
5874 if (LHSCan == RHSCan)
5875 return LHS;
5876 if (RHSCan->isFunctionType()) {
5877 if (!LHSCan->isFunctionType())
5878 return QualType();
5879 QualType OldReturnType =
5880 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5881 QualType NewReturnType =
5882 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5883 QualType ResReturnType =
5884 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5885 if (ResReturnType.isNull())
5886 return QualType();
5887 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5888 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5889 // In either case, use OldReturnType to build the new function type.
5890 const FunctionType *F = LHS->getAs<FunctionType>();
5891 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005892 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5893 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005894 QualType ResultType
5895 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005896 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005897 return ResultType;
5898 }
5899 }
5900 return QualType();
5901 }
5902
5903 // If the qualifiers are different, the types can still be merged.
5904 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5905 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5906 if (LQuals != RQuals) {
5907 // If any of these qualifiers are different, we have a type mismatch.
5908 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5909 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5910 return QualType();
5911
5912 // Exactly one GC qualifier difference is allowed: __strong is
5913 // okay if the other type has no GC qualifier but is an Objective
5914 // C object pointer (i.e. implicitly strong by default). We fix
5915 // this by pretending that the unqualified type was actually
5916 // qualified __strong.
5917 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5918 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5919 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5920
5921 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5922 return QualType();
5923
5924 if (GC_L == Qualifiers::Strong)
5925 return LHS;
5926 if (GC_R == Qualifiers::Strong)
5927 return RHS;
5928 return QualType();
5929 }
5930
5931 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5932 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5933 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5934 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5935 if (ResQT == LHSBaseQT)
5936 return LHS;
5937 if (ResQT == RHSBaseQT)
5938 return RHS;
5939 }
5940 return QualType();
5941}
5942
Chris Lattner5426bf62008-04-07 07:01:58 +00005943//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005944// Integer Predicates
5945//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005946
Jay Foad4ba2a172011-01-12 09:06:06 +00005947unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00005948 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005949 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005950 if (T->isBooleanType())
5951 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005952 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005953 return (unsigned)getTypeSize(T);
5954}
5955
5956QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005957 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005958
5959 // Turn <4 x signed int> -> <4 x unsigned int>
5960 if (const VectorType *VTy = T->getAs<VectorType>())
5961 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005962 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005963
5964 // For enums, we return the unsigned version of the base type.
5965 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005966 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005967
5968 const BuiltinType *BTy = T->getAs<BuiltinType>();
5969 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005970 switch (BTy->getKind()) {
5971 case BuiltinType::Char_S:
5972 case BuiltinType::SChar:
5973 return UnsignedCharTy;
5974 case BuiltinType::Short:
5975 return UnsignedShortTy;
5976 case BuiltinType::Int:
5977 return UnsignedIntTy;
5978 case BuiltinType::Long:
5979 return UnsignedLongTy;
5980 case BuiltinType::LongLong:
5981 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005982 case BuiltinType::Int128:
5983 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005984 default:
5985 assert(0 && "Unexpected signed integer type");
5986 return QualType();
5987 }
5988}
5989
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005990ASTMutationListener::~ASTMutationListener() { }
5991
Chris Lattner86df27b2009-06-14 00:45:47 +00005992
5993//===----------------------------------------------------------------------===//
5994// Builtin Type Computation
5995//===----------------------------------------------------------------------===//
5996
5997/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00005998/// pointer over the consumed characters. This returns the resultant type. If
5999/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6000/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6001/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006002///
6003/// RequiresICE is filled in on return to indicate whether the value is required
6004/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006005static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006006 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006007 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006008 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006009 // Modifiers.
6010 int HowLong = 0;
6011 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006012 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006013
Chris Lattner33daae62010-10-01 22:42:38 +00006014 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006015 bool Done = false;
6016 while (!Done) {
6017 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006018 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006019 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006020 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006021 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006022 case 'S':
6023 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6024 assert(!Signed && "Can't use 'S' modifier multiple times!");
6025 Signed = true;
6026 break;
6027 case 'U':
6028 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6029 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6030 Unsigned = true;
6031 break;
6032 case 'L':
6033 assert(HowLong <= 2 && "Can't have LLLL modifier");
6034 ++HowLong;
6035 break;
6036 }
6037 }
6038
6039 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006040
Chris Lattner86df27b2009-06-14 00:45:47 +00006041 // Read the base type.
6042 switch (*Str++) {
6043 default: assert(0 && "Unknown builtin type letter!");
6044 case 'v':
6045 assert(HowLong == 0 && !Signed && !Unsigned &&
6046 "Bad modifiers used with 'v'!");
6047 Type = Context.VoidTy;
6048 break;
6049 case 'f':
6050 assert(HowLong == 0 && !Signed && !Unsigned &&
6051 "Bad modifiers used with 'f'!");
6052 Type = Context.FloatTy;
6053 break;
6054 case 'd':
6055 assert(HowLong < 2 && !Signed && !Unsigned &&
6056 "Bad modifiers used with 'd'!");
6057 if (HowLong)
6058 Type = Context.LongDoubleTy;
6059 else
6060 Type = Context.DoubleTy;
6061 break;
6062 case 's':
6063 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6064 if (Unsigned)
6065 Type = Context.UnsignedShortTy;
6066 else
6067 Type = Context.ShortTy;
6068 break;
6069 case 'i':
6070 if (HowLong == 3)
6071 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6072 else if (HowLong == 2)
6073 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6074 else if (HowLong == 1)
6075 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6076 else
6077 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6078 break;
6079 case 'c':
6080 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6081 if (Signed)
6082 Type = Context.SignedCharTy;
6083 else if (Unsigned)
6084 Type = Context.UnsignedCharTy;
6085 else
6086 Type = Context.CharTy;
6087 break;
6088 case 'b': // boolean
6089 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6090 Type = Context.BoolTy;
6091 break;
6092 case 'z': // size_t.
6093 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6094 Type = Context.getSizeType();
6095 break;
6096 case 'F':
6097 Type = Context.getCFConstantStringType();
6098 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006099 case 'G':
6100 Type = Context.getObjCIdType();
6101 break;
6102 case 'H':
6103 Type = Context.getObjCSelType();
6104 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006105 case 'a':
6106 Type = Context.getBuiltinVaListType();
6107 assert(!Type.isNull() && "builtin va list type not initialized!");
6108 break;
6109 case 'A':
6110 // This is a "reference" to a va_list; however, what exactly
6111 // this means depends on how va_list is defined. There are two
6112 // different kinds of va_list: ones passed by value, and ones
6113 // passed by reference. An example of a by-value va_list is
6114 // x86, where va_list is a char*. An example of by-ref va_list
6115 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6116 // we want this argument to be a char*&; for x86-64, we want
6117 // it to be a __va_list_tag*.
6118 Type = Context.getBuiltinVaListType();
6119 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006120 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006121 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006122 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006123 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006124 break;
6125 case 'V': {
6126 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006127 unsigned NumElements = strtoul(Str, &End, 10);
6128 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006129 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006130
Chris Lattner14e0e742010-10-01 22:53:11 +00006131 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6132 RequiresICE, false);
6133 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006134
6135 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006136 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006137 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006138 break;
6139 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006140 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006141 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6142 false);
6143 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006144 Type = Context.getComplexType(ElementType);
6145 break;
6146 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006147 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006148 Type = Context.getFILEType();
6149 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006150 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006151 return QualType();
6152 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006153 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006154 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006155 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006156 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006157 else
6158 Type = Context.getjmp_bufType();
6159
Mike Stumpfd612db2009-07-28 23:47:15 +00006160 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006161 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006162 return QualType();
6163 }
6164 break;
Mike Stump782fa302009-07-28 02:25:19 +00006165 }
Mike Stump1eb44332009-09-09 15:08:12 +00006166
Chris Lattner33daae62010-10-01 22:42:38 +00006167 // If there are modifiers and if we're allowed to parse them, go for it.
6168 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006169 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006170 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006171 default: Done = true; --Str; break;
6172 case '*':
6173 case '&': {
6174 // Both pointers and references can have their pointee types
6175 // qualified with an address space.
6176 char *End;
6177 unsigned AddrSpace = strtoul(Str, &End, 10);
6178 if (End != Str && AddrSpace != 0) {
6179 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6180 Str = End;
6181 }
6182 if (c == '*')
6183 Type = Context.getPointerType(Type);
6184 else
6185 Type = Context.getLValueReferenceType(Type);
6186 break;
6187 }
6188 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6189 case 'C':
6190 Type = Type.withConst();
6191 break;
6192 case 'D':
6193 Type = Context.getVolatileType(Type);
6194 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006195 }
6196 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006197
Chris Lattner14e0e742010-10-01 22:53:11 +00006198 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006199 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006200
Chris Lattner86df27b2009-06-14 00:45:47 +00006201 return Type;
6202}
6203
6204/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006205QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006206 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006207 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006208 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006209
Chris Lattner86df27b2009-06-14 00:45:47 +00006210 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006211
Chris Lattner14e0e742010-10-01 22:53:11 +00006212 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006213 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006214 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6215 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006216 if (Error != GE_None)
6217 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006218
6219 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6220
Chris Lattner86df27b2009-06-14 00:45:47 +00006221 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006222 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006223 if (Error != GE_None)
6224 return QualType();
6225
Chris Lattner14e0e742010-10-01 22:53:11 +00006226 // If this argument is required to be an IntegerConstantExpression and the
6227 // caller cares, fill in the bitmask we return.
6228 if (RequiresICE && IntegerConstantArgs)
6229 *IntegerConstantArgs |= 1 << ArgTypes.size();
6230
Chris Lattner86df27b2009-06-14 00:45:47 +00006231 // Do array -> pointer decay. The builtin should use the decayed type.
6232 if (Ty->isArrayType())
6233 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006234
Chris Lattner86df27b2009-06-14 00:45:47 +00006235 ArgTypes.push_back(Ty);
6236 }
6237
6238 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6239 "'.' should only occur at end of builtin type list!");
6240
John McCall00ccbef2010-12-21 00:44:39 +00006241 FunctionType::ExtInfo EI;
6242 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6243
6244 bool Variadic = (TypeStr[0] == '.');
6245
6246 // We really shouldn't be making a no-proto type here, especially in C++.
6247 if (ArgTypes.empty() && Variadic)
6248 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006249
John McCalle23cf432010-12-14 08:05:40 +00006250 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006251 EPI.ExtInfo = EI;
6252 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006253
6254 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006255}
Eli Friedmana95d7572009-08-19 07:44:53 +00006256
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006257GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6258 GVALinkage External = GVA_StrongExternal;
6259
6260 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006261 switch (L) {
6262 case NoLinkage:
6263 case InternalLinkage:
6264 case UniqueExternalLinkage:
6265 return GVA_Internal;
6266
6267 case ExternalLinkage:
6268 switch (FD->getTemplateSpecializationKind()) {
6269 case TSK_Undeclared:
6270 case TSK_ExplicitSpecialization:
6271 External = GVA_StrongExternal;
6272 break;
6273
6274 case TSK_ExplicitInstantiationDefinition:
6275 return GVA_ExplicitTemplateInstantiation;
6276
6277 case TSK_ExplicitInstantiationDeclaration:
6278 case TSK_ImplicitInstantiation:
6279 External = GVA_TemplateInstantiation;
6280 break;
6281 }
6282 }
6283
6284 if (!FD->isInlined())
6285 return External;
6286
6287 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6288 // GNU or C99 inline semantics. Determine whether this symbol should be
6289 // externally visible.
6290 if (FD->isInlineDefinitionExternallyVisible())
6291 return External;
6292
6293 // C99 inline semantics, where the symbol is not externally visible.
6294 return GVA_C99Inline;
6295 }
6296
6297 // C++0x [temp.explicit]p9:
6298 // [ Note: The intent is that an inline function that is the subject of
6299 // an explicit instantiation declaration will still be implicitly
6300 // instantiated when used so that the body can be considered for
6301 // inlining, but that no out-of-line copy of the inline function would be
6302 // generated in the translation unit. -- end note ]
6303 if (FD->getTemplateSpecializationKind()
6304 == TSK_ExplicitInstantiationDeclaration)
6305 return GVA_C99Inline;
6306
6307 return GVA_CXXInline;
6308}
6309
6310GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6311 // If this is a static data member, compute the kind of template
6312 // specialization. Otherwise, this variable is not part of a
6313 // template.
6314 TemplateSpecializationKind TSK = TSK_Undeclared;
6315 if (VD->isStaticDataMember())
6316 TSK = VD->getTemplateSpecializationKind();
6317
6318 Linkage L = VD->getLinkage();
6319 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6320 VD->getType()->getLinkage() == UniqueExternalLinkage)
6321 L = UniqueExternalLinkage;
6322
6323 switch (L) {
6324 case NoLinkage:
6325 case InternalLinkage:
6326 case UniqueExternalLinkage:
6327 return GVA_Internal;
6328
6329 case ExternalLinkage:
6330 switch (TSK) {
6331 case TSK_Undeclared:
6332 case TSK_ExplicitSpecialization:
6333 return GVA_StrongExternal;
6334
6335 case TSK_ExplicitInstantiationDeclaration:
6336 llvm_unreachable("Variable should not be instantiated");
6337 // Fall through to treat this like any other instantiation.
6338
6339 case TSK_ExplicitInstantiationDefinition:
6340 return GVA_ExplicitTemplateInstantiation;
6341
6342 case TSK_ImplicitInstantiation:
6343 return GVA_TemplateInstantiation;
6344 }
6345 }
6346
6347 return GVA_StrongExternal;
6348}
6349
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006350bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006351 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6352 if (!VD->isFileVarDecl())
6353 return false;
6354 } else if (!isa<FunctionDecl>(D))
6355 return false;
6356
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006357 // Weak references don't produce any output by themselves.
6358 if (D->hasAttr<WeakRefAttr>())
6359 return false;
6360
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006361 // Aliases and used decls are required.
6362 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6363 return true;
6364
6365 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6366 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006367 if (!FD->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006368 return false;
6369
6370 // Constructors and destructors are required.
6371 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6372 return true;
6373
6374 // The key function for a class is required.
6375 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6376 const CXXRecordDecl *RD = MD->getParent();
6377 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6378 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6379 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6380 return true;
6381 }
6382 }
6383
6384 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6385
6386 // static, static inline, always_inline, and extern inline functions can
6387 // always be deferred. Normal inline functions can be deferred in C99/C++.
6388 // Implicit template instantiations can also be deferred in C++.
6389 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6390 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6391 return false;
6392 return true;
6393 }
6394
6395 const VarDecl *VD = cast<VarDecl>(D);
6396 assert(VD->isFileVarDecl() && "Expected file scoped var");
6397
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006398 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6399 return false;
6400
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006401 // Structs that have non-trivial constructors or destructors are required.
6402
6403 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006404 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006405 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6406 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006407 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6408 RD->hasTrivialCopyConstructor() &&
6409 RD->hasTrivialMoveConstructor() &&
6410 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006411 return true;
6412 }
6413 }
6414
6415 GVALinkage L = GetGVALinkageForVariable(VD);
6416 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6417 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6418 return false;
6419 }
6420
6421 return true;
6422}
Charles Davis071cc7d2010-08-16 03:33:14 +00006423
Charles Davisee743f92010-11-09 18:04:24 +00006424CallingConv ASTContext::getDefaultMethodCallConv() {
6425 // Pass through to the C++ ABI object
6426 return ABI->getDefaultMethodCallConv();
6427}
6428
Jay Foad4ba2a172011-01-12 09:06:06 +00006429bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006430 // Pass through to the C++ ABI object
6431 return ABI->isNearlyEmpty(RD);
6432}
6433
Peter Collingbourne14110472011-01-13 18:57:25 +00006434MangleContext *ASTContext::createMangleContext() {
6435 switch (Target.getCXXABI()) {
6436 case CXXABI_ARM:
6437 case CXXABI_Itanium:
6438 return createItaniumMangleContext(*this, getDiagnostics());
6439 case CXXABI_Microsoft:
6440 return createMicrosoftMangleContext(*this, getDiagnostics());
6441 }
6442 assert(0 && "Unsupported ABI");
6443 return 0;
6444}
6445
Charles Davis071cc7d2010-08-16 03:33:14 +00006446CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006447
6448size_t ASTContext::getSideTableAllocatedMemory() const {
6449 size_t bytes = 0;
6450 bytes += ASTRecordLayouts.getMemorySize();
6451 bytes += ObjCLayouts.getMemorySize();
6452 bytes += KeyFunctions.getMemorySize();
6453 bytes += ObjCImpls.getMemorySize();
6454 bytes += BlockVarCopyInits.getMemorySize();
6455 bytes += DeclAttrs.getMemorySize();
6456 bytes += InstantiatedFromStaticDataMember.getMemorySize();
6457 bytes += InstantiatedFromUsingDecl.getMemorySize();
6458 bytes += InstantiatedFromUsingShadowDecl.getMemorySize();
6459 bytes += InstantiatedFromUnnamedFieldDecl.getMemorySize();
6460 return bytes;
6461}
6462