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