blob: 50c295f241f23e3dd0184c121745a883ceff6b43 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000033#include "CXXABI.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000034
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
36
Douglas Gregor18274032010-07-03 00:47:00 +000037unsigned ASTContext::NumImplicitDefaultConstructors;
38unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000039unsigned ASTContext::NumImplicitCopyConstructors;
40unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000041unsigned ASTContext::NumImplicitCopyAssignmentOperators;
42unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000043unsigned ASTContext::NumImplicitDestructors;
44unsigned ASTContext::NumImplicitDestructorsDeclared;
45
Reid Spencer5f016e22007-07-11 17:01:13 +000046enum FloatingRank {
47 FloatRank, DoubleRank, LongDoubleRank
48};
49
Douglas Gregor3e1274f2010-06-16 21:09:37 +000050void
51ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
52 TemplateTemplateParmDecl *Parm) {
53 ID.AddInteger(Parm->getDepth());
54 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +000055 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000056
57 TemplateParameterList *Params = Parm->getTemplateParameters();
58 ID.AddInteger(Params->size());
59 for (TemplateParameterList::const_iterator P = Params->begin(),
60 PEnd = Params->end();
61 P != PEnd; ++P) {
62 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
63 ID.AddInteger(0);
64 ID.AddBoolean(TTP->isParameterPack());
65 continue;
66 }
67
68 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
69 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +000070 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000071 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000072 if (NTTP->isExpandedParameterPack()) {
73 ID.AddBoolean(true);
74 ID.AddInteger(NTTP->getNumExpansionTypes());
75 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
76 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
77 } else
78 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000079 continue;
80 }
81
82 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
83 ID.AddInteger(2);
84 Profile(ID, TTP);
85 }
86}
87
88TemplateTemplateParmDecl *
89ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000090 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000091 // Check if we already have a canonical template template parameter.
92 llvm::FoldingSetNodeID ID;
93 CanonicalTemplateTemplateParm::Profile(ID, TTP);
94 void *InsertPos = 0;
95 CanonicalTemplateTemplateParm *Canonical
96 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
97 if (Canonical)
98 return Canonical->getParam();
99
100 // Build a canonical template parameter list.
101 TemplateParameterList *Params = TTP->getTemplateParameters();
102 llvm::SmallVector<NamedDecl *, 4> CanonParams;
103 CanonParams.reserve(Params->size());
104 for (TemplateParameterList::const_iterator P = Params->begin(),
105 PEnd = Params->end();
106 P != PEnd; ++P) {
107 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
108 CanonParams.push_back(
109 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
110 SourceLocation(), TTP->getDepth(),
111 TTP->getIndex(), 0, false,
112 TTP->isParameterPack()));
113 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000114 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
115 QualType T = getCanonicalType(NTTP->getType());
116 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
117 NonTypeTemplateParmDecl *Param;
118 if (NTTP->isExpandedParameterPack()) {
119 llvm::SmallVector<QualType, 2> ExpandedTypes;
120 llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
121 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
122 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
123 ExpandedTInfos.push_back(
124 getTrivialTypeSourceInfo(ExpandedTypes.back()));
125 }
126
127 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
128 SourceLocation(),
129 NTTP->getDepth(),
130 NTTP->getPosition(), 0,
131 T,
132 TInfo,
133 ExpandedTypes.data(),
134 ExpandedTypes.size(),
135 ExpandedTInfos.data());
136 } else {
137 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
138 SourceLocation(),
139 NTTP->getDepth(),
140 NTTP->getPosition(), 0,
141 T,
142 NTTP->isParameterPack(),
143 TInfo);
144 }
145 CanonParams.push_back(Param);
146
147 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000148 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
149 cast<TemplateTemplateParmDecl>(*P)));
150 }
151
152 TemplateTemplateParmDecl *CanonTTP
153 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
154 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000155 TTP->getPosition(),
156 TTP->isParameterPack(),
157 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000158 TemplateParameterList::Create(*this, SourceLocation(),
159 SourceLocation(),
160 CanonParams.data(),
161 CanonParams.size(),
162 SourceLocation()));
163
164 // Get the new insert position for the node we care about.
165 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
166 assert(Canonical == 0 && "Shouldn't be in the map!");
167 (void)Canonical;
168
169 // Create the canonical template template parameter entry.
170 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
171 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
172 return CanonTTP;
173}
174
Charles Davis071cc7d2010-08-16 03:33:14 +0000175CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000176 if (!LangOpts.CPlusPlus) return 0;
177
Charles Davis20cf7172010-08-19 02:18:14 +0000178 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000179 case CXXABI_ARM:
180 return CreateARMCXXABI(*this);
181 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000182 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000183 case CXXABI_Microsoft:
184 return CreateMicrosoftCXXABI(*this);
185 }
John McCallee79a4c2010-08-21 22:46:04 +0000186 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000187}
188
Chris Lattner61710852008-10-05 17:34:18 +0000189ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000190 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000191 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000192 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000193 unsigned size_reserve) :
John McCallef990012010-06-11 11:07:21 +0000194 TemplateSpecializationTypes(this_()),
195 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000196 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
197 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000198 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000199 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Peter Collingbourne14b6ba72011-02-09 21:04:32 +0000200 cudaConfigureCallDecl(0),
John McCallbf1a0282010-06-04 23:28:52 +0000201 NullTypeSourceInfo(QualType()),
Charles Davis071cc7d2010-08-16 03:33:14 +0000202 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000203 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000204 BuiltinInfo(builtins),
205 DeclarationNames(*this),
Argyrios Kyrtzidis9a44b5f2010-10-28 09:29:35 +0000206 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000207 LastSDM(0, 0),
208 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000209 ObjCIdRedefinitionType = QualType();
210 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000211 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000212 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000213 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000214 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000215}
216
Reid Spencer5f016e22007-07-11 17:01:13 +0000217ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000218 // Release the DenseMaps associated with DeclContext objects.
219 // FIXME: Is this the ideal solution?
220 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000221
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000222 // Call all of the deallocation functions.
223 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
224 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000225
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000226 // Release all of the memory associated with overridden C++ methods.
227 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
228 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
229 OM != OMEnd; ++OM)
230 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000231
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000232 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000233 // because they can contain DenseMaps.
234 for (llvm::DenseMap<const ObjCContainerDecl*,
235 const ASTRecordLayout*>::iterator
236 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
237 // Increment in loop to prevent using deallocated memory.
238 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
239 R->Destroy(*this);
240
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000241 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
242 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
243 // Increment in loop to prevent using deallocated memory.
244 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
245 R->Destroy(*this);
246 }
Douglas Gregor63200642010-08-30 16:49:28 +0000247
248 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
249 AEnd = DeclAttrs.end();
250 A != AEnd; ++A)
251 A->second->~AttrVec();
252}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000253
Douglas Gregor00545312010-05-23 18:26:36 +0000254void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
255 Deallocations.push_back(std::make_pair(Callback, Data));
256}
257
Mike Stump1eb44332009-09-09 15:08:12 +0000258void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000259ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
260 ExternalSource.reset(Source.take());
261}
262
Reid Spencer5f016e22007-07-11 17:01:13 +0000263void ASTContext::PrintStats() const {
264 fprintf(stderr, "*** AST Context Stats:\n");
265 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000266
Douglas Gregordbe833d2009-05-26 14:40:08 +0000267 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000268#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000269#define ABSTRACT_TYPE(Name, Parent)
270#include "clang/AST/TypeNodes.def"
271 0 // Extra
272 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000273
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
275 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000276 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 }
278
Douglas Gregordbe833d2009-05-26 14:40:08 +0000279 unsigned Idx = 0;
280 unsigned TotalBytes = 0;
281#define TYPE(Name, Parent) \
282 if (counts[Idx]) \
283 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
284 TotalBytes += counts[Idx] * sizeof(Name##Type); \
285 ++Idx;
286#define ABSTRACT_TYPE(Name, Parent)
287#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000288
Douglas Gregordbe833d2009-05-26 14:40:08 +0000289 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000290
Douglas Gregor4923aa22010-07-02 20:37:36 +0000291 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000292 fprintf(stderr, " %u/%u implicit default constructors created\n",
293 NumImplicitDefaultConstructorsDeclared,
294 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000295 fprintf(stderr, " %u/%u implicit copy constructors created\n",
296 NumImplicitCopyConstructorsDeclared,
297 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000298 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
299 NumImplicitCopyAssignmentOperatorsDeclared,
300 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000301 fprintf(stderr, " %u/%u implicit destructors created\n",
302 NumImplicitDestructorsDeclared, NumImplicitDestructors);
303
Douglas Gregor2cf26342009-04-09 22:27:44 +0000304 if (ExternalSource.get()) {
305 fprintf(stderr, "\n");
306 ExternalSource->PrintStats();
307 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000308
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000309 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000310}
311
312
John McCalle27ec8a2009-10-23 23:03:21 +0000313void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000314 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000315 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000316 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000317}
318
Reid Spencer5f016e22007-07-11 17:01:13 +0000319void ASTContext::InitBuiltinTypes() {
320 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Reid Spencer5f016e22007-07-11 17:01:13 +0000322 // C99 6.2.5p19.
323 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 // C99 6.2.5p2.
326 InitBuiltinType(BoolTy, BuiltinType::Bool);
327 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000328 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 InitBuiltinType(CharTy, BuiltinType::Char_S);
330 else
331 InitBuiltinType(CharTy, BuiltinType::Char_U);
332 // C99 6.2.5p4.
333 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
334 InitBuiltinType(ShortTy, BuiltinType::Short);
335 InitBuiltinType(IntTy, BuiltinType::Int);
336 InitBuiltinType(LongTy, BuiltinType::Long);
337 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Reid Spencer5f016e22007-07-11 17:01:13 +0000339 // C99 6.2.5p6.
340 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
341 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
342 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
343 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
344 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 // C99 6.2.5p10.
347 InitBuiltinType(FloatTy, BuiltinType::Float);
348 InitBuiltinType(DoubleTy, BuiltinType::Double);
349 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000350
Chris Lattner2df9ced2009-04-30 02:43:43 +0000351 // GNU extension, 128-bit integers.
352 InitBuiltinType(Int128Ty, BuiltinType::Int128);
353 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
354
Chris Lattner3f59c972010-12-25 23:25:43 +0000355 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
356 if (!LangOpts.ShortWChar)
357 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
358 else // -fshort-wchar makes wchar_t be unsigned.
359 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
360 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000361 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000362
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000363 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
364 InitBuiltinType(Char16Ty, BuiltinType::Char16);
365 else // C99
366 Char16Ty = getFromTargetType(Target.getChar16Type());
367
368 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
369 InitBuiltinType(Char32Ty, BuiltinType::Char32);
370 else // C99
371 Char32Ty = getFromTargetType(Target.getChar32Type());
372
Douglas Gregor898574e2008-12-05 23:32:09 +0000373 // Placeholder type for type-dependent expressions whose type is
374 // completely unknown. No code should ever check a type against
375 // DependentTy and users should never see it; however, it is here to
376 // help diagnose failures to properly check for type-dependent
377 // expressions.
378 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000379
John McCall2a984ca2010-10-12 00:20:44 +0000380 // Placeholder type for functions.
381 InitBuiltinType(OverloadTy, BuiltinType::Overload);
382
Mike Stump1eb44332009-09-09 15:08:12 +0000383 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000384 // not yet been deduced.
John McCall2a984ca2010-10-12 00:20:44 +0000385 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 // C99 6.2.5p11.
388 FloatComplexTy = getComplexType(FloatTy);
389 DoubleComplexTy = getComplexType(DoubleTy);
390 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000391
Steve Naroff7e219e42007-10-15 14:41:52 +0000392 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Steve Naroffde2e22d2009-07-15 18:40:39 +0000394 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
395 ObjCIdTypedefType = QualType();
396 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000397 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000399 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000400 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
401 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000402 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000403
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000404 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000406 // void * type
407 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000408
409 // nullptr type (C++0x 2.14.7)
410 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000411}
412
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000413Diagnostic &ASTContext::getDiagnostics() const {
414 return SourceMgr.getDiagnostics();
415}
416
Douglas Gregor63200642010-08-30 16:49:28 +0000417AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
418 AttrVec *&Result = DeclAttrs[D];
419 if (!Result) {
420 void *Mem = Allocate(sizeof(AttrVec));
421 Result = new (Mem) AttrVec;
422 }
423
424 return *Result;
425}
426
427/// \brief Erase the attributes corresponding to the given declaration.
428void ASTContext::eraseDeclAttrs(const Decl *D) {
429 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
430 if (Pos != DeclAttrs.end()) {
431 Pos->second->~AttrVec();
432 DeclAttrs.erase(Pos);
433 }
434}
435
436
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000437MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000438ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000439 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000440 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000441 = InstantiatedFromStaticDataMember.find(Var);
442 if (Pos == InstantiatedFromStaticDataMember.end())
443 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Douglas Gregor7caa6822009-07-24 20:34:43 +0000445 return Pos->second;
446}
447
Mike Stump1eb44332009-09-09 15:08:12 +0000448void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000449ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000450 TemplateSpecializationKind TSK,
451 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000452 assert(Inst->isStaticDataMember() && "Not a static data member");
453 assert(Tmpl->isStaticDataMember() && "Not a static data member");
454 assert(!InstantiatedFromStaticDataMember[Inst] &&
455 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000456 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000457 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000458}
459
John McCall7ba107a2009-11-18 02:36:19 +0000460NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000461ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000462 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000463 = InstantiatedFromUsingDecl.find(UUD);
464 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000465 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Anders Carlsson0d8df782009-08-29 19:37:28 +0000467 return Pos->second;
468}
469
470void
John McCalled976492009-12-04 22:46:56 +0000471ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
472 assert((isa<UsingDecl>(Pattern) ||
473 isa<UnresolvedUsingValueDecl>(Pattern) ||
474 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
475 "pattern decl is not a using decl");
476 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
477 InstantiatedFromUsingDecl[Inst] = Pattern;
478}
479
480UsingShadowDecl *
481ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
482 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
483 = InstantiatedFromUsingShadowDecl.find(Inst);
484 if (Pos == InstantiatedFromUsingShadowDecl.end())
485 return 0;
486
487 return Pos->second;
488}
489
490void
491ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
492 UsingShadowDecl *Pattern) {
493 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
494 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000495}
496
Anders Carlssond8b285f2009-09-01 04:26:58 +0000497FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
498 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
499 = InstantiatedFromUnnamedFieldDecl.find(Field);
500 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
501 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Anders Carlssond8b285f2009-09-01 04:26:58 +0000503 return Pos->second;
504}
505
506void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
507 FieldDecl *Tmpl) {
508 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
509 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
510 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
511 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Anders Carlssond8b285f2009-09-01 04:26:58 +0000513 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
514}
515
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000516ASTContext::overridden_cxx_method_iterator
517ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
518 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
519 = OverriddenMethods.find(Method);
520 if (Pos == OverriddenMethods.end())
521 return 0;
522
523 return Pos->second.begin();
524}
525
526ASTContext::overridden_cxx_method_iterator
527ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
528 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
529 = OverriddenMethods.find(Method);
530 if (Pos == OverriddenMethods.end())
531 return 0;
532
533 return Pos->second.end();
534}
535
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000536unsigned
537ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
538 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
539 = OverriddenMethods.find(Method);
540 if (Pos == OverriddenMethods.end())
541 return 0;
542
543 return Pos->second.size();
544}
545
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000546void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
547 const CXXMethodDecl *Overridden) {
548 OverriddenMethods[Method].push_back(Overridden);
549}
550
Chris Lattner464175b2007-07-18 17:52:12 +0000551//===----------------------------------------------------------------------===//
552// Type Sizing and Analysis
553//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000554
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000555/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
556/// scalar floating point type.
557const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000558 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000559 assert(BT && "Not a floating point type!");
560 switch (BT->getKind()) {
561 default: assert(0 && "Not a floating point type!");
562 case BuiltinType::Float: return Target.getFloatFormat();
563 case BuiltinType::Double: return Target.getDoubleFormat();
564 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
565 }
566}
567
Ken Dyck8b752f12010-01-27 17:10:57 +0000568/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000569/// specified decl. Note that bitfields do not have a valid alignment, so
570/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000571/// If @p RefAsPointee, references are treated like their underlying type
572/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000573CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000574 unsigned Align = Target.getCharWidth();
575
John McCall4081a5c2010-10-08 18:24:19 +0000576 bool UseAlignAttrOnly = false;
577 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
578 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000579
John McCall4081a5c2010-10-08 18:24:19 +0000580 // __attribute__((aligned)) can increase or decrease alignment
581 // *except* on a struct or struct member, where it only increases
582 // alignment unless 'packed' is also specified.
583 //
584 // It is an error for [[align]] to decrease alignment, so we can
585 // ignore that possibility; Sema should diagnose it.
586 if (isa<FieldDecl>(D)) {
587 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
588 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
589 } else {
590 UseAlignAttrOnly = true;
591 }
592 }
593
John McCallba4f5d52011-01-20 07:57:12 +0000594 // If we're using the align attribute only, just ignore everything
595 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000596 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000597 // do nothing
598
John McCall4081a5c2010-10-08 18:24:19 +0000599 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000600 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000601 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000602 if (RefAsPointee)
603 T = RT->getPointeeType();
604 else
605 T = getPointerType(RT->getPointeeType());
606 }
607 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000608 // Adjust alignments of declarations with array type by the
609 // large-array alignment on the target.
Rafael Espindola6deecb02010-06-04 23:15:27 +0000610 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000611 const ArrayType *arrayType;
612 if (MinWidth && (arrayType = getAsArrayType(T))) {
613 if (isa<VariableArrayType>(arrayType))
614 Align = std::max(Align, Target.getLargeArrayAlign());
615 else if (isa<ConstantArrayType>(arrayType) &&
616 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
617 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000618
John McCall3b657512011-01-19 10:06:00 +0000619 // Walk through any array types while we're at it.
620 T = getBaseElementType(arrayType);
621 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000622 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
623 }
John McCallba4f5d52011-01-20 07:57:12 +0000624
625 // Fields can be subject to extra alignment constraints, like if
626 // the field is packed, the struct is packed, or the struct has a
627 // a max-field-alignment constraint (#pragma pack). So calculate
628 // the actual alignment of the field within the struct, and then
629 // (as we're expected to) constrain that by the alignment of the type.
630 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
631 // So calculate the alignment of the field.
632 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
633
634 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000635 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000636
637 // Use the GCD of that and the offset within the record.
638 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
639 if (offset > 0) {
640 // Alignment is always a power of 2, so the GCD will be a power of 2,
641 // which means we get to do this crazy thing instead of Euclid's.
642 uint64_t lowBitOfOffset = offset & (~offset + 1);
643 if (lowBitOfOffset < fieldAlign)
644 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
645 }
646
647 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000648 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000649 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000650
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000651 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000652}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000653
John McCallea1471e2010-05-20 01:18:31 +0000654std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000655ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000656 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000657 return std::make_pair(toCharUnitsFromBits(Info.first),
658 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000659}
660
661std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000662ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000663 return getTypeInfoInChars(T.getTypePtr());
664}
665
Chris Lattnera7674d82007-07-13 22:13:22 +0000666/// getTypeSize - Return the size of the specified type, in bits. This method
667/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000668///
669/// FIXME: Pointers into different addr spaces could have different sizes and
670/// alignment requirements: getPointerInfo should take an AddrSpace, this
671/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000672std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000673ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000674 uint64_t Width=0;
675 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000676 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000677#define TYPE(Class, Base)
678#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000679#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000680#define DEPENDENT_TYPE(Class, Base) case Type::Class:
681#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000682 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000683 break;
684
Chris Lattner692233e2007-07-13 22:27:08 +0000685 case Type::FunctionNoProto:
686 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000687 // GCC extension: alignof(function) = 32 bits
688 Width = 0;
689 Align = 32;
690 break;
691
Douglas Gregor72564e72009-02-26 23:50:07 +0000692 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000693 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000694 Width = 0;
695 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
696 break;
697
Steve Narofffb22d962007-08-30 01:06:46 +0000698 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000699 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Chris Lattner98be4942008-03-05 18:54:05 +0000701 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000702 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000703 Align = EltInfo.second;
704 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000705 }
Nate Begeman213541a2008-04-18 23:10:10 +0000706 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000707 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000708 const VectorType *VT = cast<VectorType>(T);
709 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
710 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000711 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000712 // If the alignment is not a power of 2, round up to the next power of 2.
713 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000714 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000715 Align = llvm::NextPowerOf2(Align);
716 Width = llvm::RoundUpToAlignment(Width, Align);
717 }
Chris Lattner030d8842007-07-19 22:06:24 +0000718 break;
719 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000720
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000721 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000722 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000723 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000724 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000725 // GCC extension: alignof(void) = 8 bits.
726 Width = 0;
727 Align = 8;
728 break;
729
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000730 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000731 Width = Target.getBoolWidth();
732 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000733 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000734 case BuiltinType::Char_S:
735 case BuiltinType::Char_U:
736 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000737 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000738 Width = Target.getCharWidth();
739 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000740 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000741 case BuiltinType::WChar_S:
742 case BuiltinType::WChar_U:
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000743 Width = Target.getWCharWidth();
744 Align = Target.getWCharAlign();
745 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000746 case BuiltinType::Char16:
747 Width = Target.getChar16Width();
748 Align = Target.getChar16Align();
749 break;
750 case BuiltinType::Char32:
751 Width = Target.getChar32Width();
752 Align = Target.getChar32Align();
753 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000754 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000755 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000756 Width = Target.getShortWidth();
757 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000758 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000759 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000760 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000761 Width = Target.getIntWidth();
762 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000763 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000764 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000765 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000766 Width = Target.getLongWidth();
767 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000768 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000769 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000770 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000771 Width = Target.getLongLongWidth();
772 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000773 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000774 case BuiltinType::Int128:
775 case BuiltinType::UInt128:
776 Width = 128;
777 Align = 128; // int128_t is 128-bit aligned on all targets.
778 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000779 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000780 Width = Target.getFloatWidth();
781 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000782 break;
783 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000784 Width = Target.getDoubleWidth();
785 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000786 break;
787 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000788 Width = Target.getLongDoubleWidth();
789 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000790 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000791 case BuiltinType::NullPtr:
792 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
793 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000794 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000795 case BuiltinType::ObjCId:
796 case BuiltinType::ObjCClass:
797 case BuiltinType::ObjCSel:
798 Width = Target.getPointerWidth(0);
799 Align = Target.getPointerAlign(0);
800 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000801 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000802 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000803 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000804 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000805 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000806 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000807 case Type::BlockPointer: {
808 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
809 Width = Target.getPointerWidth(AS);
810 Align = Target.getPointerAlign(AS);
811 break;
812 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000813 case Type::LValueReference:
814 case Type::RValueReference: {
815 // alignof and sizeof should never enter this code path here, so we go
816 // the pointer route.
817 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
818 Width = Target.getPointerWidth(AS);
819 Align = Target.getPointerAlign(AS);
820 break;
821 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000822 case Type::Pointer: {
823 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000824 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000825 Align = Target.getPointerAlign(AS);
826 break;
827 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000828 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000829 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000830 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000831 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000832 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000833 Align = PtrDiffInfo.second;
834 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000835 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000836 case Type::Complex: {
837 // Complex types have the same alignment as their elements, but twice the
838 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000839 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000840 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000841 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000842 Align = EltInfo.second;
843 break;
844 }
John McCallc12c5bb2010-05-15 11:32:37 +0000845 case Type::ObjCObject:
846 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000847 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000848 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000849 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000850 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000851 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +0000852 break;
853 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000854 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000855 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000856 const TagType *TT = cast<TagType>(T);
857
858 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000859 Width = 1;
860 Align = 1;
861 break;
862 }
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Daniel Dunbar1d751182008-11-08 05:48:37 +0000864 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000865 return getTypeInfo(ET->getDecl()->getIntegerType());
866
Daniel Dunbar1d751182008-11-08 05:48:37 +0000867 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000868 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000869 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000870 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000871 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000872 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000873
Chris Lattner9fcfe922009-10-22 05:17:15 +0000874 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000875 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
876 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000877
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000878 case Type::Paren:
879 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
880
Douglas Gregor18857642009-04-30 17:32:17 +0000881 case Type::Typedef: {
882 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000883 std::pair<uint64_t, unsigned> Info
884 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +0000885 // If the typedef has an aligned attribute on it, it overrides any computed
886 // alignment we have. This violates the GCC documentation (which says that
887 // attribute(aligned) can only round up) but matches its implementation.
888 if (unsigned AttrAlign = Typedef->getMaxAlignment())
889 Align = AttrAlign;
890 else
891 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +0000892 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000893 break;
Chris Lattner71763312008-04-06 22:05:18 +0000894 }
Douglas Gregor18857642009-04-30 17:32:17 +0000895
896 case Type::TypeOfExpr:
897 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
898 .getTypePtr());
899
900 case Type::TypeOf:
901 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
902
Anders Carlsson395b4752009-06-24 19:06:50 +0000903 case Type::Decltype:
904 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
905 .getTypePtr());
906
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000907 case Type::Elaborated:
908 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000909
John McCall9d156a72011-01-06 01:58:22 +0000910 case Type::Attributed:
911 return getTypeInfo(
912 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
913
Douglas Gregor18857642009-04-30 17:32:17 +0000914 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000915 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000916 "Cannot request the size of a dependent type");
917 // FIXME: this is likely to be wrong once we support template
918 // aliases, since a template alias could refer to a typedef that
919 // has an __aligned__ attribute on it.
920 return getTypeInfo(getCanonicalType(T));
921 }
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Chris Lattner464175b2007-07-18 17:52:12 +0000923 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000924 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000925}
926
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000927/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
928CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
929 return CharUnits::fromQuantity(BitSize / getCharWidth());
930}
931
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000932/// toBits - Convert a size in characters to a size in characters.
933int64_t ASTContext::toBits(CharUnits CharSize) const {
934 return CharSize.getQuantity() * getCharWidth();
935}
936
Ken Dyckbdc601b2009-12-22 14:23:30 +0000937/// getTypeSizeInChars - Return the size of the specified type, in characters.
938/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +0000939CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000940 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +0000941}
Jay Foad4ba2a172011-01-12 09:06:06 +0000942CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000943 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +0000944}
945
Ken Dyck16e20cc2010-01-26 17:25:18 +0000946/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000947/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +0000948CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000949 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +0000950}
Jay Foad4ba2a172011-01-12 09:06:06 +0000951CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000952 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +0000953}
954
Chris Lattner34ebde42009-01-27 18:08:34 +0000955/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
956/// type for the current target in bits. This can be different than the ABI
957/// alignment in cases where it is beneficial for performance to overalign
958/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +0000959unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +0000960 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000961
962 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000963 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000964 T = CT->getElementType().getTypePtr();
965 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
966 T->isSpecificBuiltinType(BuiltinType::LongLong))
967 return std::max(ABIAlign, (unsigned)getTypeSize(T));
968
Chris Lattner34ebde42009-01-27 18:08:34 +0000969 return ABIAlign;
970}
971
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000972/// ShallowCollectObjCIvars -
973/// Collect all ivars, including those synthesized, in the current class.
974///
975void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad4ba2a172011-01-12 09:06:06 +0000976 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000977 // FIXME. This need be removed but there are two many places which
978 // assume const-ness of ObjCInterfaceDecl
979 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
980 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
981 Iv= Iv->getNextIvar())
982 Ivars.push_back(Iv);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000983}
984
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000985/// DeepCollectObjCIvars -
986/// This routine first collects all declared, but not synthesized, ivars in
987/// super class and then collects all ivars, including those synthesized for
988/// current class. This routine is used for implementation of current class
989/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000990///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000991void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
992 bool leafClass,
Jay Foad4ba2a172011-01-12 09:06:06 +0000993 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000994 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
995 DeepCollectObjCIvars(SuperClass, false, Ivars);
996 if (!leafClass) {
997 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
998 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000999 Ivars.push_back(*I);
1000 }
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001001 else
1002 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian98200742009-05-12 18:14:29 +00001003}
1004
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001005/// CollectInheritedProtocols - Collect all protocols in current class and
1006/// those inherited by it.
1007void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001008 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001009 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001010 // We can use protocol_iterator here instead of
1011 // all_referenced_protocol_iterator since we are walking all categories.
1012 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1013 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001014 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001015 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001016 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001017 PE = Proto->protocol_end(); P != PE; ++P) {
1018 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001019 CollectInheritedProtocols(*P, Protocols);
1020 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001021 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001022
1023 // Categories of this Interface.
1024 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1025 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1026 CollectInheritedProtocols(CDeclChain, Protocols);
1027 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1028 while (SD) {
1029 CollectInheritedProtocols(SD, Protocols);
1030 SD = SD->getSuperClass();
1031 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001032 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001033 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001034 PE = OC->protocol_end(); P != PE; ++P) {
1035 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001036 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001037 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1038 PE = Proto->protocol_end(); P != PE; ++P)
1039 CollectInheritedProtocols(*P, Protocols);
1040 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001041 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001042 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1043 PE = OP->protocol_end(); P != PE; ++P) {
1044 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001045 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001046 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1047 PE = Proto->protocol_end(); P != PE; ++P)
1048 CollectInheritedProtocols(*P, Protocols);
1049 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001050 }
1051}
1052
Jay Foad4ba2a172011-01-12 09:06:06 +00001053unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001054 unsigned count = 0;
1055 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001056 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1057 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001058 count += CDecl->ivar_size();
1059
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001060 // Count ivar defined in this class's implementation. This
1061 // includes synthesized ivars.
1062 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001063 count += ImplDecl->ivar_size();
1064
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001065 return count;
1066}
1067
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001068/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1069ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1070 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1071 I = ObjCImpls.find(D);
1072 if (I != ObjCImpls.end())
1073 return cast<ObjCImplementationDecl>(I->second);
1074 return 0;
1075}
1076/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1077ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1078 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1079 I = ObjCImpls.find(D);
1080 if (I != ObjCImpls.end())
1081 return cast<ObjCCategoryImplDecl>(I->second);
1082 return 0;
1083}
1084
1085/// \brief Set the implementation of ObjCInterfaceDecl.
1086void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1087 ObjCImplementationDecl *ImplD) {
1088 assert(IFaceD && ImplD && "Passed null params");
1089 ObjCImpls[IFaceD] = ImplD;
1090}
1091/// \brief Set the implementation of ObjCCategoryDecl.
1092void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1093 ObjCCategoryImplDecl *ImplD) {
1094 assert(CatD && ImplD && "Passed null params");
1095 ObjCImpls[CatD] = ImplD;
1096}
1097
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001098/// \brief Get the copy initialization expression of VarDecl,or NULL if
1099/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001100Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001101 assert(VD && "Passed null params");
1102 assert(VD->hasAttr<BlocksAttr>() &&
1103 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001104 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001105 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001106 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1107}
1108
1109/// \brief Set the copy inialization expression of a block var decl.
1110void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1111 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001112 assert(VD->hasAttr<BlocksAttr>() &&
1113 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001114 BlockVarCopyInits[VD] = Init;
1115}
1116
John McCalla93c9342009-12-07 02:54:59 +00001117/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001118///
John McCalla93c9342009-12-07 02:54:59 +00001119/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001120/// the TypeLoc wrappers.
1121///
1122/// \param T the type that will be the basis for type source info. This type
1123/// should refer to how the declarator was written in source code, not to
1124/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001125TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001126 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001127 if (!DataSize)
1128 DataSize = TypeLoc::getFullDataSizeForType(T);
1129 else
1130 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001131 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001132
John McCalla93c9342009-12-07 02:54:59 +00001133 TypeSourceInfo *TInfo =
1134 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1135 new (TInfo) TypeSourceInfo(T);
1136 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001137}
1138
John McCalla93c9342009-12-07 02:54:59 +00001139TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001140 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001141 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001142 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001143 return DI;
1144}
1145
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001146const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001147ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001148 return getObjCLayout(D, 0);
1149}
1150
1151const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001152ASTContext::getASTObjCImplementationLayout(
1153 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001154 return getObjCLayout(D->getClassInterface(), D);
1155}
1156
Chris Lattnera7674d82007-07-13 22:13:22 +00001157//===----------------------------------------------------------------------===//
1158// Type creation/memoization methods
1159//===----------------------------------------------------------------------===//
1160
Jay Foad4ba2a172011-01-12 09:06:06 +00001161QualType
John McCall3b657512011-01-19 10:06:00 +00001162ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1163 unsigned fastQuals = quals.getFastQualifiers();
1164 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001165
1166 // Check if we've already instantiated this type.
1167 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001168 ExtQuals::Profile(ID, baseType, quals);
1169 void *insertPos = 0;
1170 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1171 assert(eq->getQualifiers() == quals);
1172 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001173 }
1174
John McCall3b657512011-01-19 10:06:00 +00001175 // If the base type is not canonical, make the appropriate canonical type.
1176 QualType canon;
1177 if (!baseType->isCanonicalUnqualified()) {
1178 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1179 canonSplit.second.addConsistentQualifiers(quals);
1180 canon = getExtQualType(canonSplit.first, canonSplit.second);
1181
1182 // Re-find the insert position.
1183 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1184 }
1185
1186 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1187 ExtQualNodes.InsertNode(eq, insertPos);
1188 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001189}
1190
Jay Foad4ba2a172011-01-12 09:06:06 +00001191QualType
1192ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001193 QualType CanT = getCanonicalType(T);
1194 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001195 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001196
John McCall0953e762009-09-24 19:53:00 +00001197 // If we are composing extended qualifiers together, merge together
1198 // into one ExtQuals node.
1199 QualifierCollector Quals;
1200 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001201
John McCall0953e762009-09-24 19:53:00 +00001202 // If this type already has an address space specified, it cannot get
1203 // another one.
1204 assert(!Quals.hasAddressSpace() &&
1205 "Type cannot be in multiple addr spaces!");
1206 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001207
John McCall0953e762009-09-24 19:53:00 +00001208 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001209}
1210
Chris Lattnerb7d25532009-02-18 22:53:11 +00001211QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001212 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001213 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001214 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001215 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001216
John McCall7f040a92010-12-24 02:08:15 +00001217 if (const PointerType *ptr = T->getAs<PointerType>()) {
1218 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001219 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001220 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1221 return getPointerType(ResultType);
1222 }
1223 }
Mike Stump1eb44332009-09-09 15:08:12 +00001224
John McCall0953e762009-09-24 19:53:00 +00001225 // If we are composing extended qualifiers together, merge together
1226 // into one ExtQuals node.
1227 QualifierCollector Quals;
1228 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001229
John McCall0953e762009-09-24 19:53:00 +00001230 // If this type already has an ObjCGC specified, it cannot get
1231 // another one.
1232 assert(!Quals.hasObjCGCAttr() &&
1233 "Type cannot have multiple ObjCGCs!");
1234 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
John McCall0953e762009-09-24 19:53:00 +00001236 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001237}
Chris Lattnera7674d82007-07-13 22:13:22 +00001238
John McCalle6a365d2010-12-19 02:44:49 +00001239const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1240 FunctionType::ExtInfo Info) {
1241 if (T->getExtInfo() == Info)
1242 return T;
1243
1244 QualType Result;
1245 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1246 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1247 } else {
1248 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1249 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1250 EPI.ExtInfo = Info;
1251 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1252 FPT->getNumArgs(), EPI);
1253 }
1254
1255 return cast<FunctionType>(Result.getTypePtr());
1256}
1257
Reid Spencer5f016e22007-07-11 17:01:13 +00001258/// getComplexType - Return the uniqued reference to the type for a complex
1259/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001260QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 // Unique pointers, to guarantee there is only one pointer of a particular
1262 // structure.
1263 llvm::FoldingSetNodeID ID;
1264 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 void *InsertPos = 0;
1267 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1268 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Reid Spencer5f016e22007-07-11 17:01:13 +00001270 // If the pointee type isn't canonical, this won't be a canonical type either,
1271 // so fill in the canonical type field.
1272 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001273 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001274 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Reid Spencer5f016e22007-07-11 17:01:13 +00001276 // Get the new insert position for the node we care about.
1277 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001278 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001279 }
John McCall6b304a02009-09-24 23:30:46 +00001280 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001281 Types.push_back(New);
1282 ComplexTypes.InsertNode(New, InsertPos);
1283 return QualType(New, 0);
1284}
1285
Reid Spencer5f016e22007-07-11 17:01:13 +00001286/// getPointerType - Return the uniqued reference to the type for a pointer to
1287/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001288QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 // Unique pointers, to guarantee there is only one pointer of a particular
1290 // structure.
1291 llvm::FoldingSetNodeID ID;
1292 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 void *InsertPos = 0;
1295 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1296 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 // If the pointee type isn't canonical, this won't be a canonical type either,
1299 // so fill in the canonical type field.
1300 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001301 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001302 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001303
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 // Get the new insert position for the node we care about.
1305 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001306 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 }
John McCall6b304a02009-09-24 23:30:46 +00001308 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001309 Types.push_back(New);
1310 PointerTypes.InsertNode(New, InsertPos);
1311 return QualType(New, 0);
1312}
1313
Mike Stump1eb44332009-09-09 15:08:12 +00001314/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001315/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001316QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001317 assert(T->isFunctionType() && "block of function types only");
1318 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001319 // structure.
1320 llvm::FoldingSetNodeID ID;
1321 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Steve Naroff5618bd42008-08-27 16:04:49 +00001323 void *InsertPos = 0;
1324 if (BlockPointerType *PT =
1325 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1326 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001327
1328 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001329 // type either so fill in the canonical type field.
1330 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001331 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001332 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001333
Steve Naroff5618bd42008-08-27 16:04:49 +00001334 // Get the new insert position for the node we care about.
1335 BlockPointerType *NewIP =
1336 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001337 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001338 }
John McCall6b304a02009-09-24 23:30:46 +00001339 BlockPointerType *New
1340 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001341 Types.push_back(New);
1342 BlockPointerTypes.InsertNode(New, InsertPos);
1343 return QualType(New, 0);
1344}
1345
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001346/// getLValueReferenceType - Return the uniqued reference to the type for an
1347/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001348QualType
1349ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 // Unique pointers, to guarantee there is only one pointer of a particular
1351 // structure.
1352 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001353 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001354
1355 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001356 if (LValueReferenceType *RT =
1357 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001359
John McCall54e14c42009-10-22 22:37:11 +00001360 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1361
Reid Spencer5f016e22007-07-11 17:01:13 +00001362 // If the referencee type isn't canonical, this won't be a canonical type
1363 // either, so fill in the canonical type field.
1364 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001365 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1366 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1367 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001368
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001370 LValueReferenceType *NewIP =
1371 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001372 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 }
1374
John McCall6b304a02009-09-24 23:30:46 +00001375 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001376 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1377 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001379 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001380
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001381 return QualType(New, 0);
1382}
1383
1384/// getRValueReferenceType - Return the uniqued reference to the type for an
1385/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001386QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001387 // Unique pointers, to guarantee there is only one pointer of a particular
1388 // structure.
1389 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001390 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001391
1392 void *InsertPos = 0;
1393 if (RValueReferenceType *RT =
1394 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1395 return QualType(RT, 0);
1396
John McCall54e14c42009-10-22 22:37:11 +00001397 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1398
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001399 // If the referencee type isn't canonical, this won't be a canonical type
1400 // either, so fill in the canonical type field.
1401 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001402 if (InnerRef || !T.isCanonical()) {
1403 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1404 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001405
1406 // Get the new insert position for the node we care about.
1407 RValueReferenceType *NewIP =
1408 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001409 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001410 }
1411
John McCall6b304a02009-09-24 23:30:46 +00001412 RValueReferenceType *New
1413 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001414 Types.push_back(New);
1415 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001416 return QualType(New, 0);
1417}
1418
Sebastian Redlf30208a2009-01-24 21:16:55 +00001419/// getMemberPointerType - Return the uniqued reference to the type for a
1420/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001421QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001422 // Unique pointers, to guarantee there is only one pointer of a particular
1423 // structure.
1424 llvm::FoldingSetNodeID ID;
1425 MemberPointerType::Profile(ID, T, Cls);
1426
1427 void *InsertPos = 0;
1428 if (MemberPointerType *PT =
1429 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1430 return QualType(PT, 0);
1431
1432 // If the pointee or class type isn't canonical, this won't be a canonical
1433 // type either, so fill in the canonical type field.
1434 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001435 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001436 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1437
1438 // Get the new insert position for the node we care about.
1439 MemberPointerType *NewIP =
1440 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001441 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001442 }
John McCall6b304a02009-09-24 23:30:46 +00001443 MemberPointerType *New
1444 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001445 Types.push_back(New);
1446 MemberPointerTypes.InsertNode(New, InsertPos);
1447 return QualType(New, 0);
1448}
1449
Mike Stump1eb44332009-09-09 15:08:12 +00001450/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001451/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001452QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001453 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001454 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001455 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001456 assert((EltTy->isDependentType() ||
1457 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001458 "Constant array of VLAs is illegal!");
1459
Chris Lattner38aeec72009-05-13 04:12:56 +00001460 // Convert the array size into a canonical width matching the pointer size for
1461 // the target.
1462 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001463 ArySize =
1464 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001467 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Reid Spencer5f016e22007-07-11 17:01:13 +00001469 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001470 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001471 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001473
John McCall3b657512011-01-19 10:06:00 +00001474 // If the element type isn't canonical or has qualifiers, this won't
1475 // be a canonical type either, so fill in the canonical type field.
1476 QualType Canon;
1477 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1478 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1479 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001480 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001481 Canon = getQualifiedType(Canon, canonSplit.second);
1482
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001484 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001485 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001486 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 }
Mike Stump1eb44332009-09-09 15:08:12 +00001488
John McCall6b304a02009-09-24 23:30:46 +00001489 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001490 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001491 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 Types.push_back(New);
1493 return QualType(New, 0);
1494}
1495
John McCallce889032011-01-18 08:40:38 +00001496/// getVariableArrayDecayedType - Turns the given type, which may be
1497/// variably-modified, into the corresponding type with all the known
1498/// sizes replaced with [*].
1499QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1500 // Vastly most common case.
1501 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001502
John McCallce889032011-01-18 08:40:38 +00001503 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001504
John McCallce889032011-01-18 08:40:38 +00001505 SplitQualType split = type.getSplitDesugaredType();
1506 const Type *ty = split.first;
1507 switch (ty->getTypeClass()) {
1508#define TYPE(Class, Base)
1509#define ABSTRACT_TYPE(Class, Base)
1510#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1511#include "clang/AST/TypeNodes.def"
1512 llvm_unreachable("didn't desugar past all non-canonical types?");
1513
1514 // These types should never be variably-modified.
1515 case Type::Builtin:
1516 case Type::Complex:
1517 case Type::Vector:
1518 case Type::ExtVector:
1519 case Type::DependentSizedExtVector:
1520 case Type::ObjCObject:
1521 case Type::ObjCInterface:
1522 case Type::ObjCObjectPointer:
1523 case Type::Record:
1524 case Type::Enum:
1525 case Type::UnresolvedUsing:
1526 case Type::TypeOfExpr:
1527 case Type::TypeOf:
1528 case Type::Decltype:
1529 case Type::DependentName:
1530 case Type::InjectedClassName:
1531 case Type::TemplateSpecialization:
1532 case Type::DependentTemplateSpecialization:
1533 case Type::TemplateTypeParm:
1534 case Type::SubstTemplateTypeParmPack:
1535 case Type::PackExpansion:
1536 llvm_unreachable("type should never be variably-modified");
1537
1538 // These types can be variably-modified but should never need to
1539 // further decay.
1540 case Type::FunctionNoProto:
1541 case Type::FunctionProto:
1542 case Type::BlockPointer:
1543 case Type::MemberPointer:
1544 return type;
1545
1546 // These types can be variably-modified. All these modifications
1547 // preserve structure except as noted by comments.
1548 // TODO: if we ever care about optimizing VLAs, there are no-op
1549 // optimizations available here.
1550 case Type::Pointer:
1551 result = getPointerType(getVariableArrayDecayedType(
1552 cast<PointerType>(ty)->getPointeeType()));
1553 break;
1554
1555 case Type::LValueReference: {
1556 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1557 result = getLValueReferenceType(
1558 getVariableArrayDecayedType(lv->getPointeeType()),
1559 lv->isSpelledAsLValue());
1560 break;
1561 }
1562
1563 case Type::RValueReference: {
1564 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1565 result = getRValueReferenceType(
1566 getVariableArrayDecayedType(lv->getPointeeType()));
1567 break;
1568 }
1569
1570 case Type::ConstantArray: {
1571 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1572 result = getConstantArrayType(
1573 getVariableArrayDecayedType(cat->getElementType()),
1574 cat->getSize(),
1575 cat->getSizeModifier(),
1576 cat->getIndexTypeCVRQualifiers());
1577 break;
1578 }
1579
1580 case Type::DependentSizedArray: {
1581 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1582 result = getDependentSizedArrayType(
1583 getVariableArrayDecayedType(dat->getElementType()),
1584 dat->getSizeExpr(),
1585 dat->getSizeModifier(),
1586 dat->getIndexTypeCVRQualifiers(),
1587 dat->getBracketsRange());
1588 break;
1589 }
1590
1591 // Turn incomplete types into [*] types.
1592 case Type::IncompleteArray: {
1593 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1594 result = getVariableArrayType(
1595 getVariableArrayDecayedType(iat->getElementType()),
1596 /*size*/ 0,
1597 ArrayType::Normal,
1598 iat->getIndexTypeCVRQualifiers(),
1599 SourceRange());
1600 break;
1601 }
1602
1603 // Turn VLA types into [*] types.
1604 case Type::VariableArray: {
1605 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1606 result = getVariableArrayType(
1607 getVariableArrayDecayedType(vat->getElementType()),
1608 /*size*/ 0,
1609 ArrayType::Star,
1610 vat->getIndexTypeCVRQualifiers(),
1611 vat->getBracketsRange());
1612 break;
1613 }
1614 }
1615
1616 // Apply the top-level qualifiers from the original.
1617 return getQualifiedType(result, split.second);
1618}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001619
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001620/// getVariableArrayType - Returns a non-unique reference to the type for a
1621/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001622QualType ASTContext::getVariableArrayType(QualType EltTy,
1623 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001624 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001625 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001626 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001627 // Since we don't unique expressions, it isn't possible to unique VLA's
1628 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001629 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001630
John McCall3b657512011-01-19 10:06:00 +00001631 // Be sure to pull qualifiers off the element type.
1632 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1633 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1634 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001635 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001636 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001637 }
1638
John McCall6b304a02009-09-24 23:30:46 +00001639 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001640 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001641
1642 VariableArrayTypes.push_back(New);
1643 Types.push_back(New);
1644 return QualType(New, 0);
1645}
1646
Douglas Gregor898574e2008-12-05 23:32:09 +00001647/// getDependentSizedArrayType - Returns a non-unique reference to
1648/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001649/// type.
John McCall3b657512011-01-19 10:06:00 +00001650QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1651 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001652 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001653 unsigned elementTypeQuals,
1654 SourceRange brackets) const {
1655 assert((!numElements || numElements->isTypeDependent() ||
1656 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001657 "Size must be type- or value-dependent!");
1658
John McCall3b657512011-01-19 10:06:00 +00001659 // Dependently-sized array types that do not have a specified number
1660 // of elements will have their sizes deduced from a dependent
1661 // initializer. We do no canonicalization here at all, which is okay
1662 // because they can't be used in most locations.
1663 if (!numElements) {
1664 DependentSizedArrayType *newType
1665 = new (*this, TypeAlignment)
1666 DependentSizedArrayType(*this, elementType, QualType(),
1667 numElements, ASM, elementTypeQuals,
1668 brackets);
1669 Types.push_back(newType);
1670 return QualType(newType, 0);
1671 }
1672
1673 // Otherwise, we actually build a new type every time, but we
1674 // also build a canonical type.
1675
1676 SplitQualType canonElementType = getCanonicalType(elementType).split();
1677
1678 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001679 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001680 DependentSizedArrayType::Profile(ID, *this,
1681 QualType(canonElementType.first, 0),
1682 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001683
John McCall3b657512011-01-19 10:06:00 +00001684 // Look for an existing type with these properties.
1685 DependentSizedArrayType *canonTy =
1686 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001687
John McCall3b657512011-01-19 10:06:00 +00001688 // If we don't have one, build one.
1689 if (!canonTy) {
1690 canonTy = new (*this, TypeAlignment)
1691 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1692 QualType(), numElements, ASM, elementTypeQuals,
1693 brackets);
1694 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1695 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001696 }
1697
John McCall3b657512011-01-19 10:06:00 +00001698 // Apply qualifiers from the element type to the array.
1699 QualType canon = getQualifiedType(QualType(canonTy,0),
1700 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001701
John McCall3b657512011-01-19 10:06:00 +00001702 // If we didn't need extra canonicalization for the element type,
1703 // then just use that as our result.
1704 if (QualType(canonElementType.first, 0) == elementType)
1705 return canon;
1706
1707 // Otherwise, we need to build a type which follows the spelling
1708 // of the element type.
1709 DependentSizedArrayType *sugaredType
1710 = new (*this, TypeAlignment)
1711 DependentSizedArrayType(*this, elementType, canon, numElements,
1712 ASM, elementTypeQuals, brackets);
1713 Types.push_back(sugaredType);
1714 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001715}
1716
John McCall3b657512011-01-19 10:06:00 +00001717QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001718 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001719 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001720 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001721 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001722
John McCall3b657512011-01-19 10:06:00 +00001723 void *insertPos = 0;
1724 if (IncompleteArrayType *iat =
1725 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1726 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001727
1728 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001729 // either, so fill in the canonical type field. We also have to pull
1730 // qualifiers off the element type.
1731 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001732
John McCall3b657512011-01-19 10:06:00 +00001733 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1734 SplitQualType canonSplit = getCanonicalType(elementType).split();
1735 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1736 ASM, elementTypeQuals);
1737 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001738
1739 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001740 IncompleteArrayType *existing =
1741 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1742 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001743 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001744
John McCall3b657512011-01-19 10:06:00 +00001745 IncompleteArrayType *newType = new (*this, TypeAlignment)
1746 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001747
John McCall3b657512011-01-19 10:06:00 +00001748 IncompleteArrayTypes.InsertNode(newType, insertPos);
1749 Types.push_back(newType);
1750 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001751}
1752
Steve Naroff73322922007-07-18 18:00:27 +00001753/// getVectorType - Return the unique reference to a vector type of
1754/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001755QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001756 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001757 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 // Check if we've already instantiated a vector of this type.
1760 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001761 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001762
Reid Spencer5f016e22007-07-11 17:01:13 +00001763 void *InsertPos = 0;
1764 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1765 return QualType(VTP, 0);
1766
1767 // If the element type isn't canonical, this won't be a canonical type either,
1768 // so fill in the canonical type field.
1769 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001770 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001771 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Reid Spencer5f016e22007-07-11 17:01:13 +00001773 // Get the new insert position for the node we care about.
1774 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001775 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001776 }
John McCall6b304a02009-09-24 23:30:46 +00001777 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001778 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 VectorTypes.InsertNode(New, InsertPos);
1780 Types.push_back(New);
1781 return QualType(New, 0);
1782}
1783
Nate Begeman213541a2008-04-18 23:10:10 +00001784/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001785/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001786QualType
1787ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall3b657512011-01-19 10:06:00 +00001788 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Steve Naroff73322922007-07-18 18:00:27 +00001790 // Check if we've already instantiated a vector of this type.
1791 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001792 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001793 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001794 void *InsertPos = 0;
1795 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1796 return QualType(VTP, 0);
1797
1798 // If the element type isn't canonical, this won't be a canonical type either,
1799 // so fill in the canonical type field.
1800 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001801 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001802 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Steve Naroff73322922007-07-18 18:00:27 +00001804 // Get the new insert position for the node we care about.
1805 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001806 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001807 }
John McCall6b304a02009-09-24 23:30:46 +00001808 ExtVectorType *New = new (*this, TypeAlignment)
1809 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001810 VectorTypes.InsertNode(New, InsertPos);
1811 Types.push_back(New);
1812 return QualType(New, 0);
1813}
1814
Jay Foad4ba2a172011-01-12 09:06:06 +00001815QualType
1816ASTContext::getDependentSizedExtVectorType(QualType vecType,
1817 Expr *SizeExpr,
1818 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001819 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001820 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001821 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001823 void *InsertPos = 0;
1824 DependentSizedExtVectorType *Canon
1825 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1826 DependentSizedExtVectorType *New;
1827 if (Canon) {
1828 // We already have a canonical version of this array type; use it as
1829 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001830 New = new (*this, TypeAlignment)
1831 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1832 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001833 } else {
1834 QualType CanonVecTy = getCanonicalType(vecType);
1835 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001836 New = new (*this, TypeAlignment)
1837 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1838 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001839
1840 DependentSizedExtVectorType *CanonCheck
1841 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1842 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1843 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001844 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1845 } else {
1846 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1847 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001848 New = new (*this, TypeAlignment)
1849 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001850 }
1851 }
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001853 Types.push_back(New);
1854 return QualType(New, 0);
1855}
1856
Douglas Gregor72564e72009-02-26 23:50:07 +00001857/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001858///
Jay Foad4ba2a172011-01-12 09:06:06 +00001859QualType
1860ASTContext::getFunctionNoProtoType(QualType ResultTy,
1861 const FunctionType::ExtInfo &Info) const {
Rafael Espindola264ba482010-03-30 20:24:48 +00001862 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001863 // Unique functions, to guarantee there is only one function of a particular
1864 // structure.
1865 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001866 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001869 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001870 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001874 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001875 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001876 Canonical =
1877 getFunctionNoProtoType(getCanonicalType(ResultTy),
1878 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Reid Spencer5f016e22007-07-11 17:01:13 +00001880 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001881 FunctionNoProtoType *NewIP =
1882 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001883 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001884 }
Mike Stump1eb44332009-09-09 15:08:12 +00001885
John McCall6b304a02009-09-24 23:30:46 +00001886 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001887 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001888 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001889 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001890 return QualType(New, 0);
1891}
1892
1893/// getFunctionType - Return a normal function type with a typed argument
1894/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00001895QualType
1896ASTContext::getFunctionType(QualType ResultTy,
1897 const QualType *ArgArray, unsigned NumArgs,
1898 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 // Unique functions, to guarantee there is only one function of a particular
1900 // structure.
1901 llvm::FoldingSetNodeID ID;
John McCalle23cf432010-12-14 08:05:40 +00001902 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00001903
1904 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001905 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001906 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001907 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001908
1909 // Determine whether the type being created is already canonical or not.
John McCalle23cf432010-12-14 08:05:40 +00001910 bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001911 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001912 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 isCanonical = false;
1914
John McCalle23cf432010-12-14 08:05:40 +00001915 const CallingConv CallConv = EPI.ExtInfo.getCC();
1916
Reid Spencer5f016e22007-07-11 17:01:13 +00001917 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001918 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001920 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001921 llvm::SmallVector<QualType, 16> CanonicalArgs;
1922 CanonicalArgs.reserve(NumArgs);
1923 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001924 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001925
John McCalle23cf432010-12-14 08:05:40 +00001926 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1927 if (CanonicalEPI.HasExceptionSpec) {
1928 CanonicalEPI.HasExceptionSpec = false;
1929 CanonicalEPI.HasAnyExceptionSpec = false;
1930 CanonicalEPI.NumExceptions = 0;
1931 }
1932 CanonicalEPI.ExtInfo
1933 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1934
Chris Lattnerf52ab252008-04-06 22:59:24 +00001935 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001936 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00001937 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00001938
Reid Spencer5f016e22007-07-11 17:01:13 +00001939 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001940 FunctionProtoType *NewIP =
1941 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001942 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001944
Douglas Gregor72564e72009-02-26 23:50:07 +00001945 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001946 // for two variable size arrays (for parameter and exception types) at the
1947 // end of them.
John McCalle23cf432010-12-14 08:05:40 +00001948 size_t Size = sizeof(FunctionProtoType) +
1949 NumArgs * sizeof(QualType) +
1950 EPI.NumExceptions * sizeof(QualType);
1951 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
1952 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00001953 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001954 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 return QualType(FTP, 0);
1956}
1957
John McCall3cb0ebd2010-03-10 03:28:59 +00001958#ifndef NDEBUG
1959static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1960 if (!isa<CXXRecordDecl>(D)) return false;
1961 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1962 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1963 return true;
1964 if (RD->getDescribedClassTemplate() &&
1965 !isa<ClassTemplateSpecializationDecl>(RD))
1966 return true;
1967 return false;
1968}
1969#endif
1970
1971/// getInjectedClassNameType - Return the unique reference to the
1972/// injected class name type for the specified templated declaration.
1973QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00001974 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00001975 assert(NeedsInjectedClassNameType(Decl));
1976 if (Decl->TypeForDecl) {
1977 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001978 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001979 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1980 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1981 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1982 } else {
John McCallf4c73712011-01-19 06:33:43 +00001983 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00001984 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00001985 Decl->TypeForDecl = newType;
1986 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00001987 }
1988 return QualType(Decl->TypeForDecl, 0);
1989}
1990
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001991/// getTypeDeclType - Return the unique reference to the type for the
1992/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00001993QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001994 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001995 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001996
John McCall19c85762010-02-16 03:57:14 +00001997 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001998 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001999
John McCallbecb8d52010-03-10 06:48:02 +00002000 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2001 "Template type parameter types are always available.");
2002
John McCall19c85762010-02-16 03:57:14 +00002003 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002004 assert(!Record->getPreviousDeclaration() &&
2005 "struct/union has previous declaration");
2006 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002007 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002008 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002009 assert(!Enum->getPreviousDeclaration() &&
2010 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002011 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002012 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002013 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002014 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2015 Decl->TypeForDecl = newType;
2016 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002017 } else
John McCallbecb8d52010-03-10 06:48:02 +00002018 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002019
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002020 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002021}
2022
Reid Spencer5f016e22007-07-11 17:01:13 +00002023/// getTypedefType - Return the unique reference to the type for the
2024/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002025QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002026ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002027 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002029 if (Canonical.isNull())
2030 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002031 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002032 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002033 Decl->TypeForDecl = newType;
2034 Types.push_back(newType);
2035 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002036}
2037
Jay Foad4ba2a172011-01-12 09:06:06 +00002038QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002039 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2040
2041 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2042 if (PrevDecl->TypeForDecl)
2043 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2044
John McCallf4c73712011-01-19 06:33:43 +00002045 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2046 Decl->TypeForDecl = newType;
2047 Types.push_back(newType);
2048 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002049}
2050
Jay Foad4ba2a172011-01-12 09:06:06 +00002051QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002052 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2053
2054 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2055 if (PrevDecl->TypeForDecl)
2056 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2057
John McCallf4c73712011-01-19 06:33:43 +00002058 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2059 Decl->TypeForDecl = newType;
2060 Types.push_back(newType);
2061 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002062}
2063
John McCall9d156a72011-01-06 01:58:22 +00002064QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2065 QualType modifiedType,
2066 QualType equivalentType) {
2067 llvm::FoldingSetNodeID id;
2068 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2069
2070 void *insertPos = 0;
2071 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2072 if (type) return QualType(type, 0);
2073
2074 QualType canon = getCanonicalType(equivalentType);
2075 type = new (*this, TypeAlignment)
2076 AttributedType(canon, attrKind, modifiedType, equivalentType);
2077
2078 Types.push_back(type);
2079 AttributedTypes.InsertNode(type, insertPos);
2080
2081 return QualType(type, 0);
2082}
2083
2084
John McCall49a832b2009-10-18 09:09:24 +00002085/// \brief Retrieve a substitution-result type.
2086QualType
2087ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002088 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002089 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002090 && "replacement types must always be canonical");
2091
2092 llvm::FoldingSetNodeID ID;
2093 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2094 void *InsertPos = 0;
2095 SubstTemplateTypeParmType *SubstParm
2096 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2097
2098 if (!SubstParm) {
2099 SubstParm = new (*this, TypeAlignment)
2100 SubstTemplateTypeParmType(Parm, Replacement);
2101 Types.push_back(SubstParm);
2102 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2103 }
2104
2105 return QualType(SubstParm, 0);
2106}
2107
Douglas Gregorc3069d62011-01-14 02:55:32 +00002108/// \brief Retrieve a
2109QualType ASTContext::getSubstTemplateTypeParmPackType(
2110 const TemplateTypeParmType *Parm,
2111 const TemplateArgument &ArgPack) {
2112#ifndef NDEBUG
2113 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2114 PEnd = ArgPack.pack_end();
2115 P != PEnd; ++P) {
2116 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2117 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2118 }
2119#endif
2120
2121 llvm::FoldingSetNodeID ID;
2122 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2123 void *InsertPos = 0;
2124 if (SubstTemplateTypeParmPackType *SubstParm
2125 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2126 return QualType(SubstParm, 0);
2127
2128 QualType Canon;
2129 if (!Parm->isCanonicalUnqualified()) {
2130 Canon = getCanonicalType(QualType(Parm, 0));
2131 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2132 ArgPack);
2133 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2134 }
2135
2136 SubstTemplateTypeParmPackType *SubstParm
2137 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2138 ArgPack);
2139 Types.push_back(SubstParm);
2140 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2141 return QualType(SubstParm, 0);
2142}
2143
Douglas Gregorfab9d672009-02-05 23:33:38 +00002144/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002145/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002146/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002147QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002148 bool ParameterPack,
Jay Foad4ba2a172011-01-12 09:06:06 +00002149 IdentifierInfo *Name) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002150 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00002151 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002152 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002153 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002154 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2155
2156 if (TypeParm)
2157 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Douglas Gregorefed5c82010-06-16 15:23:05 +00002159 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002160 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00002161 TypeParm = new (*this, TypeAlignment)
2162 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002163
2164 TemplateTypeParmType *TypeCheck
2165 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2166 assert(!TypeCheck && "Template type parameter canonical type broken");
2167 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002168 } else
John McCall6b304a02009-09-24 23:30:46 +00002169 TypeParm = new (*this, TypeAlignment)
2170 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002171
2172 Types.push_back(TypeParm);
2173 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2174
2175 return QualType(TypeParm, 0);
2176}
2177
John McCall3cb0ebd2010-03-10 03:28:59 +00002178TypeSourceInfo *
2179ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2180 SourceLocation NameLoc,
2181 const TemplateArgumentListInfo &Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002182 QualType CanonType) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002183 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2184
2185 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2186 TemplateSpecializationTypeLoc TL
2187 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2188 TL.setTemplateNameLoc(NameLoc);
2189 TL.setLAngleLoc(Args.getLAngleLoc());
2190 TL.setRAngleLoc(Args.getRAngleLoc());
2191 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2192 TL.setArgLocInfo(i, Args[i].getLocInfo());
2193 return DI;
2194}
2195
Mike Stump1eb44332009-09-09 15:08:12 +00002196QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002197ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002198 const TemplateArgumentListInfo &Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002199 QualType Canon) const {
John McCalld5532b62009-11-23 01:53:49 +00002200 unsigned NumArgs = Args.size();
2201
John McCall833ca992009-10-29 08:12:44 +00002202 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2203 ArgVec.reserve(NumArgs);
2204 for (unsigned i = 0; i != NumArgs; ++i)
2205 ArgVec.push_back(Args[i].getArgument());
2206
John McCall31f17ec2010-04-27 00:57:59 +00002207 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00002208 Canon);
John McCall833ca992009-10-29 08:12:44 +00002209}
2210
2211QualType
2212ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002213 const TemplateArgument *Args,
2214 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002215 QualType Canon) const {
Douglas Gregorb88e8882009-07-30 17:40:51 +00002216 if (!Canon.isNull())
2217 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002218 else
2219 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00002220
Douglas Gregor1275ae02009-07-28 23:00:59 +00002221 // Allocate the (non-canonical) template specialization type, but don't
2222 // try to unique it: these types typically have location information that
2223 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00002224 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00002225 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00002226 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002227 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002228 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002229 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00002230 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Douglas Gregor55f6b142009-02-09 18:46:07 +00002232 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002233 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002234}
2235
Mike Stump1eb44332009-09-09 15:08:12 +00002236QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002237ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2238 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002239 unsigned NumArgs) const {
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002240 // Build the canonical template specialization type.
2241 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2242 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2243 CanonArgs.reserve(NumArgs);
2244 for (unsigned I = 0; I != NumArgs; ++I)
2245 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2246
2247 // Determine whether this canonical template specialization type already
2248 // exists.
2249 llvm::FoldingSetNodeID ID;
2250 TemplateSpecializationType::Profile(ID, CanonTemplate,
2251 CanonArgs.data(), NumArgs, *this);
2252
2253 void *InsertPos = 0;
2254 TemplateSpecializationType *Spec
2255 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2256
2257 if (!Spec) {
2258 // Allocate a new canonical template specialization type.
2259 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2260 sizeof(TemplateArgument) * NumArgs),
2261 TypeAlignment);
2262 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2263 CanonArgs.data(), NumArgs,
2264 QualType());
2265 Types.push_back(Spec);
2266 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2267 }
2268
2269 assert(Spec->isDependentType() &&
2270 "Non-dependent template-id type must have a canonical type");
2271 return QualType(Spec, 0);
2272}
2273
2274QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002275ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2276 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002277 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002278 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002279 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002280
2281 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002282 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002283 if (T)
2284 return QualType(T, 0);
2285
Douglas Gregor789b1f62010-02-04 18:10:26 +00002286 QualType Canon = NamedType;
2287 if (!Canon.isCanonical()) {
2288 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002289 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2290 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002291 (void)CheckT;
2292 }
2293
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002294 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002295 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002296 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002297 return QualType(T, 0);
2298}
2299
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002300QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002301ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002302 llvm::FoldingSetNodeID ID;
2303 ParenType::Profile(ID, InnerType);
2304
2305 void *InsertPos = 0;
2306 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2307 if (T)
2308 return QualType(T, 0);
2309
2310 QualType Canon = InnerType;
2311 if (!Canon.isCanonical()) {
2312 Canon = getCanonicalType(InnerType);
2313 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2314 assert(!CheckT && "Paren canonical type broken");
2315 (void)CheckT;
2316 }
2317
2318 T = new (*this) ParenType(InnerType, Canon);
2319 Types.push_back(T);
2320 ParenTypes.InsertNode(T, InsertPos);
2321 return QualType(T, 0);
2322}
2323
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002324QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2325 NestedNameSpecifier *NNS,
2326 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002327 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002328 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2329
2330 if (Canon.isNull()) {
2331 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002332 ElaboratedTypeKeyword CanonKeyword = Keyword;
2333 if (Keyword == ETK_None)
2334 CanonKeyword = ETK_Typename;
2335
2336 if (CanonNNS != NNS || CanonKeyword != Keyword)
2337 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002338 }
2339
2340 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002341 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002342
2343 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002344 DependentNameType *T
2345 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002346 if (T)
2347 return QualType(T, 0);
2348
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002349 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002350 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002351 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002352 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002353}
2354
Mike Stump1eb44332009-09-09 15:08:12 +00002355QualType
John McCall33500952010-06-11 00:33:02 +00002356ASTContext::getDependentTemplateSpecializationType(
2357 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002358 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002359 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002360 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002361 // TODO: avoid this copy
2362 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2363 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2364 ArgCopy.push_back(Args[I].getArgument());
2365 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2366 ArgCopy.size(),
2367 ArgCopy.data());
2368}
2369
2370QualType
2371ASTContext::getDependentTemplateSpecializationType(
2372 ElaboratedTypeKeyword Keyword,
2373 NestedNameSpecifier *NNS,
2374 const IdentifierInfo *Name,
2375 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002376 const TemplateArgument *Args) const {
Douglas Gregor17343172009-04-01 00:28:59 +00002377 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2378
Douglas Gregor789b1f62010-02-04 18:10:26 +00002379 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002380 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2381 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002382
2383 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002384 DependentTemplateSpecializationType *T
2385 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002386 if (T)
2387 return QualType(T, 0);
2388
John McCall33500952010-06-11 00:33:02 +00002389 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002390
John McCall33500952010-06-11 00:33:02 +00002391 ElaboratedTypeKeyword CanonKeyword = Keyword;
2392 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2393
2394 bool AnyNonCanonArgs = false;
2395 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2396 for (unsigned I = 0; I != NumArgs; ++I) {
2397 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2398 if (!CanonArgs[I].structurallyEquals(Args[I]))
2399 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002400 }
2401
John McCall33500952010-06-11 00:33:02 +00002402 QualType Canon;
2403 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2404 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2405 Name, NumArgs,
2406 CanonArgs.data());
2407
2408 // Find the insert position again.
2409 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2410 }
2411
2412 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2413 sizeof(TemplateArgument) * NumArgs),
2414 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002415 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002416 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002417 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002418 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002419 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002420}
2421
Douglas Gregorcded4f62011-01-14 17:04:44 +00002422QualType ASTContext::getPackExpansionType(QualType Pattern,
2423 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002424 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002425 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002426
2427 assert(Pattern->containsUnexpandedParameterPack() &&
2428 "Pack expansions must expand one or more parameter packs");
2429 void *InsertPos = 0;
2430 PackExpansionType *T
2431 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2432 if (T)
2433 return QualType(T, 0);
2434
2435 QualType Canon;
2436 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002437 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002438
2439 // Find the insert position again.
2440 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2441 }
2442
Douglas Gregorcded4f62011-01-14 17:04:44 +00002443 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002444 Types.push_back(T);
2445 PackExpansionTypes.InsertNode(T, InsertPos);
2446 return QualType(T, 0);
2447}
2448
Chris Lattner88cb27a2008-04-07 04:56:42 +00002449/// CmpProtocolNames - Comparison predicate for sorting protocols
2450/// alphabetically.
2451static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2452 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002453 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002454}
2455
John McCallc12c5bb2010-05-15 11:32:37 +00002456static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002457 unsigned NumProtocols) {
2458 if (NumProtocols == 0) return true;
2459
2460 for (unsigned i = 1; i != NumProtocols; ++i)
2461 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2462 return false;
2463 return true;
2464}
2465
2466static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002467 unsigned &NumProtocols) {
2468 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002469
Chris Lattner88cb27a2008-04-07 04:56:42 +00002470 // Sort protocols, keyed by name.
2471 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2472
2473 // Remove duplicates.
2474 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2475 NumProtocols = ProtocolsEnd-Protocols;
2476}
2477
John McCallc12c5bb2010-05-15 11:32:37 +00002478QualType ASTContext::getObjCObjectType(QualType BaseType,
2479 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002480 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002481 // If the base type is an interface and there aren't any protocols
2482 // to add, then the interface type will do just fine.
2483 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2484 return BaseType;
2485
2486 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002487 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002488 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002489 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002490 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2491 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002492
John McCallc12c5bb2010-05-15 11:32:37 +00002493 // Build the canonical type, which has the canonical base type and
2494 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002495 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002496 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2497 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2498 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002499 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2500 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002501 unsigned UniqueCount = NumProtocols;
2502
John McCall54e14c42009-10-22 22:37:11 +00002503 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002504 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2505 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002506 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002507 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2508 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002509 }
2510
2511 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002512 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2513 }
2514
2515 unsigned Size = sizeof(ObjCObjectTypeImpl);
2516 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2517 void *Mem = Allocate(Size, TypeAlignment);
2518 ObjCObjectTypeImpl *T =
2519 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2520
2521 Types.push_back(T);
2522 ObjCObjectTypes.InsertNode(T, InsertPos);
2523 return QualType(T, 0);
2524}
2525
2526/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2527/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002528QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002529 llvm::FoldingSetNodeID ID;
2530 ObjCObjectPointerType::Profile(ID, ObjectT);
2531
2532 void *InsertPos = 0;
2533 if (ObjCObjectPointerType *QT =
2534 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2535 return QualType(QT, 0);
2536
2537 // Find the canonical object type.
2538 QualType Canonical;
2539 if (!ObjectT.isCanonical()) {
2540 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2541
2542 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002543 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2544 }
2545
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002546 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002547 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2548 ObjCObjectPointerType *QType =
2549 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002550
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002551 Types.push_back(QType);
2552 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002553 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002554}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002555
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002556/// getObjCInterfaceType - Return the unique reference to the type for the
2557/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002558QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002559 if (Decl->TypeForDecl)
2560 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002561
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002562 // FIXME: redeclarations?
2563 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2564 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2565 Decl->TypeForDecl = T;
2566 Types.push_back(T);
2567 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002568}
2569
Douglas Gregor72564e72009-02-26 23:50:07 +00002570/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2571/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002572/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002573/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002574/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002575QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002576 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002577 if (tofExpr->isTypeDependent()) {
2578 llvm::FoldingSetNodeID ID;
2579 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002580
Douglas Gregorb1975722009-07-30 23:18:24 +00002581 void *InsertPos = 0;
2582 DependentTypeOfExprType *Canon
2583 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2584 if (Canon) {
2585 // We already have a "canonical" version of an identical, dependent
2586 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002587 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002588 QualType((TypeOfExprType*)Canon, 0));
2589 }
2590 else {
2591 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002592 Canon
2593 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002594 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2595 toe = Canon;
2596 }
2597 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002598 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002599 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002600 }
Steve Naroff9752f252007-08-01 18:02:17 +00002601 Types.push_back(toe);
2602 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002603}
2604
Steve Naroff9752f252007-08-01 18:02:17 +00002605/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2606/// TypeOfType AST's. The only motivation to unique these nodes would be
2607/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002608/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002609/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002610QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002611 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002612 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002613 Types.push_back(tot);
2614 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002615}
2616
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002617/// getDecltypeForExpr - Given an expr, will return the decltype for that
2618/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002619static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002620 if (e->isTypeDependent())
2621 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002622
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002623 // If e is an id expression or a class member access, decltype(e) is defined
2624 // as the type of the entity named by e.
2625 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2626 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2627 return VD->getType();
2628 }
2629 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2630 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2631 return FD->getType();
2632 }
2633 // If e is a function call or an invocation of an overloaded operator,
2634 // (parentheses around e are ignored), decltype(e) is defined as the
2635 // return type of that function.
2636 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2637 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002638
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002639 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002640
2641 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002642 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002643 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002644 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002645
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002646 return T;
2647}
2648
Anders Carlsson395b4752009-06-24 19:06:50 +00002649/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2650/// DecltypeType AST's. The only motivation to unique these nodes would be
2651/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002652/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002653/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002654QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002655 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002656 if (e->isTypeDependent()) {
2657 llvm::FoldingSetNodeID ID;
2658 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002659
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002660 void *InsertPos = 0;
2661 DependentDecltypeType *Canon
2662 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2663 if (Canon) {
2664 // We already have a "canonical" version of an equivalent, dependent
2665 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002666 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002667 QualType((DecltypeType*)Canon, 0));
2668 }
2669 else {
2670 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002671 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002672 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2673 dt = Canon;
2674 }
2675 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002676 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002677 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002678 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002679 Types.push_back(dt);
2680 return QualType(dt, 0);
2681}
2682
Reid Spencer5f016e22007-07-11 17:01:13 +00002683/// getTagDeclType - Return the unique reference to the type for the
2684/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00002685QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00002686 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002687 // FIXME: What is the design on getTagDeclType when it requires casting
2688 // away const? mutable?
2689 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002690}
2691
Mike Stump1eb44332009-09-09 15:08:12 +00002692/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2693/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2694/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002695CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002696 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002697}
2698
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002699/// getSignedWCharType - Return the type of "signed wchar_t".
2700/// Used when in C++, as a GCC extension.
2701QualType ASTContext::getSignedWCharType() const {
2702 // FIXME: derive from "Target" ?
2703 return WCharTy;
2704}
2705
2706/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2707/// Used when in C++, as a GCC extension.
2708QualType ASTContext::getUnsignedWCharType() const {
2709 // FIXME: derive from "Target" ?
2710 return UnsignedIntTy;
2711}
2712
Chris Lattner8b9023b2007-07-13 03:05:23 +00002713/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2714/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2715QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002716 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002717}
2718
Chris Lattnere6327742008-04-02 05:18:44 +00002719//===----------------------------------------------------------------------===//
2720// Type Operators
2721//===----------------------------------------------------------------------===//
2722
Jay Foad4ba2a172011-01-12 09:06:06 +00002723CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00002724 // Push qualifiers into arrays, and then discard any remaining
2725 // qualifiers.
2726 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002727 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002728 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002729 QualType Result;
2730 if (isa<ArrayType>(Ty)) {
2731 Result = getArrayDecayedType(QualType(Ty,0));
2732 } else if (isa<FunctionType>(Ty)) {
2733 Result = getPointerType(QualType(Ty, 0));
2734 } else {
2735 Result = QualType(Ty, 0);
2736 }
2737
2738 return CanQualType::CreateUnsafe(Result);
2739}
2740
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002741
John McCall62c28c82011-01-18 07:41:22 +00002742QualType ASTContext::getUnqualifiedArrayType(QualType type,
2743 Qualifiers &quals) {
2744 SplitQualType splitType = type.getSplitUnqualifiedType();
2745
2746 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2747 // the unqualified desugared type and then drops it on the floor.
2748 // We then have to strip that sugar back off with
2749 // getUnqualifiedDesugaredType(), which is silly.
2750 const ArrayType *AT =
2751 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2752
2753 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00002754 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00002755 quals = splitType.second;
2756 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002757 }
2758
John McCall62c28c82011-01-18 07:41:22 +00002759 // Otherwise, recurse on the array's element type.
2760 QualType elementType = AT->getElementType();
2761 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2762
2763 // If that didn't change the element type, AT has no qualifiers, so we
2764 // can just use the results in splitType.
2765 if (elementType == unqualElementType) {
2766 assert(quals.empty()); // from the recursive call
2767 quals = splitType.second;
2768 return QualType(splitType.first, 0);
2769 }
2770
2771 // Otherwise, add in the qualifiers from the outermost type, then
2772 // build the type back up.
2773 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002774
Douglas Gregor9dadd942010-05-17 18:45:21 +00002775 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002776 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002777 CAT->getSizeModifier(), 0);
2778 }
2779
Douglas Gregor9dadd942010-05-17 18:45:21 +00002780 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002781 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002782 }
2783
Douglas Gregor9dadd942010-05-17 18:45:21 +00002784 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002785 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00002786 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00002787 VAT->getSizeModifier(),
2788 VAT->getIndexTypeCVRQualifiers(),
2789 VAT->getBracketsRange());
2790 }
2791
2792 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00002793 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002794 DSAT->getSizeModifier(), 0,
2795 SourceRange());
2796}
2797
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002798/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2799/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2800/// they point to and return true. If T1 and T2 aren't pointer types
2801/// or pointer-to-member types, or if they are not similar at this
2802/// level, returns false and leaves T1 and T2 unchanged. Top-level
2803/// qualifiers on T1 and T2 are ignored. This function will typically
2804/// be called in a loop that successively "unwraps" pointer and
2805/// pointer-to-member types to compare them at each level.
2806bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2807 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2808 *T2PtrType = T2->getAs<PointerType>();
2809 if (T1PtrType && T2PtrType) {
2810 T1 = T1PtrType->getPointeeType();
2811 T2 = T2PtrType->getPointeeType();
2812 return true;
2813 }
2814
2815 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2816 *T2MPType = T2->getAs<MemberPointerType>();
2817 if (T1MPType && T2MPType &&
2818 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2819 QualType(T2MPType->getClass(), 0))) {
2820 T1 = T1MPType->getPointeeType();
2821 T2 = T2MPType->getPointeeType();
2822 return true;
2823 }
2824
2825 if (getLangOptions().ObjC1) {
2826 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2827 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2828 if (T1OPType && T2OPType) {
2829 T1 = T1OPType->getPointeeType();
2830 T2 = T2OPType->getPointeeType();
2831 return true;
2832 }
2833 }
2834
2835 // FIXME: Block pointers, too?
2836
2837 return false;
2838}
2839
Jay Foad4ba2a172011-01-12 09:06:06 +00002840DeclarationNameInfo
2841ASTContext::getNameForTemplate(TemplateName Name,
2842 SourceLocation NameLoc) const {
John McCall80ad16f2009-11-24 18:42:40 +00002843 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002844 // DNInfo work in progress: CHECKME: what about DNLoc?
2845 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2846
John McCall80ad16f2009-11-24 18:42:40 +00002847 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002848 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002849 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002850 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2851 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002852 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00002853 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2854 // DNInfo work in progress: FIXME: source locations?
2855 DeclarationNameLoc DNLoc;
2856 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2857 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2858 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002859 }
2860 }
2861
John McCall0bd6feb2009-12-02 08:04:21 +00002862 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2863 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002864 // DNInfo work in progress: CHECKME: what about DNLoc?
2865 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002866}
2867
Jay Foad4ba2a172011-01-12 09:06:06 +00002868TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002869 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2870 if (TemplateTemplateParmDecl *TTP
2871 = dyn_cast<TemplateTemplateParmDecl>(Template))
2872 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2873
2874 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002875 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002876 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002877
Douglas Gregor1aee05d2011-01-15 06:45:20 +00002878 if (SubstTemplateTemplateParmPackStorage *SubstPack
2879 = Name.getAsSubstTemplateTemplateParmPack()) {
2880 TemplateTemplateParmDecl *CanonParam
2881 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2882 TemplateArgument CanonArgPack
2883 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2884 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2885 }
2886
John McCall0bd6feb2009-12-02 08:04:21 +00002887 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002888
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002889 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2890 assert(DTN && "Non-dependent template names must refer to template decls.");
2891 return DTN->CanonicalTemplateName;
2892}
2893
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002894bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2895 X = getCanonicalTemplateName(X);
2896 Y = getCanonicalTemplateName(Y);
2897 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2898}
2899
Mike Stump1eb44332009-09-09 15:08:12 +00002900TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00002901ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00002902 switch (Arg.getKind()) {
2903 case TemplateArgument::Null:
2904 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002905
Douglas Gregor1275ae02009-07-28 23:00:59 +00002906 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002907 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002908
Douglas Gregor1275ae02009-07-28 23:00:59 +00002909 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002910 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002911
Douglas Gregor788cd062009-11-11 01:00:40 +00002912 case TemplateArgument::Template:
2913 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00002914
2915 case TemplateArgument::TemplateExpansion:
2916 return TemplateArgument(getCanonicalTemplateName(
2917 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00002918 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00002919
Douglas Gregor1275ae02009-07-28 23:00:59 +00002920 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002921 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002922 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002923
Douglas Gregor1275ae02009-07-28 23:00:59 +00002924 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002925 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002926
Douglas Gregor1275ae02009-07-28 23:00:59 +00002927 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00002928 if (Arg.pack_size() == 0)
2929 return Arg;
2930
Douglas Gregor910f8002010-11-07 23:05:16 +00002931 TemplateArgument *CanonArgs
2932 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00002933 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002934 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002935 AEnd = Arg.pack_end();
2936 A != AEnd; (void)++A, ++Idx)
2937 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002938
Douglas Gregor910f8002010-11-07 23:05:16 +00002939 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00002940 }
2941 }
2942
2943 // Silence GCC warning
2944 assert(false && "Unhandled template argument kind");
2945 return TemplateArgument();
2946}
2947
Douglas Gregord57959a2009-03-27 23:10:48 +00002948NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00002949ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00002950 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002951 return 0;
2952
2953 switch (NNS->getKind()) {
2954 case NestedNameSpecifier::Identifier:
2955 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002956 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002957 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2958 NNS->getAsIdentifier());
2959
2960 case NestedNameSpecifier::Namespace:
2961 // A namespace is canonical; build a nested-name-specifier with
2962 // this namespace and no prefix.
2963 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2964
2965 case NestedNameSpecifier::TypeSpec:
2966 case NestedNameSpecifier::TypeSpecWithTemplate: {
2967 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00002968
2969 // If we have some kind of dependent-named type (e.g., "typename T::type"),
2970 // break it apart into its prefix and identifier, then reconsititute those
2971 // as the canonical nested-name-specifier. This is required to canonicalize
2972 // a dependent nested-name-specifier involving typedefs of dependent-name
2973 // types, e.g.,
2974 // typedef typename T::type T1;
2975 // typedef typename T1::type T2;
2976 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
2977 NestedNameSpecifier *Prefix
2978 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
2979 return NestedNameSpecifier::Create(*this, Prefix,
2980 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
2981 }
2982
Douglas Gregor643f8432010-11-04 00:14:23 +00002983 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00002984 if (const DependentTemplateSpecializationType *DTST
2985 = T->getAs<DependentTemplateSpecializationType>()) {
2986 NestedNameSpecifier *Prefix
2987 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
2988 TemplateName Name
2989 = getDependentTemplateName(Prefix, DTST->getIdentifier());
2990 T = getTemplateSpecializationType(Name,
2991 DTST->getArgs(), DTST->getNumArgs());
2992 T = getCanonicalType(T);
2993 }
2994
John McCall3b657512011-01-19 10:06:00 +00002995 return NestedNameSpecifier::Create(*this, 0, false,
2996 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00002997 }
2998
2999 case NestedNameSpecifier::Global:
3000 // The global specifier is canonical and unique.
3001 return NNS;
3002 }
3003
3004 // Required to silence a GCC warning
3005 return 0;
3006}
3007
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003008
Jay Foad4ba2a172011-01-12 09:06:06 +00003009const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003010 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003011 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003012 // Handle the common positive case fast.
3013 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3014 return AT;
3015 }
Mike Stump1eb44332009-09-09 15:08:12 +00003016
John McCall0953e762009-09-24 19:53:00 +00003017 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003018 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003019 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003020
John McCall0953e762009-09-24 19:53:00 +00003021 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003022 // implements C99 6.7.3p8: "If the specification of an array type includes
3023 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003024
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003025 // If we get here, we either have type qualifiers on the type, or we have
3026 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003027 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003028
John McCall3b657512011-01-19 10:06:00 +00003029 SplitQualType split = T.getSplitDesugaredType();
3030 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003031
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003032 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003033 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3034 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003035 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003036
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003037 // Otherwise, we have an array and we have qualifiers on it. Push the
3038 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003039 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003040
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003041 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3042 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3043 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003044 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003045 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3046 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3047 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003048 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003049
Mike Stump1eb44332009-09-09 15:08:12 +00003050 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003051 = dyn_cast<DependentSizedArrayType>(ATy))
3052 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003053 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003054 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003055 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003056 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003057 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003058
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003059 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003060 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003061 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003062 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003063 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003064 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003065}
3066
Chris Lattnere6327742008-04-02 05:18:44 +00003067/// getArrayDecayedType - Return the properly qualified result of decaying the
3068/// specified array type to a pointer. This operation is non-trivial when
3069/// handling typedefs etc. The canonical type of "T" must be an array type,
3070/// this returns a pointer to a properly qualified element of the array.
3071///
3072/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003073QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003074 // Get the element type with 'getAsArrayType' so that we don't lose any
3075 // typedefs in the element type of the array. This also handles propagation
3076 // of type qualifiers from the array type into the element type if present
3077 // (C99 6.7.3p8).
3078 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3079 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003080
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003081 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003082
3083 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003084 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003085}
3086
John McCall3b657512011-01-19 10:06:00 +00003087QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3088 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003089}
3090
John McCall3b657512011-01-19 10:06:00 +00003091QualType ASTContext::getBaseElementType(QualType type) const {
3092 Qualifiers qs;
3093 while (true) {
3094 SplitQualType split = type.getSplitDesugaredType();
3095 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3096 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003097
John McCall3b657512011-01-19 10:06:00 +00003098 type = array->getElementType();
3099 qs.addConsistentQualifiers(split.second);
3100 }
Mike Stump1eb44332009-09-09 15:08:12 +00003101
John McCall3b657512011-01-19 10:06:00 +00003102 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003103}
3104
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003105/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003106uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003107ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3108 uint64_t ElementCount = 1;
3109 do {
3110 ElementCount *= CA->getSize().getZExtValue();
3111 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3112 } while (CA);
3113 return ElementCount;
3114}
3115
Reid Spencer5f016e22007-07-11 17:01:13 +00003116/// getFloatingRank - Return a relative rank for floating point types.
3117/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003118static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003119 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003120 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003121
John McCall183700f2009-09-21 23:43:11 +00003122 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3123 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00003124 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003125 case BuiltinType::Float: return FloatRank;
3126 case BuiltinType::Double: return DoubleRank;
3127 case BuiltinType::LongDouble: return LongDoubleRank;
3128 }
3129}
3130
Mike Stump1eb44332009-09-09 15:08:12 +00003131/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3132/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003133/// 'typeDomain' is a real floating point or complex type.
3134/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003135QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3136 QualType Domain) const {
3137 FloatingRank EltRank = getFloatingRank(Size);
3138 if (Domain->isComplexType()) {
3139 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00003140 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003141 case FloatRank: return FloatComplexTy;
3142 case DoubleRank: return DoubleComplexTy;
3143 case LongDoubleRank: return LongDoubleComplexTy;
3144 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003145 }
Chris Lattner1361b112008-04-06 23:58:54 +00003146
3147 assert(Domain->isRealFloatingType() && "Unknown domain!");
3148 switch (EltRank) {
3149 default: assert(0 && "getFloatingRank(): illegal value for rank");
3150 case FloatRank: return FloatTy;
3151 case DoubleRank: return DoubleTy;
3152 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003153 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003154}
3155
Chris Lattner7cfeb082008-04-06 23:55:33 +00003156/// getFloatingTypeOrder - Compare the rank of the two specified floating
3157/// point types, ignoring the domain of the type (i.e. 'double' ==
3158/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003159/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003160int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003161 FloatingRank LHSR = getFloatingRank(LHS);
3162 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003163
Chris Lattnera75cea32008-04-06 23:38:49 +00003164 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003165 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003166 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003167 return 1;
3168 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003169}
3170
Chris Lattnerf52ab252008-04-06 22:59:24 +00003171/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3172/// routine will assert if passed a built-in type that isn't an integer or enum,
3173/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003174unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003175 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCallf4c73712011-01-19 06:33:43 +00003176 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00003177 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00003178
Chris Lattner3f59c972010-12-25 23:25:43 +00003179 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3180 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmana3426752009-07-05 23:44:27 +00003181 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3182
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003183 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3184 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3185
3186 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3187 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3188
Chris Lattnerf52ab252008-04-06 22:59:24 +00003189 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00003190 default: assert(0 && "getIntegerRank(): not a built-in integer");
3191 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003192 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003193 case BuiltinType::Char_S:
3194 case BuiltinType::Char_U:
3195 case BuiltinType::SChar:
3196 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003197 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003198 case BuiltinType::Short:
3199 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003200 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003201 case BuiltinType::Int:
3202 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003203 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003204 case BuiltinType::Long:
3205 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003206 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003207 case BuiltinType::LongLong:
3208 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003209 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003210 case BuiltinType::Int128:
3211 case BuiltinType::UInt128:
3212 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003213 }
3214}
3215
Eli Friedman04e83572009-08-20 04:21:42 +00003216/// \brief Whether this is a promotable bitfield reference according
3217/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3218///
3219/// \returns the type this bit-field will promote to, or NULL if no
3220/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003221QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003222 if (E->isTypeDependent() || E->isValueDependent())
3223 return QualType();
3224
Eli Friedman04e83572009-08-20 04:21:42 +00003225 FieldDecl *Field = E->getBitField();
3226 if (!Field)
3227 return QualType();
3228
3229 QualType FT = Field->getType();
3230
3231 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3232 uint64_t BitWidth = BitWidthAP.getZExtValue();
3233 uint64_t IntSize = getTypeSize(IntTy);
3234 // GCC extension compatibility: if the bit-field size is less than or equal
3235 // to the size of int, it gets promoted no matter what its type is.
3236 // For instance, unsigned long bf : 4 gets promoted to signed int.
3237 if (BitWidth < IntSize)
3238 return IntTy;
3239
3240 if (BitWidth == IntSize)
3241 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3242
3243 // Types bigger than int are not subject to promotions, and therefore act
3244 // like the base type.
3245 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3246 // is ridiculous.
3247 return QualType();
3248}
3249
Eli Friedmana95d7572009-08-19 07:44:53 +00003250/// getPromotedIntegerType - Returns the type that Promotable will
3251/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3252/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003253QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003254 assert(!Promotable.isNull());
3255 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003256 if (const EnumType *ET = Promotable->getAs<EnumType>())
3257 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003258 if (Promotable->isSignedIntegerType())
3259 return IntTy;
3260 uint64_t PromotableSize = getTypeSize(Promotable);
3261 uint64_t IntSize = getTypeSize(IntTy);
3262 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3263 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3264}
3265
Mike Stump1eb44332009-09-09 15:08:12 +00003266/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003267/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003268/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003269int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003270 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3271 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003272 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003273
Chris Lattnerf52ab252008-04-06 22:59:24 +00003274 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3275 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003276
Chris Lattner7cfeb082008-04-06 23:55:33 +00003277 unsigned LHSRank = getIntegerRank(LHSC);
3278 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003279
Chris Lattner7cfeb082008-04-06 23:55:33 +00003280 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3281 if (LHSRank == RHSRank) return 0;
3282 return LHSRank > RHSRank ? 1 : -1;
3283 }
Mike Stump1eb44332009-09-09 15:08:12 +00003284
Chris Lattner7cfeb082008-04-06 23:55:33 +00003285 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3286 if (LHSUnsigned) {
3287 // If the unsigned [LHS] type is larger, return it.
3288 if (LHSRank >= RHSRank)
3289 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003290
Chris Lattner7cfeb082008-04-06 23:55:33 +00003291 // If the signed type can represent all values of the unsigned type, it
3292 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003293 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003294 return -1;
3295 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003296
Chris Lattner7cfeb082008-04-06 23:55:33 +00003297 // If the unsigned [RHS] type is larger, return it.
3298 if (RHSRank >= LHSRank)
3299 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003300
Chris Lattner7cfeb082008-04-06 23:55:33 +00003301 // If the signed type can represent all values of the unsigned type, it
3302 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003303 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003304 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003305}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003306
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003307static RecordDecl *
Jay Foad4ba2a172011-01-12 09:06:06 +00003308CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003309 SourceLocation L, IdentifierInfo *Id) {
3310 if (Ctx.getLangOptions().CPlusPlus)
3311 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3312 else
3313 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3314}
3315
Mike Stump1eb44332009-09-09 15:08:12 +00003316// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003317QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003318 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003319 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003320 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003321 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003322 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003323
Anders Carlssonf06273f2007-11-19 00:25:30 +00003324 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003325
Anders Carlsson71993dd2007-08-17 05:31:46 +00003326 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003327 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003328 // int flags;
3329 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003330 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003331 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003332 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003333 FieldTypes[3] = LongTy;
3334
Anders Carlsson71993dd2007-08-17 05:31:46 +00003335 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003336 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003337 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003338 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003339 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003340 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003341 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003342 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003343 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003344 }
3345
Douglas Gregor838db382010-02-11 01:19:42 +00003346 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003347 }
Mike Stump1eb44332009-09-09 15:08:12 +00003348
Anders Carlsson71993dd2007-08-17 05:31:46 +00003349 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003350}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003351
Douglas Gregor319ac892009-04-23 22:29:11 +00003352void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003353 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003354 assert(Rec && "Invalid CFConstantStringType");
3355 CFConstantStringTypeDecl = Rec->getDecl();
3356}
3357
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003358// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003359QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003360 if (!NSConstantStringTypeDecl) {
3361 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003362 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003363 &Idents.get("__builtin_NSString"));
3364 NSConstantStringTypeDecl->startDefinition();
3365
3366 QualType FieldTypes[3];
3367
3368 // const int *isa;
3369 FieldTypes[0] = getPointerType(IntTy.withConst());
3370 // const char *str;
3371 FieldTypes[1] = getPointerType(CharTy.withConst());
3372 // unsigned int length;
3373 FieldTypes[2] = UnsignedIntTy;
3374
3375 // Create fields
3376 for (unsigned i = 0; i < 3; ++i) {
3377 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3378 SourceLocation(), 0,
3379 FieldTypes[i], /*TInfo=*/0,
3380 /*BitWidth=*/0,
3381 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003382 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003383 NSConstantStringTypeDecl->addDecl(Field);
3384 }
3385
3386 NSConstantStringTypeDecl->completeDefinition();
3387 }
3388
3389 return getTagDeclType(NSConstantStringTypeDecl);
3390}
3391
3392void ASTContext::setNSConstantStringType(QualType T) {
3393 const RecordType *Rec = T->getAs<RecordType>();
3394 assert(Rec && "Invalid NSConstantStringType");
3395 NSConstantStringTypeDecl = Rec->getDecl();
3396}
3397
Jay Foad4ba2a172011-01-12 09:06:06 +00003398QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003399 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003400 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003401 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003402 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003403 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003404
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003405 QualType FieldTypes[] = {
3406 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003407 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003408 getPointerType(UnsignedLongTy),
3409 getConstantArrayType(UnsignedLongTy,
3410 llvm::APInt(32, 5), ArrayType::Normal, 0)
3411 };
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Douglas Gregor44b43212008-12-11 16:49:14 +00003413 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003414 FieldDecl *Field = FieldDecl::Create(*this,
3415 ObjCFastEnumerationStateTypeDecl,
3416 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003417 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003418 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003419 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003420 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003421 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003422 }
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Douglas Gregor838db382010-02-11 01:19:42 +00003424 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003425 }
Mike Stump1eb44332009-09-09 15:08:12 +00003426
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003427 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3428}
3429
Jay Foad4ba2a172011-01-12 09:06:06 +00003430QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003431 if (BlockDescriptorType)
3432 return getTagDeclType(BlockDescriptorType);
3433
3434 RecordDecl *T;
3435 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003436 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003437 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003438 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003439
3440 QualType FieldTypes[] = {
3441 UnsignedLongTy,
3442 UnsignedLongTy,
3443 };
3444
3445 const char *FieldNames[] = {
3446 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003447 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003448 };
3449
3450 for (size_t i = 0; i < 2; ++i) {
3451 FieldDecl *Field = FieldDecl::Create(*this,
3452 T,
3453 SourceLocation(),
3454 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003455 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003456 /*BitWidth=*/0,
3457 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003458 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003459 T->addDecl(Field);
3460 }
3461
Douglas Gregor838db382010-02-11 01:19:42 +00003462 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003463
3464 BlockDescriptorType = T;
3465
3466 return getTagDeclType(BlockDescriptorType);
3467}
3468
3469void ASTContext::setBlockDescriptorType(QualType T) {
3470 const RecordType *Rec = T->getAs<RecordType>();
3471 assert(Rec && "Invalid BlockDescriptorType");
3472 BlockDescriptorType = Rec->getDecl();
3473}
3474
Jay Foad4ba2a172011-01-12 09:06:06 +00003475QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003476 if (BlockDescriptorExtendedType)
3477 return getTagDeclType(BlockDescriptorExtendedType);
3478
3479 RecordDecl *T;
3480 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003481 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003482 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003483 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003484
3485 QualType FieldTypes[] = {
3486 UnsignedLongTy,
3487 UnsignedLongTy,
3488 getPointerType(VoidPtrTy),
3489 getPointerType(VoidPtrTy)
3490 };
3491
3492 const char *FieldNames[] = {
3493 "reserved",
3494 "Size",
3495 "CopyFuncPtr",
3496 "DestroyFuncPtr"
3497 };
3498
3499 for (size_t i = 0; i < 4; ++i) {
3500 FieldDecl *Field = FieldDecl::Create(*this,
3501 T,
3502 SourceLocation(),
3503 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003504 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003505 /*BitWidth=*/0,
3506 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003507 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003508 T->addDecl(Field);
3509 }
3510
Douglas Gregor838db382010-02-11 01:19:42 +00003511 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003512
3513 BlockDescriptorExtendedType = T;
3514
3515 return getTagDeclType(BlockDescriptorExtendedType);
3516}
3517
3518void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3519 const RecordType *Rec = T->getAs<RecordType>();
3520 assert(Rec && "Invalid BlockDescriptorType");
3521 BlockDescriptorExtendedType = Rec->getDecl();
3522}
3523
Jay Foad4ba2a172011-01-12 09:06:06 +00003524bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003525 if (Ty->isBlockPointerType())
3526 return true;
3527 if (isObjCNSObjectType(Ty))
3528 return true;
3529 if (Ty->isObjCObjectPointerType())
3530 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003531 if (getLangOptions().CPlusPlus) {
3532 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3533 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3534 return RD->hasConstCopyConstructor(*this);
3535
3536 }
3537 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003538 return false;
3539}
3540
Jay Foad4ba2a172011-01-12 09:06:06 +00003541QualType
3542ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003543 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003544 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003545 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003546 // unsigned int __flags;
3547 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003548 // void *__copy_helper; // as needed
3549 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003550 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003551 // } *
3552
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003553 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3554
3555 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003556 llvm::SmallString<36> Name;
3557 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3558 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003559 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003560 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003561 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003562 T->startDefinition();
3563 QualType Int32Ty = IntTy;
3564 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3565 QualType FieldTypes[] = {
3566 getPointerType(VoidPtrTy),
3567 getPointerType(getTagDeclType(T)),
3568 Int32Ty,
3569 Int32Ty,
3570 getPointerType(VoidPtrTy),
3571 getPointerType(VoidPtrTy),
3572 Ty
3573 };
3574
Daniel Dunbar4087f272010-08-17 22:39:59 +00003575 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003576 "__isa",
3577 "__forwarding",
3578 "__flags",
3579 "__size",
3580 "__copy_helper",
3581 "__destroy_helper",
3582 DeclName,
3583 };
3584
3585 for (size_t i = 0; i < 7; ++i) {
3586 if (!HasCopyAndDispose && i >=4 && i <= 5)
3587 continue;
3588 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3589 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003590 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003591 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003592 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003593 T->addDecl(Field);
3594 }
3595
Douglas Gregor838db382010-02-11 01:19:42 +00003596 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003597
3598 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003599}
3600
3601
3602QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003603 bool BlockHasCopyDispose,
Jay Foad4ba2a172011-01-12 09:06:06 +00003604 llvm::SmallVectorImpl<const Expr *> &Layout) const {
John McCallea1471e2010-05-20 01:18:31 +00003605
Mike Stumpadaaad32009-10-20 02:12:22 +00003606 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003607 llvm::SmallString<36> Name;
3608 llvm::raw_svector_ostream(Name) << "__block_literal_"
3609 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003610 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003611 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003612 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003613 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003614 QualType FieldTypes[] = {
3615 getPointerType(VoidPtrTy),
3616 IntTy,
3617 IntTy,
3618 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003619 (BlockHasCopyDispose ?
3620 getPointerType(getBlockDescriptorExtendedType()) :
3621 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003622 };
3623
3624 const char *FieldNames[] = {
3625 "__isa",
3626 "__flags",
3627 "__reserved",
3628 "__FuncPtr",
3629 "__descriptor"
3630 };
3631
3632 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003633 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003634 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003635 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003636 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003637 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003638 T->addDecl(Field);
3639 }
3640
John McCallea1471e2010-05-20 01:18:31 +00003641 for (unsigned i = 0; i < Layout.size(); ++i) {
3642 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003643
John McCallea1471e2010-05-20 01:18:31 +00003644 QualType FieldType = E->getType();
3645 IdentifierInfo *FieldName = 0;
3646 if (isa<CXXThisExpr>(E)) {
3647 FieldName = &Idents.get("this");
3648 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3649 const ValueDecl *D = BDRE->getDecl();
3650 FieldName = D->getIdentifier();
3651 if (BDRE->isByRef())
Daniel Dunbar4087f272010-08-17 22:39:59 +00003652 FieldType = BuildByRefType(D->getName(), FieldType);
John McCallea1471e2010-05-20 01:18:31 +00003653 } else {
3654 // Padding.
3655 assert(isa<ConstantArrayType>(FieldType) &&
3656 isa<DeclRefExpr>(E) &&
3657 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3658 "doesn't match characteristics of padding decl");
3659 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003660
3661 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003662 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003663 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003664 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003665 T->addDecl(Field);
3666 }
3667
Douglas Gregor838db382010-02-11 01:19:42 +00003668 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003669
3670 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003671}
3672
Douglas Gregor319ac892009-04-23 22:29:11 +00003673void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003674 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003675 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3676 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3677}
3678
Anders Carlssone8c49532007-10-29 06:33:42 +00003679// This returns true if a type has been typedefed to BOOL:
3680// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003681static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003682 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003683 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3684 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003685
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003686 return false;
3687}
3688
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003689/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003690/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003691CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck199c3d62010-01-11 17:06:35 +00003692 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003693
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003694 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003695 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003696 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003697 // Treat arrays as pointers, since that's how they're passed in.
3698 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003699 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003700 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003701}
3702
3703static inline
3704std::string charUnitsToString(const CharUnits &CU) {
3705 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003706}
3707
John McCall6b5a61b2011-02-07 10:33:21 +00003708/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003709/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00003710std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3711 std::string S;
3712
David Chisnall5e530af2009-11-17 19:33:30 +00003713 const BlockDecl *Decl = Expr->getBlockDecl();
3714 QualType BlockTy =
3715 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3716 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003717 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003718 // Compute size of all parameters.
3719 // Start with computing size of a pointer in number of bytes.
3720 // FIXME: There might(should) be a better way of doing this computation!
3721 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003722 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3723 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003724 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003725 E = Decl->param_end(); PI != E; ++PI) {
3726 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003727 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003728 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003729 ParmOffset += sz;
3730 }
3731 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003732 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003733 // Block pointer and offset.
3734 S += "@?0";
3735 ParmOffset = PtrSize;
3736
3737 // Argument types.
3738 ParmOffset = PtrSize;
3739 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3740 Decl->param_end(); PI != E; ++PI) {
3741 ParmVarDecl *PVDecl = *PI;
3742 QualType PType = PVDecl->getOriginalType();
3743 if (const ArrayType *AT =
3744 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3745 // Use array's original type only if it has known number of
3746 // elements.
3747 if (!isa<ConstantArrayType>(AT))
3748 PType = PVDecl->getType();
3749 } else if (PType->isFunctionType())
3750 PType = PVDecl->getType();
3751 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003752 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003753 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003754 }
John McCall6b5a61b2011-02-07 10:33:21 +00003755
3756 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00003757}
3758
David Chisnall5389f482010-12-30 14:05:53 +00003759void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3760 std::string& S) {
3761 // Encode result type.
3762 getObjCEncodingForType(Decl->getResultType(), S);
3763 CharUnits ParmOffset;
3764 // Compute size of all parameters.
3765 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3766 E = Decl->param_end(); PI != E; ++PI) {
3767 QualType PType = (*PI)->getType();
3768 CharUnits sz = getObjCEncodingTypeSize(PType);
3769 assert (sz.isPositive() &&
3770 "getObjCEncodingForMethodDecl - Incomplete param type");
3771 ParmOffset += sz;
3772 }
3773 S += charUnitsToString(ParmOffset);
3774 ParmOffset = CharUnits::Zero();
3775
3776 // Argument types.
3777 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3778 E = Decl->param_end(); PI != E; ++PI) {
3779 ParmVarDecl *PVDecl = *PI;
3780 QualType PType = PVDecl->getOriginalType();
3781 if (const ArrayType *AT =
3782 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3783 // Use array's original type only if it has known number of
3784 // elements.
3785 if (!isa<ConstantArrayType>(AT))
3786 PType = PVDecl->getType();
3787 } else if (PType->isFunctionType())
3788 PType = PVDecl->getType();
3789 getObjCEncodingForType(PType, S);
3790 S += charUnitsToString(ParmOffset);
3791 ParmOffset += getObjCEncodingTypeSize(PType);
3792 }
3793}
3794
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003795/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003796/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003797void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00003798 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003799 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003800 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003801 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003802 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003803 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003804 // Compute size of all parameters.
3805 // Start with computing size of a pointer in number of bytes.
3806 // FIXME: There might(should) be a better way of doing this computation!
3807 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003808 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003809 // The first two arguments (self and _cmd) are pointers; account for
3810 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003811 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003812 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003813 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003814 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003815 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003816 assert (sz.isPositive() &&
3817 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003818 ParmOffset += sz;
3819 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003820 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003821 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003822 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003823
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003824 // Argument types.
3825 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003826 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003827 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003828 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003829 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003830 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003831 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3832 // Use array's original type only if it has known number of
3833 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003834 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003835 PType = PVDecl->getType();
3836 } else if (PType->isFunctionType())
3837 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003838 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003839 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003840 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003841 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003842 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003843 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003844 }
3845}
3846
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003847/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003848/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003849/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3850/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003851/// Property attributes are stored as a comma-delimited C string. The simple
3852/// attributes readonly and bycopy are encoded as single characters. The
3853/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3854/// encoded as single characters, followed by an identifier. Property types
3855/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003856/// these attributes are defined by the following enumeration:
3857/// @code
3858/// enum PropertyAttributes {
3859/// kPropertyReadOnly = 'R', // property is read-only.
3860/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3861/// kPropertyByref = '&', // property is a reference to the value last assigned
3862/// kPropertyDynamic = 'D', // property is dynamic
3863/// kPropertyGetter = 'G', // followed by getter selector name
3864/// kPropertySetter = 'S', // followed by setter selector name
3865/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3866/// kPropertyType = 't' // followed by old-style type encoding.
3867/// kPropertyWeak = 'W' // 'weak' property
3868/// kPropertyStrong = 'P' // property GC'able
3869/// kPropertyNonAtomic = 'N' // property non-atomic
3870/// };
3871/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003872void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003873 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00003874 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003875 // Collect information from the property implementation decl(s).
3876 bool Dynamic = false;
3877 ObjCPropertyImplDecl *SynthesizePID = 0;
3878
3879 // FIXME: Duplicated code due to poor abstraction.
3880 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003881 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003882 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3883 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003884 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003885 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003886 ObjCPropertyImplDecl *PID = *i;
3887 if (PID->getPropertyDecl() == PD) {
3888 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3889 Dynamic = true;
3890 } else {
3891 SynthesizePID = PID;
3892 }
3893 }
3894 }
3895 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003896 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003897 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003898 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003899 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003900 ObjCPropertyImplDecl *PID = *i;
3901 if (PID->getPropertyDecl() == PD) {
3902 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3903 Dynamic = true;
3904 } else {
3905 SynthesizePID = PID;
3906 }
3907 }
Mike Stump1eb44332009-09-09 15:08:12 +00003908 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003909 }
3910 }
3911
3912 // FIXME: This is not very efficient.
3913 S = "T";
3914
3915 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003916 // GCC has some special rules regarding encoding of properties which
3917 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003918 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003919 true /* outermost type */,
3920 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003921
3922 if (PD->isReadOnly()) {
3923 S += ",R";
3924 } else {
3925 switch (PD->getSetterKind()) {
3926 case ObjCPropertyDecl::Assign: break;
3927 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003928 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003929 }
3930 }
3931
3932 // It really isn't clear at all what this means, since properties
3933 // are "dynamic by default".
3934 if (Dynamic)
3935 S += ",D";
3936
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003937 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3938 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003939
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003940 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3941 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003942 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003943 }
3944
3945 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3946 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003947 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003948 }
3949
3950 if (SynthesizePID) {
3951 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3952 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003953 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003954 }
3955
3956 // FIXME: OBJCGC: weak & strong
3957}
3958
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003959/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003960/// Another legacy compatibility encoding: 32-bit longs are encoded as
3961/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003962/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3963///
3964void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003965 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003966 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00003967 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003968 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003969 else
Jay Foad4ba2a172011-01-12 09:06:06 +00003970 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003971 PointeeTy = IntTy;
3972 }
3973 }
3974}
3975
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003976void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00003977 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003978 // We follow the behavior of gcc, expanding structures which are
3979 // directly pointed to, and expanding embedded structures. Note that
3980 // these rules are sufficient to prevent recursive encoding of the
3981 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003982 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003983 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003984}
3985
David Chisnall64fd7e82010-06-04 01:10:52 +00003986static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3987 switch (T->getAs<BuiltinType>()->getKind()) {
3988 default: assert(0 && "Unhandled builtin type kind");
3989 case BuiltinType::Void: return 'v';
3990 case BuiltinType::Bool: return 'B';
3991 case BuiltinType::Char_U:
3992 case BuiltinType::UChar: return 'C';
3993 case BuiltinType::UShort: return 'S';
3994 case BuiltinType::UInt: return 'I';
3995 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00003996 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00003997 case BuiltinType::UInt128: return 'T';
3998 case BuiltinType::ULongLong: return 'Q';
3999 case BuiltinType::Char_S:
4000 case BuiltinType::SChar: return 'c';
4001 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004002 case BuiltinType::WChar_S:
4003 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004004 case BuiltinType::Int: return 'i';
4005 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004006 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004007 case BuiltinType::LongLong: return 'q';
4008 case BuiltinType::Int128: return 't';
4009 case BuiltinType::Float: return 'f';
4010 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004011 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004012 }
4013}
4014
Jay Foad4ba2a172011-01-12 09:06:06 +00004015static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004016 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004017 const Expr *E = FD->getBitWidth();
4018 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004019 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004020 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4021 // The GNU runtime requires more information; bitfields are encoded as b,
4022 // then the offset (in bits) of the first element, then the type of the
4023 // bitfield, then the size in bits. For example, in this structure:
4024 //
4025 // struct
4026 // {
4027 // int integer;
4028 // int flags:2;
4029 // };
4030 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4031 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4032 // information is not especially sensible, but we're stuck with it for
4033 // compatibility with GCC, although providing it breaks anything that
4034 // actually uses runtime introspection and wants to work on both runtimes...
4035 if (!Ctx->getLangOptions().NeXTRuntime) {
4036 const RecordDecl *RD = FD->getParent();
4037 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4038 // FIXME: This same linear search is also used in ExprConstant - it might
4039 // be better if the FieldDecl stored its offset. We'd be increasing the
4040 // size of the object slightly, but saving some time every time it is used.
4041 unsigned i = 0;
4042 for (RecordDecl::field_iterator Field = RD->field_begin(),
4043 FieldEnd = RD->field_end();
4044 Field != FieldEnd; (void)++Field, ++i) {
4045 if (*Field == FD)
4046 break;
4047 }
4048 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnallc7ff82c2010-12-26 20:12:30 +00004049 if (T->isEnumeralType())
4050 S += 'i';
4051 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004052 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004053 }
4054 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004055 S += llvm::utostr(N);
4056}
4057
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004058// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004059void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4060 bool ExpandPointedToStructures,
4061 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004062 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004063 bool OutermostType,
Jay Foad4ba2a172011-01-12 09:06:06 +00004064 bool EncodingProperty) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004065 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004066 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004067 return EncodeBitField(this, S, T, FD);
4068 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004069 return;
4070 }
Mike Stump1eb44332009-09-09 15:08:12 +00004071
John McCall183700f2009-09-21 23:43:11 +00004072 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004073 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004074 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004075 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004076 return;
4077 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004078
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004079 // encoding for pointer or r3eference types.
4080 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004081 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004082 if (PT->isObjCSelType()) {
4083 S += ':';
4084 return;
4085 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004086 PointeeTy = PT->getPointeeType();
4087 }
4088 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4089 PointeeTy = RT->getPointeeType();
4090 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004091 bool isReadOnly = false;
4092 // For historical/compatibility reasons, the read-only qualifier of the
4093 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4094 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004095 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004096 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004097 if (OutermostType && T.isConstQualified()) {
4098 isReadOnly = true;
4099 S += 'r';
4100 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004101 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004102 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004103 while (P->getAs<PointerType>())
4104 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004105 if (P.isConstQualified()) {
4106 isReadOnly = true;
4107 S += 'r';
4108 }
4109 }
4110 if (isReadOnly) {
4111 // Another legacy compatibility encoding. Some ObjC qualifier and type
4112 // combinations need to be rearranged.
4113 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00004114 if (llvm::StringRef(S).endswith("nr"))
4115 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004116 }
Mike Stump1eb44332009-09-09 15:08:12 +00004117
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004118 if (PointeeTy->isCharType()) {
4119 // char pointer types should be encoded as '*' unless it is a
4120 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004121 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004122 S += '*';
4123 return;
4124 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004125 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004126 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4127 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4128 S += '#';
4129 return;
4130 }
4131 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4132 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4133 S += '@';
4134 return;
4135 }
4136 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004137 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004138 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004139 getLegacyIntegralTypeEncoding(PointeeTy);
4140
Mike Stump1eb44332009-09-09 15:08:12 +00004141 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004142 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004143 return;
4144 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004145
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004146 if (const ArrayType *AT =
4147 // Ignore type qualifiers etc.
4148 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004149 if (isa<IncompleteArrayType>(AT)) {
4150 // Incomplete arrays are encoded as a pointer to the array element.
4151 S += '^';
4152
Mike Stump1eb44332009-09-09 15:08:12 +00004153 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004154 false, ExpandStructures, FD);
4155 } else {
4156 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004157
Anders Carlsson559a8332009-02-22 01:38:57 +00004158 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4159 S += llvm::utostr(CAT->getSize().getZExtValue());
4160 else {
4161 //Variable length arrays are encoded as a regular array with 0 elements.
4162 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4163 S += '0';
4164 }
Mike Stump1eb44332009-09-09 15:08:12 +00004165
4166 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004167 false, ExpandStructures, FD);
4168 S += ']';
4169 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004170 return;
4171 }
Mike Stump1eb44332009-09-09 15:08:12 +00004172
John McCall183700f2009-09-21 23:43:11 +00004173 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004174 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004175 return;
4176 }
Mike Stump1eb44332009-09-09 15:08:12 +00004177
Ted Kremenek6217b802009-07-29 21:53:49 +00004178 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004179 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004180 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004181 // Anonymous structures print as '?'
4182 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4183 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004184 if (ClassTemplateSpecializationDecl *Spec
4185 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4186 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4187 std::string TemplateArgsStr
4188 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004189 TemplateArgs.data(),
4190 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004191 (*this).PrintingPolicy);
4192
4193 S += TemplateArgsStr;
4194 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004195 } else {
4196 S += '?';
4197 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004198 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004199 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004200 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4201 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00004202 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004203 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004204 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00004205 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004206 S += '"';
4207 }
Mike Stump1eb44332009-09-09 15:08:12 +00004208
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004209 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004210 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004211 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004212 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004213 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004214 QualType qt = Field->getType();
4215 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00004216 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004217 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004218 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004219 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004220 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004221 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004222 return;
4223 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004224
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004225 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004226 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004227 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004228 else
4229 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004230 return;
4231 }
Mike Stump1eb44332009-09-09 15:08:12 +00004232
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004233 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004234 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004235 return;
4236 }
Mike Stump1eb44332009-09-09 15:08:12 +00004237
John McCallc12c5bb2010-05-15 11:32:37 +00004238 // Ignore protocol qualifiers when mangling at this level.
4239 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4240 T = OT->getBaseType();
4241
John McCall0953e762009-09-24 19:53:00 +00004242 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004243 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004244 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004245 S += '{';
4246 const IdentifierInfo *II = OI->getIdentifier();
4247 S += II->getName();
4248 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004249 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4250 DeepCollectObjCIvars(OI, true, Ivars);
4251 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4252 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4253 if (Field->isBitField())
4254 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004255 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004256 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004257 }
4258 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004259 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004260 }
Mike Stump1eb44332009-09-09 15:08:12 +00004261
John McCall183700f2009-09-21 23:43:11 +00004262 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004263 if (OPT->isObjCIdType()) {
4264 S += '@';
4265 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004266 }
Mike Stump1eb44332009-09-09 15:08:12 +00004267
Steve Naroff27d20a22009-10-28 22:03:49 +00004268 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4269 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4270 // Since this is a binary compatibility issue, need to consult with runtime
4271 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004272 S += '#';
4273 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004274 }
Mike Stump1eb44332009-09-09 15:08:12 +00004275
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004276 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004277 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004278 ExpandPointedToStructures,
4279 ExpandStructures, FD);
4280 if (FD || EncodingProperty) {
4281 // Note that we do extended encoding of protocol qualifer list
4282 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004283 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004284 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4285 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004286 S += '<';
4287 S += (*I)->getNameAsString();
4288 S += '>';
4289 }
4290 S += '"';
4291 }
4292 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004293 }
Mike Stump1eb44332009-09-09 15:08:12 +00004294
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004295 QualType PointeeTy = OPT->getPointeeType();
4296 if (!EncodingProperty &&
4297 isa<TypedefType>(PointeeTy.getTypePtr())) {
4298 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004299 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004300 // {...};
4301 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004302 getObjCEncodingForTypeImpl(PointeeTy, S,
4303 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004304 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004305 return;
4306 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004307
4308 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004309 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004310 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004311 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004312 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4313 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004314 S += '<';
4315 S += (*I)->getNameAsString();
4316 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004317 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004318 S += '"';
4319 }
4320 return;
4321 }
Mike Stump1eb44332009-09-09 15:08:12 +00004322
John McCall532ec7b2010-05-17 23:56:34 +00004323 // gcc just blithely ignores member pointers.
4324 // TODO: maybe there should be a mangling for these
4325 if (T->getAs<MemberPointerType>())
4326 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004327
4328 if (T->isVectorType()) {
4329 // This matches gcc's encoding, even though technically it is
4330 // insufficient.
4331 // FIXME. We should do a better job than gcc.
4332 return;
4333 }
4334
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004335 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004336}
4337
Mike Stump1eb44332009-09-09 15:08:12 +00004338void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004339 std::string& S) const {
4340 if (QT & Decl::OBJC_TQ_In)
4341 S += 'n';
4342 if (QT & Decl::OBJC_TQ_Inout)
4343 S += 'N';
4344 if (QT & Decl::OBJC_TQ_Out)
4345 S += 'o';
4346 if (QT & Decl::OBJC_TQ_Bycopy)
4347 S += 'O';
4348 if (QT & Decl::OBJC_TQ_Byref)
4349 S += 'R';
4350 if (QT & Decl::OBJC_TQ_Oneway)
4351 S += 'V';
4352}
4353
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004354void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004355 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004356
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004357 BuiltinVaListType = T;
4358}
4359
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004360void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004361 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00004362}
4363
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004364void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004365 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004366}
4367
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004368void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004369 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004370}
4371
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004372void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004373 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004374}
4375
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004376void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004377 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004378 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004379
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004380 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004381}
4382
John McCall0bd6feb2009-12-02 08:04:21 +00004383/// \brief Retrieve the template name that corresponds to a non-empty
4384/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004385TemplateName
4386ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4387 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004388 unsigned size = End - Begin;
4389 assert(size > 1 && "set is not overloaded!");
4390
4391 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4392 size * sizeof(FunctionTemplateDecl*));
4393 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4394
4395 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004396 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004397 NamedDecl *D = *I;
4398 assert(isa<FunctionTemplateDecl>(D) ||
4399 (isa<UsingShadowDecl>(D) &&
4400 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4401 *Storage++ = D;
4402 }
4403
4404 return TemplateName(OT);
4405}
4406
Douglas Gregor7532dc62009-03-30 22:58:21 +00004407/// \brief Retrieve the template name that represents a qualified
4408/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004409TemplateName
4410ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4411 bool TemplateKeyword,
4412 TemplateDecl *Template) const {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004413 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004414 llvm::FoldingSetNodeID ID;
4415 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4416
4417 void *InsertPos = 0;
4418 QualifiedTemplateName *QTN =
4419 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4420 if (!QTN) {
4421 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4422 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4423 }
4424
4425 return TemplateName(QTN);
4426}
4427
4428/// \brief Retrieve the template name that represents a dependent
4429/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004430TemplateName
4431ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4432 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004433 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004434 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004435
4436 llvm::FoldingSetNodeID ID;
4437 DependentTemplateName::Profile(ID, NNS, Name);
4438
4439 void *InsertPos = 0;
4440 DependentTemplateName *QTN =
4441 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4442
4443 if (QTN)
4444 return TemplateName(QTN);
4445
4446 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4447 if (CanonNNS == NNS) {
4448 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4449 } else {
4450 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4451 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004452 DependentTemplateName *CheckQTN =
4453 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4454 assert(!CheckQTN && "Dependent type name canonicalization broken");
4455 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004456 }
4457
4458 DependentTemplateNames.InsertNode(QTN, InsertPos);
4459 return TemplateName(QTN);
4460}
4461
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004462/// \brief Retrieve the template name that represents a dependent
4463/// template name such as \c MetaFun::template operator+.
4464TemplateName
4465ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004466 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004467 assert((!NNS || NNS->isDependent()) &&
4468 "Nested name specifier must be dependent");
4469
4470 llvm::FoldingSetNodeID ID;
4471 DependentTemplateName::Profile(ID, NNS, Operator);
4472
4473 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004474 DependentTemplateName *QTN
4475 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004476
4477 if (QTN)
4478 return TemplateName(QTN);
4479
4480 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4481 if (CanonNNS == NNS) {
4482 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4483 } else {
4484 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4485 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004486
4487 DependentTemplateName *CheckQTN
4488 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4489 assert(!CheckQTN && "Dependent template name canonicalization broken");
4490 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004491 }
4492
4493 DependentTemplateNames.InsertNode(QTN, InsertPos);
4494 return TemplateName(QTN);
4495}
4496
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004497TemplateName
4498ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4499 const TemplateArgument &ArgPack) const {
4500 ASTContext &Self = const_cast<ASTContext &>(*this);
4501 llvm::FoldingSetNodeID ID;
4502 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4503
4504 void *InsertPos = 0;
4505 SubstTemplateTemplateParmPackStorage *Subst
4506 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4507
4508 if (!Subst) {
4509 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4510 ArgPack.pack_size(),
4511 ArgPack.pack_begin());
4512 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4513 }
4514
4515 return TemplateName(Subst);
4516}
4517
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004518/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004519/// TargetInfo, produce the corresponding type. The unsigned @p Type
4520/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004521CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004522 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004523 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004524 case TargetInfo::SignedShort: return ShortTy;
4525 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4526 case TargetInfo::SignedInt: return IntTy;
4527 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4528 case TargetInfo::SignedLong: return LongTy;
4529 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4530 case TargetInfo::SignedLongLong: return LongLongTy;
4531 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4532 }
4533
4534 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004535 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004536}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004537
4538//===----------------------------------------------------------------------===//
4539// Type Predicates.
4540//===----------------------------------------------------------------------===//
4541
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004542/// isObjCNSObjectType - Return true if this is an NSObject object using
4543/// NSObject attribute on a c-style pointer type.
4544/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004545/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004546///
4547bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCallf4c73712011-01-19 06:33:43 +00004548 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004549 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004550 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004551 return true;
4552 }
Mike Stump1eb44332009-09-09 15:08:12 +00004553 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004554}
4555
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004556/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4557/// garbage collection attribute.
4558///
John McCallae278a32011-01-12 00:34:59 +00004559Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4560 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4561 return Qualifiers::GCNone;
4562
4563 assert(getLangOptions().ObjC1);
4564 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4565
4566 // Default behaviour under objective-C's gc is for ObjC pointers
4567 // (or pointers to them) be treated as though they were declared
4568 // as __strong.
4569 if (GCAttrs == Qualifiers::GCNone) {
4570 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4571 return Qualifiers::Strong;
4572 else if (Ty->isPointerType())
4573 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4574 } else {
4575 // It's not valid to set GC attributes on anything that isn't a
4576 // pointer.
4577#ifndef NDEBUG
4578 QualType CT = Ty->getCanonicalTypeInternal();
4579 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4580 CT = AT->getElementType();
4581 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4582#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004583 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004584 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004585}
4586
Chris Lattner6ac46a42008-04-07 06:51:04 +00004587//===----------------------------------------------------------------------===//
4588// Type Compatibility Testing
4589//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004590
Mike Stump1eb44332009-09-09 15:08:12 +00004591/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004592/// compatible.
4593static bool areCompatVectorTypes(const VectorType *LHS,
4594 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004595 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004596 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004597 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004598}
4599
Douglas Gregor255210e2010-08-06 10:14:59 +00004600bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4601 QualType SecondVec) {
4602 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4603 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4604
4605 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4606 return true;
4607
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004608 // Treat Neon vector types and most AltiVec vector types as if they are the
4609 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004610 const VectorType *First = FirstVec->getAs<VectorType>();
4611 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004612 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004613 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004614 First->getVectorKind() != VectorType::AltiVecPixel &&
4615 First->getVectorKind() != VectorType::AltiVecBool &&
4616 Second->getVectorKind() != VectorType::AltiVecPixel &&
4617 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004618 return true;
4619
4620 return false;
4621}
4622
Steve Naroff4084c302009-07-23 01:01:38 +00004623//===----------------------------------------------------------------------===//
4624// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4625//===----------------------------------------------------------------------===//
4626
4627/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4628/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00004629bool
4630ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4631 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00004632 if (lProto == rProto)
4633 return true;
4634 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4635 E = rProto->protocol_end(); PI != E; ++PI)
4636 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4637 return true;
4638 return false;
4639}
4640
Steve Naroff4084c302009-07-23 01:01:38 +00004641/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4642/// return true if lhs's protocols conform to rhs's protocol; false
4643/// otherwise.
4644bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4645 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4646 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4647 return false;
4648}
4649
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004650/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4651/// Class<p1, ...>.
4652bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4653 QualType rhs) {
4654 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4655 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4656 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4657
4658 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4659 E = lhsQID->qual_end(); I != E; ++I) {
4660 bool match = false;
4661 ObjCProtocolDecl *lhsProto = *I;
4662 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4663 E = rhsOPT->qual_end(); J != E; ++J) {
4664 ObjCProtocolDecl *rhsProto = *J;
4665 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4666 match = true;
4667 break;
4668 }
4669 }
4670 if (!match)
4671 return false;
4672 }
4673 return true;
4674}
4675
Steve Naroff4084c302009-07-23 01:01:38 +00004676/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4677/// ObjCQualifiedIDType.
4678bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4679 bool compare) {
4680 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004681 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004682 lhs->isObjCIdType() || lhs->isObjCClassType())
4683 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004684 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004685 rhs->isObjCIdType() || rhs->isObjCClassType())
4686 return true;
4687
4688 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004689 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004690
Steve Naroff4084c302009-07-23 01:01:38 +00004691 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004692
Steve Naroff4084c302009-07-23 01:01:38 +00004693 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004694 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004695 // make sure we check the class hierarchy.
4696 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4697 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4698 E = lhsQID->qual_end(); I != E; ++I) {
4699 // when comparing an id<P> on lhs with a static type on rhs,
4700 // see if static class implements all of id's protocols, directly or
4701 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004702 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004703 return false;
4704 }
4705 }
4706 // If there are no qualifiers and no interface, we have an 'id'.
4707 return true;
4708 }
Mike Stump1eb44332009-09-09 15:08:12 +00004709 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004710 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4711 E = lhsQID->qual_end(); I != E; ++I) {
4712 ObjCProtocolDecl *lhsProto = *I;
4713 bool match = false;
4714
4715 // when comparing an id<P> on lhs with a static type on rhs,
4716 // see if static class implements all of id's protocols, directly or
4717 // through its super class and categories.
4718 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4719 E = rhsOPT->qual_end(); J != E; ++J) {
4720 ObjCProtocolDecl *rhsProto = *J;
4721 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4722 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4723 match = true;
4724 break;
4725 }
4726 }
Mike Stump1eb44332009-09-09 15:08:12 +00004727 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004728 // make sure we check the class hierarchy.
4729 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4730 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4731 E = lhsQID->qual_end(); I != E; ++I) {
4732 // when comparing an id<P> on lhs with a static type on rhs,
4733 // see if static class implements all of id's protocols, directly or
4734 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004735 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004736 match = true;
4737 break;
4738 }
4739 }
4740 }
4741 if (!match)
4742 return false;
4743 }
Mike Stump1eb44332009-09-09 15:08:12 +00004744
Steve Naroff4084c302009-07-23 01:01:38 +00004745 return true;
4746 }
Mike Stump1eb44332009-09-09 15:08:12 +00004747
Steve Naroff4084c302009-07-23 01:01:38 +00004748 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4749 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4750
Mike Stump1eb44332009-09-09 15:08:12 +00004751 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004752 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004753 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004754 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4755 E = lhsOPT->qual_end(); I != E; ++I) {
4756 ObjCProtocolDecl *lhsProto = *I;
4757 bool match = false;
4758
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004759 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00004760 // see if static class implements all of id's protocols, directly or
4761 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004762 // First, lhs protocols in the qualifier list must be found, direct
4763 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00004764 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4765 E = rhsQID->qual_end(); J != E; ++J) {
4766 ObjCProtocolDecl *rhsProto = *J;
4767 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4768 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4769 match = true;
4770 break;
4771 }
4772 }
4773 if (!match)
4774 return false;
4775 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004776
4777 // Static class's protocols, or its super class or category protocols
4778 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4779 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4780 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4781 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4782 // This is rather dubious but matches gcc's behavior. If lhs has
4783 // no type qualifier and its class has no static protocol(s)
4784 // assume that it is mismatch.
4785 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4786 return false;
4787 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4788 LHSInheritedProtocols.begin(),
4789 E = LHSInheritedProtocols.end(); I != E; ++I) {
4790 bool match = false;
4791 ObjCProtocolDecl *lhsProto = (*I);
4792 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4793 E = rhsQID->qual_end(); J != E; ++J) {
4794 ObjCProtocolDecl *rhsProto = *J;
4795 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4796 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4797 match = true;
4798 break;
4799 }
4800 }
4801 if (!match)
4802 return false;
4803 }
4804 }
Steve Naroff4084c302009-07-23 01:01:38 +00004805 return true;
4806 }
4807 return false;
4808}
4809
Eli Friedman3d815e72008-08-22 00:56:42 +00004810/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004811/// compatible for assignment from RHS to LHS. This handles validation of any
4812/// protocol qualifiers on the LHS or RHS.
4813///
Steve Naroff14108da2009-07-10 23:34:53 +00004814bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4815 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004816 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4817 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4818
Steve Naroffde2e22d2009-07-15 18:40:39 +00004819 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004820 if (LHS->isObjCUnqualifiedIdOrClass() ||
4821 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004822 return true;
4823
John McCallc12c5bb2010-05-15 11:32:37 +00004824 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004825 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4826 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004827 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004828
4829 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4830 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4831 QualType(RHSOPT,0));
4832
John McCallc12c5bb2010-05-15 11:32:37 +00004833 // If we have 2 user-defined types, fall into that path.
4834 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004835 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004836
Steve Naroff4084c302009-07-23 01:01:38 +00004837 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004838}
4839
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004840/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4841/// for providing type-safty for objective-c pointers used to pass/return
4842/// arguments in block literals. When passed as arguments, passing 'A*' where
4843/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4844/// not OK. For the return type, the opposite is not OK.
4845bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4846 const ObjCObjectPointerType *LHSOPT,
4847 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004848 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004849 return true;
4850
4851 if (LHSOPT->isObjCBuiltinType()) {
4852 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4853 }
4854
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004855 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004856 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4857 QualType(RHSOPT,0),
4858 false);
4859
4860 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4861 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4862 if (LHS && RHS) { // We have 2 user-defined types.
4863 if (LHS != RHS) {
4864 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4865 return false;
4866 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4867 return true;
4868 }
4869 else
4870 return true;
4871 }
4872 return false;
4873}
4874
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004875/// getIntersectionOfProtocols - This routine finds the intersection of set
4876/// of protocols inherited from two distinct objective-c pointer objects.
4877/// It is used to build composite qualifier list of the composite type of
4878/// the conditional expression involving two objective-c pointer objects.
4879static
4880void getIntersectionOfProtocols(ASTContext &Context,
4881 const ObjCObjectPointerType *LHSOPT,
4882 const ObjCObjectPointerType *RHSOPT,
4883 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4884
John McCallc12c5bb2010-05-15 11:32:37 +00004885 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4886 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4887 assert(LHS->getInterface() && "LHS must have an interface base");
4888 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004889
4890 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4891 unsigned LHSNumProtocols = LHS->getNumProtocols();
4892 if (LHSNumProtocols > 0)
4893 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4894 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004895 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004896 Context.CollectInheritedProtocols(LHS->getInterface(),
4897 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004898 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4899 LHSInheritedProtocols.end());
4900 }
4901
4902 unsigned RHSNumProtocols = RHS->getNumProtocols();
4903 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004904 ObjCProtocolDecl **RHSProtocols =
4905 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004906 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4907 if (InheritedProtocolSet.count(RHSProtocols[i]))
4908 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4909 }
4910 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004911 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004912 Context.CollectInheritedProtocols(RHS->getInterface(),
4913 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004914 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4915 RHSInheritedProtocols.begin(),
4916 E = RHSInheritedProtocols.end(); I != E; ++I)
4917 if (InheritedProtocolSet.count((*I)))
4918 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004919 }
4920}
4921
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004922/// areCommonBaseCompatible - Returns common base class of the two classes if
4923/// one found. Note that this is O'2 algorithm. But it will be called as the
4924/// last type comparison in a ?-exp of ObjC pointer types before a
4925/// warning is issued. So, its invokation is extremely rare.
4926QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004927 const ObjCObjectPointerType *Lptr,
4928 const ObjCObjectPointerType *Rptr) {
4929 const ObjCObjectType *LHS = Lptr->getObjectType();
4930 const ObjCObjectType *RHS = Rptr->getObjectType();
4931 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4932 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4933 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004934 return QualType();
4935
John McCallc12c5bb2010-05-15 11:32:37 +00004936 while ((LDecl = LDecl->getSuperClass())) {
4937 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004938 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004939 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4940 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4941
4942 QualType Result = QualType(LHS, 0);
4943 if (!Protocols.empty())
4944 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4945 Result = getObjCObjectPointerType(Result);
4946 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004947 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004948 }
4949
4950 return QualType();
4951}
4952
John McCallc12c5bb2010-05-15 11:32:37 +00004953bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4954 const ObjCObjectType *RHS) {
4955 assert(LHS->getInterface() && "LHS is not an interface type");
4956 assert(RHS->getInterface() && "RHS is not an interface type");
4957
Chris Lattner6ac46a42008-04-07 06:51:04 +00004958 // Verify that the base decls are compatible: the RHS must be a subclass of
4959 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004960 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004961 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004962
Chris Lattner6ac46a42008-04-07 06:51:04 +00004963 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4964 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004965 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004966 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004967
Chris Lattner6ac46a42008-04-07 06:51:04 +00004968 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4969 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004970 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004971 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004972
John McCallc12c5bb2010-05-15 11:32:37 +00004973 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4974 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004975 LHSPI != LHSPE; LHSPI++) {
4976 bool RHSImplementsProtocol = false;
4977
4978 // If the RHS doesn't implement the protocol on the left, the types
4979 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004980 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4981 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004982 RHSPI != RHSPE; RHSPI++) {
4983 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004984 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004985 break;
4986 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004987 }
4988 // FIXME: For better diagnostics, consider passing back the protocol name.
4989 if (!RHSImplementsProtocol)
4990 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004991 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004992 // The RHS implements all protocols listed on the LHS.
4993 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004994}
4995
Steve Naroff389bf462009-02-12 17:52:19 +00004996bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4997 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004998 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4999 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005000
Steve Naroff14108da2009-07-10 23:34:53 +00005001 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005002 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005003
5004 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5005 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005006}
5007
Douglas Gregor569c3162010-08-07 11:51:51 +00005008bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5009 return canAssignObjCInterfaces(
5010 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5011 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5012}
5013
Mike Stump1eb44332009-09-09 15:08:12 +00005014/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005015/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005016/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005017/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005018bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5019 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005020 if (getLangOptions().CPlusPlus)
5021 return hasSameType(LHS, RHS);
5022
Douglas Gregor447234d2010-07-29 15:18:02 +00005023 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005024}
5025
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005026bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5027 return !mergeTypes(LHS, RHS, true).isNull();
5028}
5029
Peter Collingbourne48466752010-10-24 18:30:18 +00005030/// mergeTransparentUnionType - if T is a transparent union type and a member
5031/// of T is compatible with SubType, return the merged type, else return
5032/// QualType()
5033QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5034 bool OfBlockPointer,
5035 bool Unqualified) {
5036 if (const RecordType *UT = T->getAsUnionType()) {
5037 RecordDecl *UD = UT->getDecl();
5038 if (UD->hasAttr<TransparentUnionAttr>()) {
5039 for (RecordDecl::field_iterator it = UD->field_begin(),
5040 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005041 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005042 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5043 if (!MT.isNull())
5044 return MT;
5045 }
5046 }
5047 }
5048
5049 return QualType();
5050}
5051
5052/// mergeFunctionArgumentTypes - merge two types which appear as function
5053/// argument types
5054QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5055 bool OfBlockPointer,
5056 bool Unqualified) {
5057 // GNU extension: two types are compatible if they appear as a function
5058 // argument, one of the types is a transparent union type and the other
5059 // type is compatible with a union member
5060 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5061 Unqualified);
5062 if (!lmerge.isNull())
5063 return lmerge;
5064
5065 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5066 Unqualified);
5067 if (!rmerge.isNull())
5068 return rmerge;
5069
5070 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5071}
5072
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005073QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005074 bool OfBlockPointer,
5075 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005076 const FunctionType *lbase = lhs->getAs<FunctionType>();
5077 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005078 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5079 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005080 bool allLTypes = true;
5081 bool allRTypes = true;
5082
5083 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005084 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005085 if (OfBlockPointer) {
5086 QualType RHS = rbase->getResultType();
5087 QualType LHS = lbase->getResultType();
5088 bool UnqualifiedResult = Unqualified;
5089 if (!UnqualifiedResult)
5090 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
5091 retType = mergeTypes(RHS, LHS, true, UnqualifiedResult);
5092 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005093 else
John McCall8cc246c2010-12-15 01:06:38 +00005094 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5095 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005096 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005097
5098 if (Unqualified)
5099 retType = retType.getUnqualifiedType();
5100
5101 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5102 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5103 if (Unqualified) {
5104 LRetType = LRetType.getUnqualifiedType();
5105 RRetType = RRetType.getUnqualifiedType();
5106 }
5107
5108 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005109 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005110 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005111 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005112
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005113 // FIXME: double check this
5114 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5115 // rbase->getRegParmAttr() != 0 &&
5116 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005117 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5118 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005119
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005120 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005121 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005122 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005123
John McCall8cc246c2010-12-15 01:06:38 +00005124 // Regparm is part of the calling convention.
5125 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5126 return QualType();
5127
5128 // It's noreturn if either type is.
5129 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5130 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5131 if (NoReturn != lbaseInfo.getNoReturn())
5132 allLTypes = false;
5133 if (NoReturn != rbaseInfo.getNoReturn())
5134 allRTypes = false;
5135
5136 FunctionType::ExtInfo einfo(NoReturn,
5137 lbaseInfo.getRegParm(),
5138 lbaseInfo.getCC());
John McCalle23cf432010-12-14 08:05:40 +00005139
Eli Friedman3d815e72008-08-22 00:56:42 +00005140 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005141 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5142 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005143 unsigned lproto_nargs = lproto->getNumArgs();
5144 unsigned rproto_nargs = rproto->getNumArgs();
5145
5146 // Compatible functions must have the same number of arguments
5147 if (lproto_nargs != rproto_nargs)
5148 return QualType();
5149
5150 // Variadic and non-variadic functions aren't compatible
5151 if (lproto->isVariadic() != rproto->isVariadic())
5152 return QualType();
5153
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005154 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5155 return QualType();
5156
Eli Friedman3d815e72008-08-22 00:56:42 +00005157 // Check argument compatibility
5158 llvm::SmallVector<QualType, 10> types;
5159 for (unsigned i = 0; i < lproto_nargs; i++) {
5160 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5161 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005162 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5163 OfBlockPointer,
5164 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005165 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005166
5167 if (Unqualified)
5168 argtype = argtype.getUnqualifiedType();
5169
Eli Friedman3d815e72008-08-22 00:56:42 +00005170 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005171 if (Unqualified) {
5172 largtype = largtype.getUnqualifiedType();
5173 rargtype = rargtype.getUnqualifiedType();
5174 }
5175
Chris Lattner61710852008-10-05 17:34:18 +00005176 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5177 allLTypes = false;
5178 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5179 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005180 }
5181 if (allLTypes) return lhs;
5182 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005183
5184 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5185 EPI.ExtInfo = einfo;
5186 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005187 }
5188
5189 if (lproto) allRTypes = false;
5190 if (rproto) allLTypes = false;
5191
Douglas Gregor72564e72009-02-26 23:50:07 +00005192 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005193 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005194 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005195 if (proto->isVariadic()) return QualType();
5196 // Check that the types are compatible with the types that
5197 // would result from default argument promotions (C99 6.7.5.3p15).
5198 // The only types actually affected are promotable integer
5199 // types and floats, which would be passed as a different
5200 // type depending on whether the prototype is visible.
5201 unsigned proto_nargs = proto->getNumArgs();
5202 for (unsigned i = 0; i < proto_nargs; ++i) {
5203 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005204
5205 // Look at the promotion type of enum types, since that is the type used
5206 // to pass enum values.
5207 if (const EnumType *Enum = argTy->getAs<EnumType>())
5208 argTy = Enum->getDecl()->getPromotionType();
5209
Eli Friedman3d815e72008-08-22 00:56:42 +00005210 if (argTy->isPromotableIntegerType() ||
5211 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5212 return QualType();
5213 }
5214
5215 if (allLTypes) return lhs;
5216 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005217
5218 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5219 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005220 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005221 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005222 }
5223
5224 if (allLTypes) return lhs;
5225 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005226 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005227}
5228
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005229QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005230 bool OfBlockPointer,
5231 bool Unqualified) {
Bill Wendling43d69752007-12-03 07:33:35 +00005232 // C++ [expr]: If an expression initially has the type "reference to T", the
5233 // type is adjusted to "T" prior to any further analysis, the expression
5234 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005235 // expression is an lvalue unless the reference is an rvalue reference and
5236 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005237 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5238 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005239
5240 if (Unqualified) {
5241 LHS = LHS.getUnqualifiedType();
5242 RHS = RHS.getUnqualifiedType();
5243 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005244
Eli Friedman3d815e72008-08-22 00:56:42 +00005245 QualType LHSCan = getCanonicalType(LHS),
5246 RHSCan = getCanonicalType(RHS);
5247
5248 // If two types are identical, they are compatible.
5249 if (LHSCan == RHSCan)
5250 return LHS;
5251
John McCall0953e762009-09-24 19:53:00 +00005252 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005253 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5254 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005255 if (LQuals != RQuals) {
5256 // If any of these qualifiers are different, we have a type
5257 // mismatch.
5258 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5259 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5260 return QualType();
5261
5262 // Exactly one GC qualifier difference is allowed: __strong is
5263 // okay if the other type has no GC qualifier but is an Objective
5264 // C object pointer (i.e. implicitly strong by default). We fix
5265 // this by pretending that the unqualified type was actually
5266 // qualified __strong.
5267 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5268 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5269 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5270
5271 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5272 return QualType();
5273
5274 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5275 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5276 }
5277 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5278 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5279 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005280 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005281 }
5282
5283 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005284
Eli Friedman852d63b2009-06-01 01:22:52 +00005285 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5286 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005287
Chris Lattner1adb8832008-01-14 05:45:46 +00005288 // We want to consider the two function types to be the same for these
5289 // comparisons, just force one to the other.
5290 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5291 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005292
5293 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005294 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5295 LHSClass = Type::ConstantArray;
5296 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5297 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005298
John McCallc12c5bb2010-05-15 11:32:37 +00005299 // ObjCInterfaces are just specialized ObjCObjects.
5300 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5301 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5302
Nate Begeman213541a2008-04-18 23:10:10 +00005303 // Canonicalize ExtVector -> Vector.
5304 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5305 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005306
Chris Lattnera36a61f2008-04-07 05:43:21 +00005307 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005308 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005309 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005310 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005311 // Compatibility is based on the underlying type, not the promotion
5312 // type.
John McCall183700f2009-09-21 23:43:11 +00005313 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005314 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5315 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005316 }
John McCall183700f2009-09-21 23:43:11 +00005317 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005318 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5319 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005320 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005321
Eli Friedman3d815e72008-08-22 00:56:42 +00005322 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005323 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005324
Steve Naroff4a746782008-01-09 22:43:08 +00005325 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005326 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005327#define TYPE(Class, Base)
5328#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005329#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005330#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5331#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5332#include "clang/AST/TypeNodes.def"
5333 assert(false && "Non-canonical and dependent types shouldn't get here");
5334 return QualType();
5335
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005336 case Type::LValueReference:
5337 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005338 case Type::MemberPointer:
5339 assert(false && "C++ should never be in mergeTypes");
5340 return QualType();
5341
John McCallc12c5bb2010-05-15 11:32:37 +00005342 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005343 case Type::IncompleteArray:
5344 case Type::VariableArray:
5345 case Type::FunctionProto:
5346 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005347 assert(false && "Types are eliminated above");
5348 return QualType();
5349
Chris Lattner1adb8832008-01-14 05:45:46 +00005350 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005351 {
5352 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005353 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5354 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005355 if (Unqualified) {
5356 LHSPointee = LHSPointee.getUnqualifiedType();
5357 RHSPointee = RHSPointee.getUnqualifiedType();
5358 }
5359 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5360 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005361 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005362 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005363 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005364 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005365 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005366 return getPointerType(ResultType);
5367 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005368 case Type::BlockPointer:
5369 {
5370 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005371 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5372 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005373 if (Unqualified) {
5374 LHSPointee = LHSPointee.getUnqualifiedType();
5375 RHSPointee = RHSPointee.getUnqualifiedType();
5376 }
5377 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5378 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005379 if (ResultType.isNull()) return QualType();
5380 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5381 return LHS;
5382 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5383 return RHS;
5384 return getBlockPointerType(ResultType);
5385 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005386 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005387 {
5388 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5389 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5390 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5391 return QualType();
5392
5393 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5394 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005395 if (Unqualified) {
5396 LHSElem = LHSElem.getUnqualifiedType();
5397 RHSElem = RHSElem.getUnqualifiedType();
5398 }
5399
5400 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005401 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005402 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5403 return LHS;
5404 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5405 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005406 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5407 ArrayType::ArraySizeModifier(), 0);
5408 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5409 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005410 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5411 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005412 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5413 return LHS;
5414 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5415 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005416 if (LVAT) {
5417 // FIXME: This isn't correct! But tricky to implement because
5418 // the array's size has to be the size of LHS, but the type
5419 // has to be different.
5420 return LHS;
5421 }
5422 if (RVAT) {
5423 // FIXME: This isn't correct! But tricky to implement because
5424 // the array's size has to be the size of RHS, but the type
5425 // has to be different.
5426 return RHS;
5427 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005428 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5429 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005430 return getIncompleteArrayType(ResultType,
5431 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005432 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005433 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005434 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005435 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005436 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005437 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005438 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005439 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005440 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005441 case Type::Complex:
5442 // Distinct complex types are incompatible.
5443 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005444 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005445 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005446 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5447 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005448 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005449 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005450 case Type::ObjCObject: {
5451 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005452 // FIXME: This should be type compatibility, e.g. whether
5453 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005454 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5455 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5456 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005457 return LHS;
5458
Eli Friedman3d815e72008-08-22 00:56:42 +00005459 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005460 }
Steve Naroff14108da2009-07-10 23:34:53 +00005461 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005462 if (OfBlockPointer) {
5463 if (canAssignObjCInterfacesInBlockPointer(
5464 LHS->getAs<ObjCObjectPointerType>(),
5465 RHS->getAs<ObjCObjectPointerType>()))
5466 return LHS;
5467 return QualType();
5468 }
John McCall183700f2009-09-21 23:43:11 +00005469 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5470 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005471 return LHS;
5472
Steve Naroffbc76dd02008-12-10 22:14:21 +00005473 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005474 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005475 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005476
5477 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005478}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005479
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005480/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5481/// 'RHS' attributes and returns the merged version; including for function
5482/// return types.
5483QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5484 QualType LHSCan = getCanonicalType(LHS),
5485 RHSCan = getCanonicalType(RHS);
5486 // If two types are identical, they are compatible.
5487 if (LHSCan == RHSCan)
5488 return LHS;
5489 if (RHSCan->isFunctionType()) {
5490 if (!LHSCan->isFunctionType())
5491 return QualType();
5492 QualType OldReturnType =
5493 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5494 QualType NewReturnType =
5495 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5496 QualType ResReturnType =
5497 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5498 if (ResReturnType.isNull())
5499 return QualType();
5500 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5501 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5502 // In either case, use OldReturnType to build the new function type.
5503 const FunctionType *F = LHS->getAs<FunctionType>();
5504 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005505 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5506 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005507 QualType ResultType
5508 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005509 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005510 return ResultType;
5511 }
5512 }
5513 return QualType();
5514 }
5515
5516 // If the qualifiers are different, the types can still be merged.
5517 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5518 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5519 if (LQuals != RQuals) {
5520 // If any of these qualifiers are different, we have a type mismatch.
5521 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5522 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5523 return QualType();
5524
5525 // Exactly one GC qualifier difference is allowed: __strong is
5526 // okay if the other type has no GC qualifier but is an Objective
5527 // C object pointer (i.e. implicitly strong by default). We fix
5528 // this by pretending that the unqualified type was actually
5529 // qualified __strong.
5530 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5531 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5532 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5533
5534 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5535 return QualType();
5536
5537 if (GC_L == Qualifiers::Strong)
5538 return LHS;
5539 if (GC_R == Qualifiers::Strong)
5540 return RHS;
5541 return QualType();
5542 }
5543
5544 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5545 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5546 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5547 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5548 if (ResQT == LHSBaseQT)
5549 return LHS;
5550 if (ResQT == RHSBaseQT)
5551 return RHS;
5552 }
5553 return QualType();
5554}
5555
Chris Lattner5426bf62008-04-07 07:01:58 +00005556//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005557// Integer Predicates
5558//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005559
Jay Foad4ba2a172011-01-12 09:06:06 +00005560unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00005561 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005562 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005563 if (T->isBooleanType())
5564 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005565 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005566 return (unsigned)getTypeSize(T);
5567}
5568
5569QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005570 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005571
5572 // Turn <4 x signed int> -> <4 x unsigned int>
5573 if (const VectorType *VTy = T->getAs<VectorType>())
5574 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005575 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005576
5577 // For enums, we return the unsigned version of the base type.
5578 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005579 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005580
5581 const BuiltinType *BTy = T->getAs<BuiltinType>();
5582 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005583 switch (BTy->getKind()) {
5584 case BuiltinType::Char_S:
5585 case BuiltinType::SChar:
5586 return UnsignedCharTy;
5587 case BuiltinType::Short:
5588 return UnsignedShortTy;
5589 case BuiltinType::Int:
5590 return UnsignedIntTy;
5591 case BuiltinType::Long:
5592 return UnsignedLongTy;
5593 case BuiltinType::LongLong:
5594 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005595 case BuiltinType::Int128:
5596 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005597 default:
5598 assert(0 && "Unexpected signed integer type");
5599 return QualType();
5600 }
5601}
5602
Douglas Gregor2cf26342009-04-09 22:27:44 +00005603ExternalASTSource::~ExternalASTSource() { }
5604
5605void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005606
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005607ASTMutationListener::~ASTMutationListener() { }
5608
Chris Lattner86df27b2009-06-14 00:45:47 +00005609
5610//===----------------------------------------------------------------------===//
5611// Builtin Type Computation
5612//===----------------------------------------------------------------------===//
5613
5614/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00005615/// pointer over the consumed characters. This returns the resultant type. If
5616/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5617/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5618/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00005619///
5620/// RequiresICE is filled in on return to indicate whether the value is required
5621/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00005622static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005623 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00005624 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00005625 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005626 // Modifiers.
5627 int HowLong = 0;
5628 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00005629 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005630
Chris Lattner33daae62010-10-01 22:42:38 +00005631 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00005632 bool Done = false;
5633 while (!Done) {
5634 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005635 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005636 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00005637 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005638 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005639 case 'S':
5640 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5641 assert(!Signed && "Can't use 'S' modifier multiple times!");
5642 Signed = true;
5643 break;
5644 case 'U':
5645 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5646 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5647 Unsigned = true;
5648 break;
5649 case 'L':
5650 assert(HowLong <= 2 && "Can't have LLLL modifier");
5651 ++HowLong;
5652 break;
5653 }
5654 }
5655
5656 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005657
Chris Lattner86df27b2009-06-14 00:45:47 +00005658 // Read the base type.
5659 switch (*Str++) {
5660 default: assert(0 && "Unknown builtin type letter!");
5661 case 'v':
5662 assert(HowLong == 0 && !Signed && !Unsigned &&
5663 "Bad modifiers used with 'v'!");
5664 Type = Context.VoidTy;
5665 break;
5666 case 'f':
5667 assert(HowLong == 0 && !Signed && !Unsigned &&
5668 "Bad modifiers used with 'f'!");
5669 Type = Context.FloatTy;
5670 break;
5671 case 'd':
5672 assert(HowLong < 2 && !Signed && !Unsigned &&
5673 "Bad modifiers used with 'd'!");
5674 if (HowLong)
5675 Type = Context.LongDoubleTy;
5676 else
5677 Type = Context.DoubleTy;
5678 break;
5679 case 's':
5680 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5681 if (Unsigned)
5682 Type = Context.UnsignedShortTy;
5683 else
5684 Type = Context.ShortTy;
5685 break;
5686 case 'i':
5687 if (HowLong == 3)
5688 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5689 else if (HowLong == 2)
5690 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5691 else if (HowLong == 1)
5692 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5693 else
5694 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5695 break;
5696 case 'c':
5697 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5698 if (Signed)
5699 Type = Context.SignedCharTy;
5700 else if (Unsigned)
5701 Type = Context.UnsignedCharTy;
5702 else
5703 Type = Context.CharTy;
5704 break;
5705 case 'b': // boolean
5706 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5707 Type = Context.BoolTy;
5708 break;
5709 case 'z': // size_t.
5710 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5711 Type = Context.getSizeType();
5712 break;
5713 case 'F':
5714 Type = Context.getCFConstantStringType();
5715 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00005716 case 'G':
5717 Type = Context.getObjCIdType();
5718 break;
5719 case 'H':
5720 Type = Context.getObjCSelType();
5721 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005722 case 'a':
5723 Type = Context.getBuiltinVaListType();
5724 assert(!Type.isNull() && "builtin va list type not initialized!");
5725 break;
5726 case 'A':
5727 // This is a "reference" to a va_list; however, what exactly
5728 // this means depends on how va_list is defined. There are two
5729 // different kinds of va_list: ones passed by value, and ones
5730 // passed by reference. An example of a by-value va_list is
5731 // x86, where va_list is a char*. An example of by-ref va_list
5732 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5733 // we want this argument to be a char*&; for x86-64, we want
5734 // it to be a __va_list_tag*.
5735 Type = Context.getBuiltinVaListType();
5736 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00005737 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00005738 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00005739 else
Chris Lattner86df27b2009-06-14 00:45:47 +00005740 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005741 break;
5742 case 'V': {
5743 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005744 unsigned NumElements = strtoul(Str, &End, 10);
5745 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00005746 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005747
Chris Lattner14e0e742010-10-01 22:53:11 +00005748 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5749 RequiresICE, false);
5750 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00005751
5752 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005753 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00005754 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00005755 break;
5756 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005757 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00005758 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5759 false);
5760 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00005761 Type = Context.getComplexType(ElementType);
5762 break;
5763 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005764 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005765 Type = Context.getFILEType();
5766 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005767 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005768 return QualType();
5769 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005770 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005771 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005772 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005773 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005774 else
5775 Type = Context.getjmp_bufType();
5776
Mike Stumpfd612db2009-07-28 23:47:15 +00005777 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005778 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005779 return QualType();
5780 }
5781 break;
Mike Stump782fa302009-07-28 02:25:19 +00005782 }
Mike Stump1eb44332009-09-09 15:08:12 +00005783
Chris Lattner33daae62010-10-01 22:42:38 +00005784 // If there are modifiers and if we're allowed to parse them, go for it.
5785 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00005786 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005787 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00005788 default: Done = true; --Str; break;
5789 case '*':
5790 case '&': {
5791 // Both pointers and references can have their pointee types
5792 // qualified with an address space.
5793 char *End;
5794 unsigned AddrSpace = strtoul(Str, &End, 10);
5795 if (End != Str && AddrSpace != 0) {
5796 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5797 Str = End;
5798 }
5799 if (c == '*')
5800 Type = Context.getPointerType(Type);
5801 else
5802 Type = Context.getLValueReferenceType(Type);
5803 break;
5804 }
5805 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5806 case 'C':
5807 Type = Type.withConst();
5808 break;
5809 case 'D':
5810 Type = Context.getVolatileType(Type);
5811 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005812 }
5813 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00005814
Chris Lattner14e0e742010-10-01 22:53:11 +00005815 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00005816 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00005817
Chris Lattner86df27b2009-06-14 00:45:47 +00005818 return Type;
5819}
5820
5821/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00005822QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00005823 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00005824 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00005825 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00005826
Chris Lattner86df27b2009-06-14 00:45:47 +00005827 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005828
Chris Lattner14e0e742010-10-01 22:53:11 +00005829 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00005830 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00005831 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5832 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005833 if (Error != GE_None)
5834 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00005835
5836 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5837
Chris Lattner86df27b2009-06-14 00:45:47 +00005838 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00005839 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005840 if (Error != GE_None)
5841 return QualType();
5842
Chris Lattner14e0e742010-10-01 22:53:11 +00005843 // If this argument is required to be an IntegerConstantExpression and the
5844 // caller cares, fill in the bitmask we return.
5845 if (RequiresICE && IntegerConstantArgs)
5846 *IntegerConstantArgs |= 1 << ArgTypes.size();
5847
Chris Lattner86df27b2009-06-14 00:45:47 +00005848 // Do array -> pointer decay. The builtin should use the decayed type.
5849 if (Ty->isArrayType())
5850 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005851
Chris Lattner86df27b2009-06-14 00:45:47 +00005852 ArgTypes.push_back(Ty);
5853 }
5854
5855 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5856 "'.' should only occur at end of builtin type list!");
5857
John McCall00ccbef2010-12-21 00:44:39 +00005858 FunctionType::ExtInfo EI;
5859 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5860
5861 bool Variadic = (TypeStr[0] == '.');
5862
5863 // We really shouldn't be making a no-proto type here, especially in C++.
5864 if (ArgTypes.empty() && Variadic)
5865 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005866
John McCalle23cf432010-12-14 08:05:40 +00005867 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00005868 EPI.ExtInfo = EI;
5869 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00005870
5871 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00005872}
Eli Friedmana95d7572009-08-19 07:44:53 +00005873
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005874GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5875 GVALinkage External = GVA_StrongExternal;
5876
5877 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005878 switch (L) {
5879 case NoLinkage:
5880 case InternalLinkage:
5881 case UniqueExternalLinkage:
5882 return GVA_Internal;
5883
5884 case ExternalLinkage:
5885 switch (FD->getTemplateSpecializationKind()) {
5886 case TSK_Undeclared:
5887 case TSK_ExplicitSpecialization:
5888 External = GVA_StrongExternal;
5889 break;
5890
5891 case TSK_ExplicitInstantiationDefinition:
5892 return GVA_ExplicitTemplateInstantiation;
5893
5894 case TSK_ExplicitInstantiationDeclaration:
5895 case TSK_ImplicitInstantiation:
5896 External = GVA_TemplateInstantiation;
5897 break;
5898 }
5899 }
5900
5901 if (!FD->isInlined())
5902 return External;
5903
5904 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5905 // GNU or C99 inline semantics. Determine whether this symbol should be
5906 // externally visible.
5907 if (FD->isInlineDefinitionExternallyVisible())
5908 return External;
5909
5910 // C99 inline semantics, where the symbol is not externally visible.
5911 return GVA_C99Inline;
5912 }
5913
5914 // C++0x [temp.explicit]p9:
5915 // [ Note: The intent is that an inline function that is the subject of
5916 // an explicit instantiation declaration will still be implicitly
5917 // instantiated when used so that the body can be considered for
5918 // inlining, but that no out-of-line copy of the inline function would be
5919 // generated in the translation unit. -- end note ]
5920 if (FD->getTemplateSpecializationKind()
5921 == TSK_ExplicitInstantiationDeclaration)
5922 return GVA_C99Inline;
5923
5924 return GVA_CXXInline;
5925}
5926
5927GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5928 // If this is a static data member, compute the kind of template
5929 // specialization. Otherwise, this variable is not part of a
5930 // template.
5931 TemplateSpecializationKind TSK = TSK_Undeclared;
5932 if (VD->isStaticDataMember())
5933 TSK = VD->getTemplateSpecializationKind();
5934
5935 Linkage L = VD->getLinkage();
5936 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5937 VD->getType()->getLinkage() == UniqueExternalLinkage)
5938 L = UniqueExternalLinkage;
5939
5940 switch (L) {
5941 case NoLinkage:
5942 case InternalLinkage:
5943 case UniqueExternalLinkage:
5944 return GVA_Internal;
5945
5946 case ExternalLinkage:
5947 switch (TSK) {
5948 case TSK_Undeclared:
5949 case TSK_ExplicitSpecialization:
5950 return GVA_StrongExternal;
5951
5952 case TSK_ExplicitInstantiationDeclaration:
5953 llvm_unreachable("Variable should not be instantiated");
5954 // Fall through to treat this like any other instantiation.
5955
5956 case TSK_ExplicitInstantiationDefinition:
5957 return GVA_ExplicitTemplateInstantiation;
5958
5959 case TSK_ImplicitInstantiation:
5960 return GVA_TemplateInstantiation;
5961 }
5962 }
5963
5964 return GVA_StrongExternal;
5965}
5966
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00005967bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005968 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5969 if (!VD->isFileVarDecl())
5970 return false;
5971 } else if (!isa<FunctionDecl>(D))
5972 return false;
5973
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005974 // Weak references don't produce any output by themselves.
5975 if (D->hasAttr<WeakRefAttr>())
5976 return false;
5977
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005978 // Aliases and used decls are required.
5979 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5980 return true;
5981
5982 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5983 // Forward declarations aren't required.
5984 if (!FD->isThisDeclarationADefinition())
5985 return false;
5986
5987 // Constructors and destructors are required.
5988 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5989 return true;
5990
5991 // The key function for a class is required.
5992 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5993 const CXXRecordDecl *RD = MD->getParent();
5994 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5995 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5996 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5997 return true;
5998 }
5999 }
6000
6001 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6002
6003 // static, static inline, always_inline, and extern inline functions can
6004 // always be deferred. Normal inline functions can be deferred in C99/C++.
6005 // Implicit template instantiations can also be deferred in C++.
6006 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6007 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6008 return false;
6009 return true;
6010 }
6011
6012 const VarDecl *VD = cast<VarDecl>(D);
6013 assert(VD->isFileVarDecl() && "Expected file scoped var");
6014
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006015 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6016 return false;
6017
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006018 // Structs that have non-trivial constructors or destructors are required.
6019
6020 // FIXME: Handle references.
6021 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6022 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00006023 if (RD->hasDefinition() &&
6024 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006025 return true;
6026 }
6027 }
6028
6029 GVALinkage L = GetGVALinkageForVariable(VD);
6030 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6031 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6032 return false;
6033 }
6034
6035 return true;
6036}
Charles Davis071cc7d2010-08-16 03:33:14 +00006037
Charles Davisee743f92010-11-09 18:04:24 +00006038CallingConv ASTContext::getDefaultMethodCallConv() {
6039 // Pass through to the C++ ABI object
6040 return ABI->getDefaultMethodCallConv();
6041}
6042
Jay Foad4ba2a172011-01-12 09:06:06 +00006043bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006044 // Pass through to the C++ ABI object
6045 return ABI->isNearlyEmpty(RD);
6046}
6047
Peter Collingbourne14110472011-01-13 18:57:25 +00006048MangleContext *ASTContext::createMangleContext() {
6049 switch (Target.getCXXABI()) {
6050 case CXXABI_ARM:
6051 case CXXABI_Itanium:
6052 return createItaniumMangleContext(*this, getDiagnostics());
6053 case CXXABI_Microsoft:
6054 return createMicrosoftMangleContext(*this, getDiagnostics());
6055 }
6056 assert(0 && "Unsupported ABI");
6057 return 0;
6058}
6059
Charles Davis071cc7d2010-08-16 03:33:14 +00006060CXXABI::~CXXABI() {}