blob: eaf222cafad80e70b5b2a4e4b584db0bc291291a [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"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000026#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000028#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000029#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000030#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000031#include "llvm/Support/raw_ostream.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000032#include "CXXABI.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000033
Reid Spencer5f016e22007-07-11 17:01:13 +000034using namespace clang;
35
Douglas Gregor18274032010-07-03 00:47:00 +000036unsigned ASTContext::NumImplicitDefaultConstructors;
37unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000038unsigned ASTContext::NumImplicitCopyConstructors;
39unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000040unsigned ASTContext::NumImplicitCopyAssignmentOperators;
41unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000042unsigned ASTContext::NumImplicitDestructors;
43unsigned ASTContext::NumImplicitDestructorsDeclared;
44
Reid Spencer5f016e22007-07-11 17:01:13 +000045enum FloatingRank {
46 FloatRank, DoubleRank, LongDoubleRank
47};
48
Douglas Gregor3e1274f2010-06-16 21:09:37 +000049void
50ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
51 TemplateTemplateParmDecl *Parm) {
52 ID.AddInteger(Parm->getDepth());
53 ID.AddInteger(Parm->getPosition());
54 // FIXME: Parameter pack
55
56 TemplateParameterList *Params = Parm->getTemplateParameters();
57 ID.AddInteger(Params->size());
58 for (TemplateParameterList::const_iterator P = Params->begin(),
59 PEnd = Params->end();
60 P != PEnd; ++P) {
61 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
62 ID.AddInteger(0);
63 ID.AddBoolean(TTP->isParameterPack());
64 continue;
65 }
66
67 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
68 ID.AddInteger(1);
69 // FIXME: Parameter pack
70 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
71 continue;
72 }
73
74 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
75 ID.AddInteger(2);
76 Profile(ID, TTP);
77 }
78}
79
80TemplateTemplateParmDecl *
81ASTContext::getCanonicalTemplateTemplateParmDecl(
82 TemplateTemplateParmDecl *TTP) {
83 // Check if we already have a canonical template template parameter.
84 llvm::FoldingSetNodeID ID;
85 CanonicalTemplateTemplateParm::Profile(ID, TTP);
86 void *InsertPos = 0;
87 CanonicalTemplateTemplateParm *Canonical
88 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
89 if (Canonical)
90 return Canonical->getParam();
91
92 // Build a canonical template parameter list.
93 TemplateParameterList *Params = TTP->getTemplateParameters();
94 llvm::SmallVector<NamedDecl *, 4> CanonParams;
95 CanonParams.reserve(Params->size());
96 for (TemplateParameterList::const_iterator P = Params->begin(),
97 PEnd = Params->end();
98 P != PEnd; ++P) {
99 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
100 CanonParams.push_back(
101 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
102 SourceLocation(), TTP->getDepth(),
103 TTP->getIndex(), 0, false,
104 TTP->isParameterPack()));
105 else if (NonTypeTemplateParmDecl *NTTP
106 = dyn_cast<NonTypeTemplateParmDecl>(*P))
107 CanonParams.push_back(
108 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
109 SourceLocation(), NTTP->getDepth(),
110 NTTP->getPosition(), 0,
111 getCanonicalType(NTTP->getType()),
Douglas Gregor10738d32010-12-23 23:51:58 +0000112 NTTP->isParameterPack(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000113 0));
114 else
115 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
116 cast<TemplateTemplateParmDecl>(*P)));
117 }
118
119 TemplateTemplateParmDecl *CanonTTP
120 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
121 SourceLocation(), TTP->getDepth(),
122 TTP->getPosition(), 0,
123 TemplateParameterList::Create(*this, SourceLocation(),
124 SourceLocation(),
125 CanonParams.data(),
126 CanonParams.size(),
127 SourceLocation()));
128
129 // Get the new insert position for the node we care about.
130 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
131 assert(Canonical == 0 && "Shouldn't be in the map!");
132 (void)Canonical;
133
134 // Create the canonical template template parameter entry.
135 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
136 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
137 return CanonTTP;
138}
139
Charles Davis071cc7d2010-08-16 03:33:14 +0000140CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000141 if (!LangOpts.CPlusPlus) return 0;
142
Charles Davis20cf7172010-08-19 02:18:14 +0000143 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000144 case CXXABI_ARM:
145 return CreateARMCXXABI(*this);
146 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000147 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000148 case CXXABI_Microsoft:
149 return CreateMicrosoftCXXABI(*this);
150 }
John McCallee79a4c2010-08-21 22:46:04 +0000151 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000152}
153
Chris Lattner61710852008-10-05 17:34:18 +0000154ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000155 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000156 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000157 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000158 unsigned size_reserve) :
John McCallef990012010-06-11 11:07:21 +0000159 TemplateSpecializationTypes(this_()),
160 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000161 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
162 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000163 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000164 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCallbf1a0282010-06-04 23:28:52 +0000165 NullTypeSourceInfo(QualType()),
Charles Davis071cc7d2010-08-16 03:33:14 +0000166 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000167 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000168 BuiltinInfo(builtins),
169 DeclarationNames(*this),
Argyrios Kyrtzidis9a44b5f2010-10-28 09:29:35 +0000170 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000171 LastSDM(0, 0),
172 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000173 ObjCIdRedefinitionType = QualType();
174 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000175 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000176 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000177 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000178 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000179}
180
Reid Spencer5f016e22007-07-11 17:01:13 +0000181ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000182 // Release the DenseMaps associated with DeclContext objects.
183 // FIXME: Is this the ideal solution?
184 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000185
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000186 // Call all of the deallocation functions.
187 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
188 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000189
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000190 // Release all of the memory associated with overridden C++ methods.
191 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
192 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
193 OM != OMEnd; ++OM)
194 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000195
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000196 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000197 // because they can contain DenseMaps.
198 for (llvm::DenseMap<const ObjCContainerDecl*,
199 const ASTRecordLayout*>::iterator
200 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
201 // Increment in loop to prevent using deallocated memory.
202 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
203 R->Destroy(*this);
204
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000205 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
206 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
207 // Increment in loop to prevent using deallocated memory.
208 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
209 R->Destroy(*this);
210 }
Douglas Gregor63200642010-08-30 16:49:28 +0000211
212 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
213 AEnd = DeclAttrs.end();
214 A != AEnd; ++A)
215 A->second->~AttrVec();
216}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000217
Douglas Gregor00545312010-05-23 18:26:36 +0000218void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
219 Deallocations.push_back(std::make_pair(Callback, Data));
220}
221
Mike Stump1eb44332009-09-09 15:08:12 +0000222void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000223ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
224 ExternalSource.reset(Source.take());
225}
226
Reid Spencer5f016e22007-07-11 17:01:13 +0000227void ASTContext::PrintStats() const {
228 fprintf(stderr, "*** AST Context Stats:\n");
229 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000230
Douglas Gregordbe833d2009-05-26 14:40:08 +0000231 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000232#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000233#define ABSTRACT_TYPE(Name, Parent)
234#include "clang/AST/TypeNodes.def"
235 0 // Extra
236 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000237
Reid Spencer5f016e22007-07-11 17:01:13 +0000238 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
239 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000240 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000241 }
242
Douglas Gregordbe833d2009-05-26 14:40:08 +0000243 unsigned Idx = 0;
244 unsigned TotalBytes = 0;
245#define TYPE(Name, Parent) \
246 if (counts[Idx]) \
247 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
248 TotalBytes += counts[Idx] * sizeof(Name##Type); \
249 ++Idx;
250#define ABSTRACT_TYPE(Name, Parent)
251#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Douglas Gregordbe833d2009-05-26 14:40:08 +0000253 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000254
Douglas Gregor4923aa22010-07-02 20:37:36 +0000255 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000256 fprintf(stderr, " %u/%u implicit default constructors created\n",
257 NumImplicitDefaultConstructorsDeclared,
258 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000259 fprintf(stderr, " %u/%u implicit copy constructors created\n",
260 NumImplicitCopyConstructorsDeclared,
261 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000262 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
263 NumImplicitCopyAssignmentOperatorsDeclared,
264 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000265 fprintf(stderr, " %u/%u implicit destructors created\n",
266 NumImplicitDestructorsDeclared, NumImplicitDestructors);
267
Douglas Gregor2cf26342009-04-09 22:27:44 +0000268 if (ExternalSource.get()) {
269 fprintf(stderr, "\n");
270 ExternalSource->PrintStats();
271 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000272
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000273 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000274}
275
276
John McCalle27ec8a2009-10-23 23:03:21 +0000277void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000278 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000279 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000280 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000281}
282
Reid Spencer5f016e22007-07-11 17:01:13 +0000283void ASTContext::InitBuiltinTypes() {
284 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Reid Spencer5f016e22007-07-11 17:01:13 +0000286 // C99 6.2.5p19.
287 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000288
Reid Spencer5f016e22007-07-11 17:01:13 +0000289 // C99 6.2.5p2.
290 InitBuiltinType(BoolTy, BuiltinType::Bool);
291 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000292 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 InitBuiltinType(CharTy, BuiltinType::Char_S);
294 else
295 InitBuiltinType(CharTy, BuiltinType::Char_U);
296 // C99 6.2.5p4.
297 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
298 InitBuiltinType(ShortTy, BuiltinType::Short);
299 InitBuiltinType(IntTy, BuiltinType::Int);
300 InitBuiltinType(LongTy, BuiltinType::Long);
301 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 // C99 6.2.5p6.
304 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
305 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
306 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
307 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
308 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000309
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 // C99 6.2.5p10.
311 InitBuiltinType(FloatTy, BuiltinType::Float);
312 InitBuiltinType(DoubleTy, BuiltinType::Double);
313 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000314
Chris Lattner2df9ced2009-04-30 02:43:43 +0000315 // GNU extension, 128-bit integers.
316 InitBuiltinType(Int128Ty, BuiltinType::Int128);
317 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
318
Chris Lattner3a250322009-02-26 23:43:47 +0000319 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
320 InitBuiltinType(WCharTy, BuiltinType::WChar);
321 else // C99
322 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000323
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000324 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
325 InitBuiltinType(Char16Ty, BuiltinType::Char16);
326 else // C99
327 Char16Ty = getFromTargetType(Target.getChar16Type());
328
329 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
330 InitBuiltinType(Char32Ty, BuiltinType::Char32);
331 else // C99
332 Char32Ty = getFromTargetType(Target.getChar32Type());
333
Douglas Gregor898574e2008-12-05 23:32:09 +0000334 // Placeholder type for type-dependent expressions whose type is
335 // completely unknown. No code should ever check a type against
336 // DependentTy and users should never see it; however, it is here to
337 // help diagnose failures to properly check for type-dependent
338 // expressions.
339 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000340
John McCall2a984ca2010-10-12 00:20:44 +0000341 // Placeholder type for functions.
342 InitBuiltinType(OverloadTy, BuiltinType::Overload);
343
Mike Stump1eb44332009-09-09 15:08:12 +0000344 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000345 // not yet been deduced.
John McCall2a984ca2010-10-12 00:20:44 +0000346 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 // C99 6.2.5p11.
349 FloatComplexTy = getComplexType(FloatTy);
350 DoubleComplexTy = getComplexType(DoubleTy);
351 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000352
Steve Naroff7e219e42007-10-15 14:41:52 +0000353 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000354
Steve Naroffde2e22d2009-07-15 18:40:39 +0000355 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
356 ObjCIdTypedefType = QualType();
357 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000358 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000360 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000361 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
362 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000363 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000364
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000365 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000367 // void * type
368 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000369
370 // nullptr type (C++0x 2.14.7)
371 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000372}
373
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000374Diagnostic &ASTContext::getDiagnostics() const {
375 return SourceMgr.getDiagnostics();
376}
377
Douglas Gregor63200642010-08-30 16:49:28 +0000378AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
379 AttrVec *&Result = DeclAttrs[D];
380 if (!Result) {
381 void *Mem = Allocate(sizeof(AttrVec));
382 Result = new (Mem) AttrVec;
383 }
384
385 return *Result;
386}
387
388/// \brief Erase the attributes corresponding to the given declaration.
389void ASTContext::eraseDeclAttrs(const Decl *D) {
390 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
391 if (Pos != DeclAttrs.end()) {
392 Pos->second->~AttrVec();
393 DeclAttrs.erase(Pos);
394 }
395}
396
397
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000398MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000399ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000400 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000401 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000402 = InstantiatedFromStaticDataMember.find(Var);
403 if (Pos == InstantiatedFromStaticDataMember.end())
404 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Douglas Gregor7caa6822009-07-24 20:34:43 +0000406 return Pos->second;
407}
408
Mike Stump1eb44332009-09-09 15:08:12 +0000409void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000410ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000411 TemplateSpecializationKind TSK,
412 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000413 assert(Inst->isStaticDataMember() && "Not a static data member");
414 assert(Tmpl->isStaticDataMember() && "Not a static data member");
415 assert(!InstantiatedFromStaticDataMember[Inst] &&
416 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000417 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000418 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000419}
420
John McCall7ba107a2009-11-18 02:36:19 +0000421NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000422ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000423 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000424 = InstantiatedFromUsingDecl.find(UUD);
425 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000426 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Anders Carlsson0d8df782009-08-29 19:37:28 +0000428 return Pos->second;
429}
430
431void
John McCalled976492009-12-04 22:46:56 +0000432ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
433 assert((isa<UsingDecl>(Pattern) ||
434 isa<UnresolvedUsingValueDecl>(Pattern) ||
435 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
436 "pattern decl is not a using decl");
437 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
438 InstantiatedFromUsingDecl[Inst] = Pattern;
439}
440
441UsingShadowDecl *
442ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
443 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
444 = InstantiatedFromUsingShadowDecl.find(Inst);
445 if (Pos == InstantiatedFromUsingShadowDecl.end())
446 return 0;
447
448 return Pos->second;
449}
450
451void
452ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
453 UsingShadowDecl *Pattern) {
454 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
455 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000456}
457
Anders Carlssond8b285f2009-09-01 04:26:58 +0000458FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
459 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
460 = InstantiatedFromUnnamedFieldDecl.find(Field);
461 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
462 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Anders Carlssond8b285f2009-09-01 04:26:58 +0000464 return Pos->second;
465}
466
467void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
468 FieldDecl *Tmpl) {
469 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
470 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
471 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
472 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Anders Carlssond8b285f2009-09-01 04:26:58 +0000474 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
475}
476
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000477ASTContext::overridden_cxx_method_iterator
478ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
479 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
480 = OverriddenMethods.find(Method);
481 if (Pos == OverriddenMethods.end())
482 return 0;
483
484 return Pos->second.begin();
485}
486
487ASTContext::overridden_cxx_method_iterator
488ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
489 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
490 = OverriddenMethods.find(Method);
491 if (Pos == OverriddenMethods.end())
492 return 0;
493
494 return Pos->second.end();
495}
496
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000497unsigned
498ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
499 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
500 = OverriddenMethods.find(Method);
501 if (Pos == OverriddenMethods.end())
502 return 0;
503
504 return Pos->second.size();
505}
506
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000507void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
508 const CXXMethodDecl *Overridden) {
509 OverriddenMethods[Method].push_back(Overridden);
510}
511
Chris Lattner464175b2007-07-18 17:52:12 +0000512//===----------------------------------------------------------------------===//
513// Type Sizing and Analysis
514//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000515
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000516/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
517/// scalar floating point type.
518const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000519 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000520 assert(BT && "Not a floating point type!");
521 switch (BT->getKind()) {
522 default: assert(0 && "Not a floating point type!");
523 case BuiltinType::Float: return Target.getFloatFormat();
524 case BuiltinType::Double: return Target.getDoubleFormat();
525 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
526 }
527}
528
Ken Dyck8b752f12010-01-27 17:10:57 +0000529/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000530/// specified decl. Note that bitfields do not have a valid alignment, so
531/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000532/// If @p RefAsPointee, references are treated like their underlying type
533/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000534CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000535 unsigned Align = Target.getCharWidth();
536
John McCall4081a5c2010-10-08 18:24:19 +0000537 bool UseAlignAttrOnly = false;
538 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
539 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000540
John McCall4081a5c2010-10-08 18:24:19 +0000541 // __attribute__((aligned)) can increase or decrease alignment
542 // *except* on a struct or struct member, where it only increases
543 // alignment unless 'packed' is also specified.
544 //
545 // It is an error for [[align]] to decrease alignment, so we can
546 // ignore that possibility; Sema should diagnose it.
547 if (isa<FieldDecl>(D)) {
548 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
549 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
550 } else {
551 UseAlignAttrOnly = true;
552 }
553 }
554
555 if (UseAlignAttrOnly) {
556 // ignore type of value
557 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000558 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000559 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000560 if (RefAsPointee)
561 T = RT->getPointeeType();
562 else
563 T = getPointerType(RT->getPointeeType());
564 }
565 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindola6deecb02010-06-04 23:15:27 +0000566 unsigned MinWidth = Target.getLargeArrayMinWidth();
567 unsigned ArrayAlign = Target.getLargeArrayAlign();
568 if (isa<VariableArrayType>(T) && MinWidth != 0)
569 Align = std::max(Align, ArrayAlign);
570 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
571 unsigned Size = getTypeSize(CT);
572 if (MinWidth != 0 && MinWidth <= Size)
573 Align = std::max(Align, ArrayAlign);
574 }
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000575 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000576 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
577 T = cast<ArrayType>(T)->getElementType();
578
579 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
580 }
Charles Davis05f62472010-02-23 04:52:00 +0000581 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
582 // In the case of a field in a packed struct, we want the minimum
583 // of the alignment of the field and the alignment of the struct.
584 Align = std::min(Align,
585 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
586 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000587 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000588
Ken Dyck8b752f12010-01-27 17:10:57 +0000589 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000590}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000591
John McCallea1471e2010-05-20 01:18:31 +0000592std::pair<CharUnits, CharUnits>
593ASTContext::getTypeInfoInChars(const Type *T) {
594 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
595 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
596 CharUnits::fromQuantity(Info.second / getCharWidth()));
597}
598
599std::pair<CharUnits, CharUnits>
600ASTContext::getTypeInfoInChars(QualType T) {
601 return getTypeInfoInChars(T.getTypePtr());
602}
603
Chris Lattnera7674d82007-07-13 22:13:22 +0000604/// getTypeSize - Return the size of the specified type, in bits. This method
605/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000606///
607/// FIXME: Pointers into different addr spaces could have different sizes and
608/// alignment requirements: getPointerInfo should take an AddrSpace, this
609/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000610std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000611ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000612 uint64_t Width=0;
613 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000614 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000615#define TYPE(Class, Base)
616#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000617#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000618#define DEPENDENT_TYPE(Class, Base) case Type::Class:
619#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000620 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000621 break;
622
Chris Lattner692233e2007-07-13 22:27:08 +0000623 case Type::FunctionNoProto:
624 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000625 // GCC extension: alignof(function) = 32 bits
626 Width = 0;
627 Align = 32;
628 break;
629
Douglas Gregor72564e72009-02-26 23:50:07 +0000630 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000631 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000632 Width = 0;
633 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
634 break;
635
Steve Narofffb22d962007-08-30 01:06:46 +0000636 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000637 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Chris Lattner98be4942008-03-05 18:54:05 +0000639 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000640 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000641 Align = EltInfo.second;
642 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000643 }
Nate Begeman213541a2008-04-18 23:10:10 +0000644 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000645 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000646 const VectorType *VT = cast<VectorType>(T);
647 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
648 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000649 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000650 // If the alignment is not a power of 2, round up to the next power of 2.
651 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000652 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000653 Align = llvm::NextPowerOf2(Align);
654 Width = llvm::RoundUpToAlignment(Width, Align);
655 }
Chris Lattner030d8842007-07-19 22:06:24 +0000656 break;
657 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000658
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000659 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000660 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000661 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000662 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000663 // GCC extension: alignof(void) = 8 bits.
664 Width = 0;
665 Align = 8;
666 break;
667
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000668 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000669 Width = Target.getBoolWidth();
670 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000671 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000672 case BuiltinType::Char_S:
673 case BuiltinType::Char_U:
674 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000675 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000676 Width = Target.getCharWidth();
677 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000678 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000679 case BuiltinType::WChar:
680 Width = Target.getWCharWidth();
681 Align = Target.getWCharAlign();
682 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000683 case BuiltinType::Char16:
684 Width = Target.getChar16Width();
685 Align = Target.getChar16Align();
686 break;
687 case BuiltinType::Char32:
688 Width = Target.getChar32Width();
689 Align = Target.getChar32Align();
690 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000691 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000692 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000693 Width = Target.getShortWidth();
694 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000695 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000696 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000697 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000698 Width = Target.getIntWidth();
699 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000700 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000701 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000702 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000703 Width = Target.getLongWidth();
704 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000705 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000706 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000707 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000708 Width = Target.getLongLongWidth();
709 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000710 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000711 case BuiltinType::Int128:
712 case BuiltinType::UInt128:
713 Width = 128;
714 Align = 128; // int128_t is 128-bit aligned on all targets.
715 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000716 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000717 Width = Target.getFloatWidth();
718 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000719 break;
720 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000721 Width = Target.getDoubleWidth();
722 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000723 break;
724 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000725 Width = Target.getLongDoubleWidth();
726 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000727 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000728 case BuiltinType::NullPtr:
729 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
730 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000731 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000732 case BuiltinType::ObjCId:
733 case BuiltinType::ObjCClass:
734 case BuiltinType::ObjCSel:
735 Width = Target.getPointerWidth(0);
736 Align = Target.getPointerAlign(0);
737 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000738 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000739 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000740 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000741 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000742 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000743 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000744 case Type::BlockPointer: {
745 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
746 Width = Target.getPointerWidth(AS);
747 Align = Target.getPointerAlign(AS);
748 break;
749 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000750 case Type::LValueReference:
751 case Type::RValueReference: {
752 // alignof and sizeof should never enter this code path here, so we go
753 // the pointer route.
754 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
755 Width = Target.getPointerWidth(AS);
756 Align = Target.getPointerAlign(AS);
757 break;
758 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000759 case Type::Pointer: {
760 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000761 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000762 Align = Target.getPointerAlign(AS);
763 break;
764 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000765 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000766 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000767 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000768 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000769 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000770 Align = PtrDiffInfo.second;
771 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000772 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000773 case Type::Complex: {
774 // Complex types have the same alignment as their elements, but twice the
775 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000776 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000777 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000778 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000779 Align = EltInfo.second;
780 break;
781 }
John McCallc12c5bb2010-05-15 11:32:37 +0000782 case Type::ObjCObject:
783 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000784 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000785 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000786 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
787 Width = Layout.getSize();
788 Align = Layout.getAlignment();
789 break;
790 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000791 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000792 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000793 const TagType *TT = cast<TagType>(T);
794
795 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000796 Width = 1;
797 Align = 1;
798 break;
799 }
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Daniel Dunbar1d751182008-11-08 05:48:37 +0000801 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000802 return getTypeInfo(ET->getDecl()->getIntegerType());
803
Daniel Dunbar1d751182008-11-08 05:48:37 +0000804 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000805 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
806 Width = Layout.getSize();
807 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000808 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000809 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000810
Chris Lattner9fcfe922009-10-22 05:17:15 +0000811 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000812 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
813 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000814
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000815 case Type::Paren:
816 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
817
Douglas Gregor18857642009-04-30 17:32:17 +0000818 case Type::Typedef: {
819 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000820 std::pair<uint64_t, unsigned> Info
821 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
822 Align = std::max(Typedef->getMaxAlignment(), Info.second);
823 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000824 break;
Chris Lattner71763312008-04-06 22:05:18 +0000825 }
Douglas Gregor18857642009-04-30 17:32:17 +0000826
827 case Type::TypeOfExpr:
828 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
829 .getTypePtr());
830
831 case Type::TypeOf:
832 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
833
Anders Carlsson395b4752009-06-24 19:06:50 +0000834 case Type::Decltype:
835 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
836 .getTypePtr());
837
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000838 case Type::Elaborated:
839 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Douglas Gregor18857642009-04-30 17:32:17 +0000841 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000842 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000843 "Cannot request the size of a dependent type");
844 // FIXME: this is likely to be wrong once we support template
845 // aliases, since a template alias could refer to a typedef that
846 // has an __aligned__ attribute on it.
847 return getTypeInfo(getCanonicalType(T));
848 }
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Chris Lattner464175b2007-07-18 17:52:12 +0000850 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000851 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000852}
853
Ken Dyckbdc601b2009-12-22 14:23:30 +0000854/// getTypeSizeInChars - Return the size of the specified type, in characters.
855/// This method does not work on incomplete types.
856CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000857 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000858}
859CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000860 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000861}
862
Ken Dyck16e20cc2010-01-26 17:25:18 +0000863/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000864/// characters. This method does not work on incomplete types.
865CharUnits ASTContext::getTypeAlignInChars(QualType T) {
866 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
867}
868CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
869 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
870}
871
Chris Lattner34ebde42009-01-27 18:08:34 +0000872/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
873/// type for the current target in bits. This can be different than the ABI
874/// alignment in cases where it is beneficial for performance to overalign
875/// a data type.
876unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
877 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000878
879 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000880 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000881 T = CT->getElementType().getTypePtr();
882 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
883 T->isSpecificBuiltinType(BuiltinType::LongLong))
884 return std::max(ABIAlign, (unsigned)getTypeSize(T));
885
Chris Lattner34ebde42009-01-27 18:08:34 +0000886 return ABIAlign;
887}
888
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000889/// ShallowCollectObjCIvars -
890/// Collect all ivars, including those synthesized, in the current class.
891///
892void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000893 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000894 // FIXME. This need be removed but there are two many places which
895 // assume const-ness of ObjCInterfaceDecl
896 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
897 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
898 Iv= Iv->getNextIvar())
899 Ivars.push_back(Iv);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000900}
901
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000902/// DeepCollectObjCIvars -
903/// This routine first collects all declared, but not synthesized, ivars in
904/// super class and then collects all ivars, including those synthesized for
905/// current class. This routine is used for implementation of current class
906/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000907///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000908void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
909 bool leafClass,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000910 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000911 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
912 DeepCollectObjCIvars(SuperClass, false, Ivars);
913 if (!leafClass) {
914 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
915 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000916 Ivars.push_back(*I);
917 }
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000918 else
919 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian98200742009-05-12 18:14:29 +0000920}
921
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000922/// CollectInheritedProtocols - Collect all protocols in current class and
923/// those inherited by it.
924void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000925 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000926 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +0000927 // We can use protocol_iterator here instead of
928 // all_referenced_protocol_iterator since we are walking all categories.
929 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
930 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000931 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000932 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000933 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000934 PE = Proto->protocol_end(); P != PE; ++P) {
935 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000936 CollectInheritedProtocols(*P, Protocols);
937 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000938 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000939
940 // Categories of this Interface.
941 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
942 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
943 CollectInheritedProtocols(CDeclChain, Protocols);
944 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
945 while (SD) {
946 CollectInheritedProtocols(SD, Protocols);
947 SD = SD->getSuperClass();
948 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000949 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +0000950 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000951 PE = OC->protocol_end(); P != PE; ++P) {
952 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000953 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000954 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
955 PE = Proto->protocol_end(); P != PE; ++P)
956 CollectInheritedProtocols(*P, Protocols);
957 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000958 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000959 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
960 PE = OP->protocol_end(); P != PE; ++P) {
961 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000962 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000963 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
964 PE = Proto->protocol_end(); P != PE; ++P)
965 CollectInheritedProtocols(*P, Protocols);
966 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000967 }
968}
969
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000970unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
971 unsigned count = 0;
972 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000973 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
974 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000975 count += CDecl->ivar_size();
976
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000977 // Count ivar defined in this class's implementation. This
978 // includes synthesized ivars.
979 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000980 count += ImplDecl->ivar_size();
981
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000982 return count;
983}
984
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000985/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
986ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
987 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
988 I = ObjCImpls.find(D);
989 if (I != ObjCImpls.end())
990 return cast<ObjCImplementationDecl>(I->second);
991 return 0;
992}
993/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
994ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
995 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
996 I = ObjCImpls.find(D);
997 if (I != ObjCImpls.end())
998 return cast<ObjCCategoryImplDecl>(I->second);
999 return 0;
1000}
1001
1002/// \brief Set the implementation of ObjCInterfaceDecl.
1003void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1004 ObjCImplementationDecl *ImplD) {
1005 assert(IFaceD && ImplD && "Passed null params");
1006 ObjCImpls[IFaceD] = ImplD;
1007}
1008/// \brief Set the implementation of ObjCCategoryDecl.
1009void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1010 ObjCCategoryImplDecl *ImplD) {
1011 assert(CatD && ImplD && "Passed null params");
1012 ObjCImpls[CatD] = ImplD;
1013}
1014
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001015/// \brief Get the copy initialization expression of VarDecl,or NULL if
1016/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001017Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001018 assert(VD && "Passed null params");
1019 assert(VD->hasAttr<BlocksAttr>() &&
1020 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001021 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001022 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001023 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1024}
1025
1026/// \brief Set the copy inialization expression of a block var decl.
1027void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1028 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001029 assert(VD->hasAttr<BlocksAttr>() &&
1030 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001031 BlockVarCopyInits[VD] = Init;
1032}
1033
John McCalla93c9342009-12-07 02:54:59 +00001034/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001035///
John McCalla93c9342009-12-07 02:54:59 +00001036/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001037/// the TypeLoc wrappers.
1038///
1039/// \param T the type that will be the basis for type source info. This type
1040/// should refer to how the declarator was written in source code, not to
1041/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001042TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001043 unsigned DataSize) {
1044 if (!DataSize)
1045 DataSize = TypeLoc::getFullDataSizeForType(T);
1046 else
1047 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001048 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001049
John McCalla93c9342009-12-07 02:54:59 +00001050 TypeSourceInfo *TInfo =
1051 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1052 new (TInfo) TypeSourceInfo(T);
1053 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001054}
1055
John McCalla93c9342009-12-07 02:54:59 +00001056TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001057 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001058 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001059 DI->getTypeLoc().initialize(L);
1060 return DI;
1061}
1062
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001063const ASTRecordLayout &
1064ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1065 return getObjCLayout(D, 0);
1066}
1067
1068const ASTRecordLayout &
1069ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1070 return getObjCLayout(D->getClassInterface(), D);
1071}
1072
Chris Lattnera7674d82007-07-13 22:13:22 +00001073//===----------------------------------------------------------------------===//
1074// Type creation/memoization methods
1075//===----------------------------------------------------------------------===//
1076
John McCall0953e762009-09-24 19:53:00 +00001077QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1078 unsigned Fast = Quals.getFastQualifiers();
1079 Quals.removeFastQualifiers();
1080
1081 // Check if we've already instantiated this type.
1082 llvm::FoldingSetNodeID ID;
1083 ExtQuals::Profile(ID, TypeNode, Quals);
1084 void *InsertPos = 0;
1085 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1086 assert(EQ->getQualifiers() == Quals);
1087 QualType T = QualType(EQ, Fast);
1088 return T;
1089 }
1090
John McCall49f4e1c2010-12-10 11:01:00 +00001091 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001092 ExtQualNodes.InsertNode(New, InsertPos);
1093 QualType T = QualType(New, Fast);
1094 return T;
1095}
1096
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001097QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001098 QualType CanT = getCanonicalType(T);
1099 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001100 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001101
John McCall0953e762009-09-24 19:53:00 +00001102 // If we are composing extended qualifiers together, merge together
1103 // into one ExtQuals node.
1104 QualifierCollector Quals;
1105 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001106
John McCall0953e762009-09-24 19:53:00 +00001107 // If this type already has an address space specified, it cannot get
1108 // another one.
1109 assert(!Quals.hasAddressSpace() &&
1110 "Type cannot be in multiple addr spaces!");
1111 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001112
John McCall0953e762009-09-24 19:53:00 +00001113 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001114}
1115
Chris Lattnerb7d25532009-02-18 22:53:11 +00001116QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001117 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001118 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001119 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001120 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001122 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001123 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001124 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001125 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1126 return getPointerType(ResultType);
1127 }
1128 }
Mike Stump1eb44332009-09-09 15:08:12 +00001129
John McCall0953e762009-09-24 19:53:00 +00001130 // If we are composing extended qualifiers together, merge together
1131 // into one ExtQuals node.
1132 QualifierCollector Quals;
1133 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001134
John McCall0953e762009-09-24 19:53:00 +00001135 // If this type already has an ObjCGC specified, it cannot get
1136 // another one.
1137 assert(!Quals.hasObjCGCAttr() &&
1138 "Type cannot have multiple ObjCGCs!");
1139 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001140
John McCall0953e762009-09-24 19:53:00 +00001141 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001142}
Chris Lattnera7674d82007-07-13 22:13:22 +00001143
John McCalle6a365d2010-12-19 02:44:49 +00001144const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1145 FunctionType::ExtInfo Info) {
1146 if (T->getExtInfo() == Info)
1147 return T;
1148
1149 QualType Result;
1150 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1151 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1152 } else {
1153 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1154 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1155 EPI.ExtInfo = Info;
1156 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1157 FPT->getNumArgs(), EPI);
1158 }
1159
1160 return cast<FunctionType>(Result.getTypePtr());
1161}
1162
Reid Spencer5f016e22007-07-11 17:01:13 +00001163/// getComplexType - Return the uniqued reference to the type for a complex
1164/// number with the specified element type.
1165QualType ASTContext::getComplexType(QualType T) {
1166 // Unique pointers, to guarantee there is only one pointer of a particular
1167 // structure.
1168 llvm::FoldingSetNodeID ID;
1169 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 void *InsertPos = 0;
1172 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1173 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Reid Spencer5f016e22007-07-11 17:01:13 +00001175 // If the pointee type isn't canonical, this won't be a canonical type either,
1176 // so fill in the canonical type field.
1177 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001178 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001179 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Reid Spencer5f016e22007-07-11 17:01:13 +00001181 // Get the new insert position for the node we care about.
1182 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001183 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 }
John McCall6b304a02009-09-24 23:30:46 +00001185 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001186 Types.push_back(New);
1187 ComplexTypes.InsertNode(New, InsertPos);
1188 return QualType(New, 0);
1189}
1190
Reid Spencer5f016e22007-07-11 17:01:13 +00001191/// getPointerType - Return the uniqued reference to the type for a pointer to
1192/// the specified type.
1193QualType ASTContext::getPointerType(QualType T) {
1194 // Unique pointers, to guarantee there is only one pointer of a particular
1195 // structure.
1196 llvm::FoldingSetNodeID ID;
1197 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 void *InsertPos = 0;
1200 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1201 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Reid Spencer5f016e22007-07-11 17:01:13 +00001203 // If the pointee type isn't canonical, this won't be a canonical type either,
1204 // so fill in the canonical type field.
1205 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001206 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001207 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Reid Spencer5f016e22007-07-11 17:01:13 +00001209 // Get the new insert position for the node we care about.
1210 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001211 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 }
John McCall6b304a02009-09-24 23:30:46 +00001213 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 Types.push_back(New);
1215 PointerTypes.InsertNode(New, InsertPos);
1216 return QualType(New, 0);
1217}
1218
Mike Stump1eb44332009-09-09 15:08:12 +00001219/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001220/// a pointer to the specified block.
1221QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001222 assert(T->isFunctionType() && "block of function types only");
1223 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001224 // structure.
1225 llvm::FoldingSetNodeID ID;
1226 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Steve Naroff5618bd42008-08-27 16:04:49 +00001228 void *InsertPos = 0;
1229 if (BlockPointerType *PT =
1230 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1231 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001232
1233 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001234 // type either so fill in the canonical type field.
1235 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001236 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001237 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Steve Naroff5618bd42008-08-27 16:04:49 +00001239 // Get the new insert position for the node we care about.
1240 BlockPointerType *NewIP =
1241 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001242 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001243 }
John McCall6b304a02009-09-24 23:30:46 +00001244 BlockPointerType *New
1245 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001246 Types.push_back(New);
1247 BlockPointerTypes.InsertNode(New, InsertPos);
1248 return QualType(New, 0);
1249}
1250
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001251/// getLValueReferenceType - Return the uniqued reference to the type for an
1252/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001253QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 // Unique pointers, to guarantee there is only one pointer of a particular
1255 // structure.
1256 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001257 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001258
1259 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001260 if (LValueReferenceType *RT =
1261 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001263
John McCall54e14c42009-10-22 22:37:11 +00001264 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1265
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 // If the referencee type isn't canonical, this won't be a canonical type
1267 // either, so fill in the canonical type field.
1268 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001269 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1270 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1271 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001272
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001274 LValueReferenceType *NewIP =
1275 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001276 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001277 }
1278
John McCall6b304a02009-09-24 23:30:46 +00001279 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001280 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1281 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001283 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001284
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001285 return QualType(New, 0);
1286}
1287
1288/// getRValueReferenceType - Return the uniqued reference to the type for an
1289/// rvalue reference to the specified type.
1290QualType ASTContext::getRValueReferenceType(QualType T) {
1291 // Unique pointers, to guarantee there is only one pointer of a particular
1292 // structure.
1293 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001294 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001295
1296 void *InsertPos = 0;
1297 if (RValueReferenceType *RT =
1298 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1299 return QualType(RT, 0);
1300
John McCall54e14c42009-10-22 22:37:11 +00001301 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1302
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001303 // If the referencee type isn't canonical, this won't be a canonical type
1304 // either, so fill in the canonical type field.
1305 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001306 if (InnerRef || !T.isCanonical()) {
1307 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1308 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001309
1310 // Get the new insert position for the node we care about.
1311 RValueReferenceType *NewIP =
1312 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001313 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001314 }
1315
John McCall6b304a02009-09-24 23:30:46 +00001316 RValueReferenceType *New
1317 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001318 Types.push_back(New);
1319 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 return QualType(New, 0);
1321}
1322
Sebastian Redlf30208a2009-01-24 21:16:55 +00001323/// getMemberPointerType - Return the uniqued reference to the type for a
1324/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001325QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001326 // Unique pointers, to guarantee there is only one pointer of a particular
1327 // structure.
1328 llvm::FoldingSetNodeID ID;
1329 MemberPointerType::Profile(ID, T, Cls);
1330
1331 void *InsertPos = 0;
1332 if (MemberPointerType *PT =
1333 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1334 return QualType(PT, 0);
1335
1336 // If the pointee or class type isn't canonical, this won't be a canonical
1337 // type either, so fill in the canonical type field.
1338 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001339 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001340 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1341
1342 // Get the new insert position for the node we care about.
1343 MemberPointerType *NewIP =
1344 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001345 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001346 }
John McCall6b304a02009-09-24 23:30:46 +00001347 MemberPointerType *New
1348 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001349 Types.push_back(New);
1350 MemberPointerTypes.InsertNode(New, InsertPos);
1351 return QualType(New, 0);
1352}
1353
Mike Stump1eb44332009-09-09 15:08:12 +00001354/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001355/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001356QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001357 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001358 ArrayType::ArraySizeModifier ASM,
1359 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001360 assert((EltTy->isDependentType() ||
1361 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001362 "Constant array of VLAs is illegal!");
1363
Chris Lattner38aeec72009-05-13 04:12:56 +00001364 // Convert the array size into a canonical width matching the pointer size for
1365 // the target.
1366 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001367 ArySize =
1368 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001371 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001374 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001375 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 // If the element type isn't canonical, this won't be a canonical type either,
1379 // so fill in the canonical type field.
1380 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001381 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001382 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001383 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001385 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001386 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001387 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 }
Mike Stump1eb44332009-09-09 15:08:12 +00001389
John McCall6b304a02009-09-24 23:30:46 +00001390 ConstantArrayType *New = new(*this,TypeAlignment)
1391 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001392 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 Types.push_back(New);
1394 return QualType(New, 0);
1395}
1396
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001397/// getIncompleteArrayType - Returns a unique reference to the type for a
1398/// incomplete array of the specified element type.
1399QualType ASTContext::getUnknownSizeVariableArrayType(QualType Ty) {
1400 QualType ElemTy = getBaseElementType(Ty);
1401 DeclarationName Name;
1402 llvm::SmallVector<QualType, 8> ATypes;
1403 QualType ATy = Ty;
1404 while (const ArrayType *AT = getAsArrayType(ATy)) {
1405 ATypes.push_back(ATy);
1406 ATy = AT->getElementType();
1407 }
1408 for (int i = ATypes.size() - 1; i >= 0; i--) {
1409 if (const VariableArrayType *VAT = getAsVariableArrayType(ATypes[i])) {
1410 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Star,
1411 0, VAT->getBracketsRange());
1412 }
1413 else if (const ConstantArrayType *CAT = getAsConstantArrayType(ATypes[i])) {
1414 llvm::APSInt ConstVal(CAT->getSize());
1415 ElemTy = getConstantArrayType(ElemTy, ConstVal, ArrayType::Normal, 0);
1416 }
1417 else if (getAsIncompleteArrayType(ATypes[i])) {
1418 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Normal,
1419 0, SourceRange());
1420 }
1421 else
1422 assert(false && "DependentArrayType is seen");
1423 }
1424 return ElemTy;
1425}
1426
1427/// getVariableArrayDecayedType - Returns a vla type where known sizes
1428/// are replaced with [*]
1429QualType ASTContext::getVariableArrayDecayedType(QualType Ty) {
1430 if (Ty->isPointerType()) {
1431 QualType BaseType = Ty->getAs<PointerType>()->getPointeeType();
1432 if (isa<VariableArrayType>(BaseType)) {
1433 ArrayType *AT = dyn_cast<ArrayType>(BaseType);
1434 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1435 if (VAT->getSizeExpr()) {
1436 Ty = getUnknownSizeVariableArrayType(BaseType);
1437 Ty = getPointerType(Ty);
1438 }
1439 }
1440 }
1441 return Ty;
1442}
1443
1444
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001445/// getVariableArrayType - Returns a non-unique reference to the type for a
1446/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001447QualType ASTContext::getVariableArrayType(QualType EltTy,
1448 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001449 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001450 unsigned EltTypeQuals,
1451 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001452 // Since we don't unique expressions, it isn't possible to unique VLA's
1453 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001454 QualType CanonType;
1455
1456 if (!EltTy.isCanonical()) {
Douglas Gregor715e9c82010-05-23 16:10:32 +00001457 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1458 EltTypeQuals, Brackets);
1459 }
1460
John McCall6b304a02009-09-24 23:30:46 +00001461 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001462 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001463
1464 VariableArrayTypes.push_back(New);
1465 Types.push_back(New);
1466 return QualType(New, 0);
1467}
1468
Douglas Gregor898574e2008-12-05 23:32:09 +00001469/// getDependentSizedArrayType - Returns a non-unique reference to
1470/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001471/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001472QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1473 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001474 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001475 unsigned EltTypeQuals,
1476 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001477 assert((!NumElts || NumElts->isTypeDependent() ||
1478 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001479 "Size must be type- or value-dependent!");
1480
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001481 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001482 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001483 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001484
Douglas Gregor32adc8b2010-10-26 00:51:02 +00001485 QualType CanonicalEltTy = getCanonicalType(EltTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001486 if (NumElts) {
1487 // Dependently-sized array types that do not have a specified
1488 // number of elements will have their sizes deduced from an
1489 // initializer.
Douglas Gregor32adc8b2010-10-26 00:51:02 +00001490 DependentSizedArrayType::Profile(ID, *this, CanonicalEltTy, ASM,
Douglas Gregorcb78d882009-11-19 18:03:26 +00001491 EltTypeQuals, NumElts);
1492
1493 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1494 }
1495
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001496 DependentSizedArrayType *New;
1497 if (Canon) {
1498 // We already have a canonical version of this array type; use it as
1499 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001500 New = new (*this, TypeAlignment)
1501 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1502 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor32adc8b2010-10-26 00:51:02 +00001503 } else if (CanonicalEltTy == EltTy) {
1504 // This is a canonical type. Record it.
1505 New = new (*this, TypeAlignment)
1506 DependentSizedArrayType(*this, EltTy, QualType(),
1507 NumElts, ASM, EltTypeQuals, Brackets);
1508
1509 if (NumElts) {
1510#ifndef NDEBUG
1511 DependentSizedArrayType *CanonCheck
1512 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1513 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1514 (void)CanonCheck;
1515#endif
1516 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001517 }
Douglas Gregor32adc8b2010-10-26 00:51:02 +00001518 } else {
1519 QualType Canon = getDependentSizedArrayType(CanonicalEltTy, NumElts,
1520 ASM, EltTypeQuals,
1521 SourceRange());
1522 New = new (*this, TypeAlignment)
1523 DependentSizedArrayType(*this, EltTy, Canon,
1524 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001525 }
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Douglas Gregor898574e2008-12-05 23:32:09 +00001527 Types.push_back(New);
1528 return QualType(New, 0);
1529}
1530
Eli Friedmanc5773c42008-02-15 18:16:39 +00001531QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1532 ArrayType::ArraySizeModifier ASM,
1533 unsigned EltTypeQuals) {
1534 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001535 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001536
1537 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001538 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001539 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1540 return QualType(ATP, 0);
1541
1542 // If the element type isn't canonical, this won't be a canonical type
1543 // either, so fill in the canonical type field.
1544 QualType Canonical;
1545
John McCall467b27b2009-10-22 20:10:53 +00001546 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001547 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001548 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001549
1550 // Get the new insert position for the node we care about.
1551 IncompleteArrayType *NewIP =
1552 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001553 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001554 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001555
John McCall6b304a02009-09-24 23:30:46 +00001556 IncompleteArrayType *New = new (*this, TypeAlignment)
1557 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001558
1559 IncompleteArrayTypes.InsertNode(New, InsertPos);
1560 Types.push_back(New);
1561 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001562}
1563
Steve Naroff73322922007-07-18 18:00:27 +00001564/// getVectorType - Return the unique reference to a vector type of
1565/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001566QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001567 VectorType::VectorKind VecKind) {
Chris Lattner33daae62010-10-01 22:42:38 +00001568 BuiltinType *BaseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Chris Lattner33daae62010-10-01 22:42:38 +00001570 BaseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1571 assert(BaseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 // Check if we've already instantiated a vector of this type.
1574 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001575 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001576
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 void *InsertPos = 0;
1578 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1579 return QualType(VTP, 0);
1580
1581 // If the element type isn't canonical, this won't be a canonical type either,
1582 // so fill in the canonical type field.
1583 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001584 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001585 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 // Get the new insert position for the node we care about.
1588 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001589 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 }
John McCall6b304a02009-09-24 23:30:46 +00001591 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001592 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 VectorTypes.InsertNode(New, InsertPos);
1594 Types.push_back(New);
1595 return QualType(New, 0);
1596}
1597
Nate Begeman213541a2008-04-18 23:10:10 +00001598/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001599/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001600QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001601 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Chris Lattnerf52ab252008-04-06 22:59:24 +00001603 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001604 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Steve Naroff73322922007-07-18 18:00:27 +00001606 // Check if we've already instantiated a vector of this type.
1607 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001608 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001609 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001610 void *InsertPos = 0;
1611 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1612 return QualType(VTP, 0);
1613
1614 // If the element type isn't canonical, this won't be a canonical type either,
1615 // so fill in the canonical type field.
1616 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001617 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001618 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Steve Naroff73322922007-07-18 18:00:27 +00001620 // Get the new insert position for the node we care about.
1621 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001622 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001623 }
John McCall6b304a02009-09-24 23:30:46 +00001624 ExtVectorType *New = new (*this, TypeAlignment)
1625 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001626 VectorTypes.InsertNode(New, InsertPos);
1627 Types.push_back(New);
1628 return QualType(New, 0);
1629}
1630
Mike Stump1eb44332009-09-09 15:08:12 +00001631QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001632 Expr *SizeExpr,
1633 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001634 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001635 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001636 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001638 void *InsertPos = 0;
1639 DependentSizedExtVectorType *Canon
1640 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1641 DependentSizedExtVectorType *New;
1642 if (Canon) {
1643 // We already have a canonical version of this array type; use it as
1644 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001645 New = new (*this, TypeAlignment)
1646 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1647 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001648 } else {
1649 QualType CanonVecTy = getCanonicalType(vecType);
1650 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001651 New = new (*this, TypeAlignment)
1652 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1653 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001654
1655 DependentSizedExtVectorType *CanonCheck
1656 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1657 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1658 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001659 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1660 } else {
1661 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1662 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001663 New = new (*this, TypeAlignment)
1664 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001665 }
1666 }
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001668 Types.push_back(New);
1669 return QualType(New, 0);
1670}
1671
Douglas Gregor72564e72009-02-26 23:50:07 +00001672/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001673///
Rafael Espindola264ba482010-03-30 20:24:48 +00001674QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1675 const FunctionType::ExtInfo &Info) {
1676 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001677 // Unique functions, to guarantee there is only one function of a particular
1678 // structure.
1679 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001680 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001683 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001684 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Reid Spencer5f016e22007-07-11 17:01:13 +00001687 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001688 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001689 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001690 Canonical =
1691 getFunctionNoProtoType(getCanonicalType(ResultTy),
1692 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001695 FunctionNoProtoType *NewIP =
1696 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001697 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 }
Mike Stump1eb44332009-09-09 15:08:12 +00001699
John McCall6b304a02009-09-24 23:30:46 +00001700 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001701 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001703 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 return QualType(New, 0);
1705}
1706
1707/// getFunctionType - Return a normal function type with a typed argument
1708/// list. isVariadic indicates whether the argument list includes '...'.
John McCalle23cf432010-12-14 08:05:40 +00001709QualType ASTContext::getFunctionType(QualType ResultTy,
1710 const QualType *ArgArray, unsigned NumArgs,
1711 const FunctionProtoType::ExtProtoInfo &EPI) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001712 // Unique functions, to guarantee there is only one function of a particular
1713 // structure.
1714 llvm::FoldingSetNodeID ID;
John McCalle23cf432010-12-14 08:05:40 +00001715 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00001716
1717 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001718 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001719 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001720 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001721
1722 // Determine whether the type being created is already canonical or not.
John McCalle23cf432010-12-14 08:05:40 +00001723 bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001724 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001725 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 isCanonical = false;
1727
John McCalle23cf432010-12-14 08:05:40 +00001728 const CallingConv CallConv = EPI.ExtInfo.getCC();
1729
Reid Spencer5f016e22007-07-11 17:01:13 +00001730 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001731 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001732 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001733 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001734 llvm::SmallVector<QualType, 16> CanonicalArgs;
1735 CanonicalArgs.reserve(NumArgs);
1736 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001737 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001738
John McCalle23cf432010-12-14 08:05:40 +00001739 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1740 if (CanonicalEPI.HasExceptionSpec) {
1741 CanonicalEPI.HasExceptionSpec = false;
1742 CanonicalEPI.HasAnyExceptionSpec = false;
1743 CanonicalEPI.NumExceptions = 0;
1744 }
1745 CanonicalEPI.ExtInfo
1746 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1747
Chris Lattnerf52ab252008-04-06 22:59:24 +00001748 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001749 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00001750 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00001751
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001753 FunctionProtoType *NewIP =
1754 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001755 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001756 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001757
Douglas Gregor72564e72009-02-26 23:50:07 +00001758 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001759 // for two variable size arrays (for parameter and exception types) at the
1760 // end of them.
John McCalle23cf432010-12-14 08:05:40 +00001761 size_t Size = sizeof(FunctionProtoType) +
1762 NumArgs * sizeof(QualType) +
1763 EPI.NumExceptions * sizeof(QualType);
1764 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
1765 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001767 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 return QualType(FTP, 0);
1769}
1770
John McCall3cb0ebd2010-03-10 03:28:59 +00001771#ifndef NDEBUG
1772static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1773 if (!isa<CXXRecordDecl>(D)) return false;
1774 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1775 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1776 return true;
1777 if (RD->getDescribedClassTemplate() &&
1778 !isa<ClassTemplateSpecializationDecl>(RD))
1779 return true;
1780 return false;
1781}
1782#endif
1783
1784/// getInjectedClassNameType - Return the unique reference to the
1785/// injected class name type for the specified templated declaration.
1786QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1787 QualType TST) {
1788 assert(NeedsInjectedClassNameType(Decl));
1789 if (Decl->TypeForDecl) {
1790 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001791 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001792 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1793 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1794 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1795 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001796 Decl->TypeForDecl =
1797 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001798 Types.push_back(Decl->TypeForDecl);
1799 }
1800 return QualType(Decl->TypeForDecl, 0);
1801}
1802
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001803/// getTypeDeclType - Return the unique reference to the type for the
1804/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001805QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001806 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001807 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001808
John McCall19c85762010-02-16 03:57:14 +00001809 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001810 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001811
John McCallbecb8d52010-03-10 06:48:02 +00001812 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1813 "Template type parameter types are always available.");
1814
John McCall19c85762010-02-16 03:57:14 +00001815 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001816 assert(!Record->getPreviousDeclaration() &&
1817 "struct/union has previous declaration");
1818 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001819 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001820 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001821 assert(!Enum->getPreviousDeclaration() &&
1822 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001823 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001824 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001825 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1826 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001827 } else
John McCallbecb8d52010-03-10 06:48:02 +00001828 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001829
John McCallbecb8d52010-03-10 06:48:02 +00001830 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001831 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001832}
1833
Reid Spencer5f016e22007-07-11 17:01:13 +00001834/// getTypedefType - Return the unique reference to the type for the
1835/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001836QualType
1837ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001838 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001840 if (Canonical.isNull())
1841 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001842 Decl->TypeForDecl = new(*this, TypeAlignment)
1843 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001844 Types.push_back(Decl->TypeForDecl);
1845 return QualType(Decl->TypeForDecl, 0);
1846}
1847
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001848QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1849 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1850
1851 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1852 if (PrevDecl->TypeForDecl)
1853 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1854
1855 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1856 Types.push_back(Decl->TypeForDecl);
1857 return QualType(Decl->TypeForDecl, 0);
1858}
1859
1860QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1861 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1862
1863 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1864 if (PrevDecl->TypeForDecl)
1865 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1866
1867 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1868 Types.push_back(Decl->TypeForDecl);
1869 return QualType(Decl->TypeForDecl, 0);
1870}
1871
John McCall49a832b2009-10-18 09:09:24 +00001872/// \brief Retrieve a substitution-result type.
1873QualType
1874ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1875 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001876 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001877 && "replacement types must always be canonical");
1878
1879 llvm::FoldingSetNodeID ID;
1880 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1881 void *InsertPos = 0;
1882 SubstTemplateTypeParmType *SubstParm
1883 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1884
1885 if (!SubstParm) {
1886 SubstParm = new (*this, TypeAlignment)
1887 SubstTemplateTypeParmType(Parm, Replacement);
1888 Types.push_back(SubstParm);
1889 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1890 }
1891
1892 return QualType(SubstParm, 0);
1893}
1894
Douglas Gregorfab9d672009-02-05 23:33:38 +00001895/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001896/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001897/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001898QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001899 bool ParameterPack,
Douglas Gregorefed5c82010-06-16 15:23:05 +00001900 IdentifierInfo *Name) {
Douglas Gregorfab9d672009-02-05 23:33:38 +00001901 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00001902 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001903 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001904 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001905 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1906
1907 if (TypeParm)
1908 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Douglas Gregorefed5c82010-06-16 15:23:05 +00001910 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001911 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00001912 TypeParm = new (*this, TypeAlignment)
1913 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001914
1915 TemplateTypeParmType *TypeCheck
1916 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1917 assert(!TypeCheck && "Template type parameter canonical type broken");
1918 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001919 } else
John McCall6b304a02009-09-24 23:30:46 +00001920 TypeParm = new (*this, TypeAlignment)
1921 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001922
1923 Types.push_back(TypeParm);
1924 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1925
1926 return QualType(TypeParm, 0);
1927}
1928
John McCall3cb0ebd2010-03-10 03:28:59 +00001929TypeSourceInfo *
1930ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1931 SourceLocation NameLoc,
1932 const TemplateArgumentListInfo &Args,
1933 QualType CanonType) {
1934 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1935
1936 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1937 TemplateSpecializationTypeLoc TL
1938 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1939 TL.setTemplateNameLoc(NameLoc);
1940 TL.setLAngleLoc(Args.getLAngleLoc());
1941 TL.setRAngleLoc(Args.getRAngleLoc());
1942 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1943 TL.setArgLocInfo(i, Args[i].getLocInfo());
1944 return DI;
1945}
1946
Mike Stump1eb44332009-09-09 15:08:12 +00001947QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001948ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001949 const TemplateArgumentListInfo &Args,
John McCall71d74bc2010-06-13 09:25:03 +00001950 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001951 unsigned NumArgs = Args.size();
1952
John McCall833ca992009-10-29 08:12:44 +00001953 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1954 ArgVec.reserve(NumArgs);
1955 for (unsigned i = 0; i != NumArgs; ++i)
1956 ArgVec.push_back(Args[i].getArgument());
1957
John McCall31f17ec2010-04-27 00:57:59 +00001958 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001959 Canon);
John McCall833ca992009-10-29 08:12:44 +00001960}
1961
1962QualType
1963ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001964 const TemplateArgument *Args,
1965 unsigned NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001966 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001967 if (!Canon.isNull())
1968 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001969 else
1970 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001971
Douglas Gregor1275ae02009-07-28 23:00:59 +00001972 // Allocate the (non-canonical) template specialization type, but don't
1973 // try to unique it: these types typically have location information that
1974 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001975 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001976 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001977 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001978 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00001979 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00001980 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001981 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Douglas Gregor55f6b142009-02-09 18:46:07 +00001983 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001984 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001985}
1986
Mike Stump1eb44332009-09-09 15:08:12 +00001987QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001988ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1989 const TemplateArgument *Args,
1990 unsigned NumArgs) {
1991 // Build the canonical template specialization type.
1992 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1993 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1994 CanonArgs.reserve(NumArgs);
1995 for (unsigned I = 0; I != NumArgs; ++I)
1996 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1997
1998 // Determine whether this canonical template specialization type already
1999 // exists.
2000 llvm::FoldingSetNodeID ID;
2001 TemplateSpecializationType::Profile(ID, CanonTemplate,
2002 CanonArgs.data(), NumArgs, *this);
2003
2004 void *InsertPos = 0;
2005 TemplateSpecializationType *Spec
2006 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2007
2008 if (!Spec) {
2009 // Allocate a new canonical template specialization type.
2010 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2011 sizeof(TemplateArgument) * NumArgs),
2012 TypeAlignment);
2013 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2014 CanonArgs.data(), NumArgs,
2015 QualType());
2016 Types.push_back(Spec);
2017 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2018 }
2019
2020 assert(Spec->isDependentType() &&
2021 "Non-dependent template-id type must have a canonical type");
2022 return QualType(Spec, 0);
2023}
2024
2025QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002026ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2027 NestedNameSpecifier *NNS,
2028 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002029 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002030 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002031
2032 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002033 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002034 if (T)
2035 return QualType(T, 0);
2036
Douglas Gregor789b1f62010-02-04 18:10:26 +00002037 QualType Canon = NamedType;
2038 if (!Canon.isCanonical()) {
2039 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002040 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2041 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002042 (void)CheckT;
2043 }
2044
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002045 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002046 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002047 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002048 return QualType(T, 0);
2049}
2050
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002051QualType
2052ASTContext::getParenType(QualType InnerType) {
2053 llvm::FoldingSetNodeID ID;
2054 ParenType::Profile(ID, InnerType);
2055
2056 void *InsertPos = 0;
2057 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2058 if (T)
2059 return QualType(T, 0);
2060
2061 QualType Canon = InnerType;
2062 if (!Canon.isCanonical()) {
2063 Canon = getCanonicalType(InnerType);
2064 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2065 assert(!CheckT && "Paren canonical type broken");
2066 (void)CheckT;
2067 }
2068
2069 T = new (*this) ParenType(InnerType, Canon);
2070 Types.push_back(T);
2071 ParenTypes.InsertNode(T, InsertPos);
2072 return QualType(T, 0);
2073}
2074
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002075QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2076 NestedNameSpecifier *NNS,
2077 const IdentifierInfo *Name,
2078 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00002079 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2080
2081 if (Canon.isNull()) {
2082 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002083 ElaboratedTypeKeyword CanonKeyword = Keyword;
2084 if (Keyword == ETK_None)
2085 CanonKeyword = ETK_Typename;
2086
2087 if (CanonNNS != NNS || CanonKeyword != Keyword)
2088 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002089 }
2090
2091 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002092 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002093
2094 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002095 DependentNameType *T
2096 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002097 if (T)
2098 return QualType(T, 0);
2099
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002100 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002101 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002102 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002103 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002104}
2105
Mike Stump1eb44332009-09-09 15:08:12 +00002106QualType
John McCall33500952010-06-11 00:33:02 +00002107ASTContext::getDependentTemplateSpecializationType(
2108 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002109 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002110 const IdentifierInfo *Name,
2111 const TemplateArgumentListInfo &Args) {
2112 // TODO: avoid this copy
2113 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2114 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2115 ArgCopy.push_back(Args[I].getArgument());
2116 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2117 ArgCopy.size(),
2118 ArgCopy.data());
2119}
2120
2121QualType
2122ASTContext::getDependentTemplateSpecializationType(
2123 ElaboratedTypeKeyword Keyword,
2124 NestedNameSpecifier *NNS,
2125 const IdentifierInfo *Name,
2126 unsigned NumArgs,
2127 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00002128 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2129
Douglas Gregor789b1f62010-02-04 18:10:26 +00002130 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002131 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2132 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002133
2134 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002135 DependentTemplateSpecializationType *T
2136 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002137 if (T)
2138 return QualType(T, 0);
2139
John McCall33500952010-06-11 00:33:02 +00002140 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002141
John McCall33500952010-06-11 00:33:02 +00002142 ElaboratedTypeKeyword CanonKeyword = Keyword;
2143 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2144
2145 bool AnyNonCanonArgs = false;
2146 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2147 for (unsigned I = 0; I != NumArgs; ++I) {
2148 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2149 if (!CanonArgs[I].structurallyEquals(Args[I]))
2150 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002151 }
2152
John McCall33500952010-06-11 00:33:02 +00002153 QualType Canon;
2154 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2155 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2156 Name, NumArgs,
2157 CanonArgs.data());
2158
2159 // Find the insert position again.
2160 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2161 }
2162
2163 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2164 sizeof(TemplateArgument) * NumArgs),
2165 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002166 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002167 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002168 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002169 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002170 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002171}
2172
Douglas Gregor7536dd52010-12-20 02:24:11 +00002173QualType ASTContext::getPackExpansionType(QualType Pattern) {
2174 llvm::FoldingSetNodeID ID;
2175 PackExpansionType::Profile(ID, Pattern);
2176
2177 assert(Pattern->containsUnexpandedParameterPack() &&
2178 "Pack expansions must expand one or more parameter packs");
2179 void *InsertPos = 0;
2180 PackExpansionType *T
2181 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2182 if (T)
2183 return QualType(T, 0);
2184
2185 QualType Canon;
2186 if (!Pattern.isCanonical()) {
2187 Canon = getPackExpansionType(getCanonicalType(Pattern));
2188
2189 // Find the insert position again.
2190 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2191 }
2192
2193 T = new (*this) PackExpansionType(Pattern, Canon);
2194 Types.push_back(T);
2195 PackExpansionTypes.InsertNode(T, InsertPos);
2196 return QualType(T, 0);
2197}
2198
Chris Lattner88cb27a2008-04-07 04:56:42 +00002199/// CmpProtocolNames - Comparison predicate for sorting protocols
2200/// alphabetically.
2201static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2202 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002203 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002204}
2205
John McCallc12c5bb2010-05-15 11:32:37 +00002206static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002207 unsigned NumProtocols) {
2208 if (NumProtocols == 0) return true;
2209
2210 for (unsigned i = 1; i != NumProtocols; ++i)
2211 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2212 return false;
2213 return true;
2214}
2215
2216static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002217 unsigned &NumProtocols) {
2218 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Chris Lattner88cb27a2008-04-07 04:56:42 +00002220 // Sort protocols, keyed by name.
2221 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2222
2223 // Remove duplicates.
2224 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2225 NumProtocols = ProtocolsEnd-Protocols;
2226}
2227
John McCallc12c5bb2010-05-15 11:32:37 +00002228QualType ASTContext::getObjCObjectType(QualType BaseType,
2229 ObjCProtocolDecl * const *Protocols,
2230 unsigned NumProtocols) {
2231 // If the base type is an interface and there aren't any protocols
2232 // to add, then the interface type will do just fine.
2233 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2234 return BaseType;
2235
2236 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002237 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002238 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002239 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002240 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2241 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002242
John McCallc12c5bb2010-05-15 11:32:37 +00002243 // Build the canonical type, which has the canonical base type and
2244 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002245 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002246 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2247 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2248 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002249 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2250 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002251 unsigned UniqueCount = NumProtocols;
2252
John McCall54e14c42009-10-22 22:37:11 +00002253 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002254 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2255 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002256 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002257 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2258 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002259 }
2260
2261 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002262 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2263 }
2264
2265 unsigned Size = sizeof(ObjCObjectTypeImpl);
2266 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2267 void *Mem = Allocate(Size, TypeAlignment);
2268 ObjCObjectTypeImpl *T =
2269 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2270
2271 Types.push_back(T);
2272 ObjCObjectTypes.InsertNode(T, InsertPos);
2273 return QualType(T, 0);
2274}
2275
2276/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2277/// the given object type.
2278QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2279 llvm::FoldingSetNodeID ID;
2280 ObjCObjectPointerType::Profile(ID, ObjectT);
2281
2282 void *InsertPos = 0;
2283 if (ObjCObjectPointerType *QT =
2284 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2285 return QualType(QT, 0);
2286
2287 // Find the canonical object type.
2288 QualType Canonical;
2289 if (!ObjectT.isCanonical()) {
2290 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2291
2292 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002293 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2294 }
2295
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002296 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002297 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2298 ObjCObjectPointerType *QType =
2299 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002301 Types.push_back(QType);
2302 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002303 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002304}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002305
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002306/// getObjCInterfaceType - Return the unique reference to the type for the
2307/// specified ObjC interface decl. The list of protocols is optional.
2308QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2309 if (Decl->TypeForDecl)
2310 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002312 // FIXME: redeclarations?
2313 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2314 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2315 Decl->TypeForDecl = T;
2316 Types.push_back(T);
2317 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002318}
2319
Douglas Gregor72564e72009-02-26 23:50:07 +00002320/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2321/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002322/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002323/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002324/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002325QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002326 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002327 if (tofExpr->isTypeDependent()) {
2328 llvm::FoldingSetNodeID ID;
2329 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002330
Douglas Gregorb1975722009-07-30 23:18:24 +00002331 void *InsertPos = 0;
2332 DependentTypeOfExprType *Canon
2333 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2334 if (Canon) {
2335 // We already have a "canonical" version of an identical, dependent
2336 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002337 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002338 QualType((TypeOfExprType*)Canon, 0));
2339 }
2340 else {
2341 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002342 Canon
2343 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002344 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2345 toe = Canon;
2346 }
2347 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002348 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002349 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002350 }
Steve Naroff9752f252007-08-01 18:02:17 +00002351 Types.push_back(toe);
2352 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002353}
2354
Steve Naroff9752f252007-08-01 18:02:17 +00002355/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2356/// TypeOfType AST's. The only motivation to unique these nodes would be
2357/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002358/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002359/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002360QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002361 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002362 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002363 Types.push_back(tot);
2364 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002365}
2366
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002367/// getDecltypeForExpr - Given an expr, will return the decltype for that
2368/// expression, according to the rules in C++0x [dcl.type.simple]p4
2369static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002370 if (e->isTypeDependent())
2371 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002372
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002373 // If e is an id expression or a class member access, decltype(e) is defined
2374 // as the type of the entity named by e.
2375 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2376 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2377 return VD->getType();
2378 }
2379 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2380 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2381 return FD->getType();
2382 }
2383 // If e is a function call or an invocation of an overloaded operator,
2384 // (parentheses around e are ignored), decltype(e) is defined as the
2385 // return type of that function.
2386 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2387 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002388
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002389 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002390
2391 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002392 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002393 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002394 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002395
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002396 return T;
2397}
2398
Anders Carlsson395b4752009-06-24 19:06:50 +00002399/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2400/// DecltypeType AST's. The only motivation to unique these nodes would be
2401/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002402/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002403/// on canonical type's (which are always unique).
2404QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002405 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002406 if (e->isTypeDependent()) {
2407 llvm::FoldingSetNodeID ID;
2408 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002409
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002410 void *InsertPos = 0;
2411 DependentDecltypeType *Canon
2412 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2413 if (Canon) {
2414 // We already have a "canonical" version of an equivalent, dependent
2415 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002416 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002417 QualType((DecltypeType*)Canon, 0));
2418 }
2419 else {
2420 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002421 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002422 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2423 dt = Canon;
2424 }
2425 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002426 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002427 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002428 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002429 Types.push_back(dt);
2430 return QualType(dt, 0);
2431}
2432
Reid Spencer5f016e22007-07-11 17:01:13 +00002433/// getTagDeclType - Return the unique reference to the type for the
2434/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002435QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002436 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002437 // FIXME: What is the design on getTagDeclType when it requires casting
2438 // away const? mutable?
2439 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002440}
2441
Mike Stump1eb44332009-09-09 15:08:12 +00002442/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2443/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2444/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002445CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002446 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002447}
2448
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002449/// getSignedWCharType - Return the type of "signed wchar_t".
2450/// Used when in C++, as a GCC extension.
2451QualType ASTContext::getSignedWCharType() const {
2452 // FIXME: derive from "Target" ?
2453 return WCharTy;
2454}
2455
2456/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2457/// Used when in C++, as a GCC extension.
2458QualType ASTContext::getUnsignedWCharType() const {
2459 // FIXME: derive from "Target" ?
2460 return UnsignedIntTy;
2461}
2462
Chris Lattner8b9023b2007-07-13 03:05:23 +00002463/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2464/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2465QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002466 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002467}
2468
Chris Lattnere6327742008-04-02 05:18:44 +00002469//===----------------------------------------------------------------------===//
2470// Type Operators
2471//===----------------------------------------------------------------------===//
2472
John McCall54e14c42009-10-22 22:37:11 +00002473CanQualType ASTContext::getCanonicalParamType(QualType T) {
2474 // Push qualifiers into arrays, and then discard any remaining
2475 // qualifiers.
2476 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002477 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002478 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002479 QualType Result;
2480 if (isa<ArrayType>(Ty)) {
2481 Result = getArrayDecayedType(QualType(Ty,0));
2482 } else if (isa<FunctionType>(Ty)) {
2483 Result = getPointerType(QualType(Ty, 0));
2484 } else {
2485 Result = QualType(Ty, 0);
2486 }
2487
2488 return CanQualType::CreateUnsafe(Result);
2489}
2490
Chris Lattner77c96472008-04-06 22:41:35 +00002491/// getCanonicalType - Return the canonical (structural) type corresponding to
2492/// the specified potentially non-canonical type. The non-canonical version
2493/// of a type may have many "decorated" versions of types. Decorators can
2494/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2495/// to be free of any of these, allowing two canonical types to be compared
2496/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002497CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002498 QualifierCollector Quals;
2499 const Type *Ptr = Quals.strip(T);
2500 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002501
John McCall0953e762009-09-24 19:53:00 +00002502 // The canonical internal type will be the canonical type *except*
2503 // that we push type qualifiers down through array types.
2504
2505 // If there are no new qualifiers to push down, stop here.
2506 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002507 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002508
John McCall0953e762009-09-24 19:53:00 +00002509 // If the type qualifiers are on an array type, get the canonical
2510 // type of the array with the qualifiers applied to the element
2511 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002512 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2513 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002514 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002515
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002516 // Get the canonical version of the element with the extra qualifiers on it.
2517 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002518 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002519 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002520
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002521 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002522 return CanQualType::CreateUnsafe(
2523 getConstantArrayType(NewEltTy, CAT->getSize(),
2524 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002525 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002526 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002527 return CanQualType::CreateUnsafe(
2528 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002529 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002530
Douglas Gregor898574e2008-12-05 23:32:09 +00002531 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002532 return CanQualType::CreateUnsafe(
2533 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00002534 DSAT->getSizeExpr(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002535 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002536 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002537 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002538
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002539 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002540 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00002541 VAT->getSizeExpr(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002542 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002543 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002544 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002545}
2546
Chandler Carruth28e318c2009-12-29 07:16:59 +00002547QualType ASTContext::getUnqualifiedArrayType(QualType T,
2548 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002549 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002550 const ArrayType *AT = getAsArrayType(T);
2551 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002552 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002553 }
2554
Chandler Carruth28e318c2009-12-29 07:16:59 +00002555 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002556 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002557 if (Elt == UnqualElt)
2558 return T;
2559
Douglas Gregor9dadd942010-05-17 18:45:21 +00002560 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002561 return getConstantArrayType(UnqualElt, CAT->getSize(),
2562 CAT->getSizeModifier(), 0);
2563 }
2564
Douglas Gregor9dadd942010-05-17 18:45:21 +00002565 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002566 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2567 }
2568
Douglas Gregor9dadd942010-05-17 18:45:21 +00002569 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2570 return getVariableArrayType(UnqualElt,
John McCall3fa5cae2010-10-26 07:05:15 +00002571 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00002572 VAT->getSizeModifier(),
2573 VAT->getIndexTypeCVRQualifiers(),
2574 VAT->getBracketsRange());
2575 }
2576
2577 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall3fa5cae2010-10-26 07:05:15 +00002578 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002579 DSAT->getSizeModifier(), 0,
2580 SourceRange());
2581}
2582
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002583/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2584/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2585/// they point to and return true. If T1 and T2 aren't pointer types
2586/// or pointer-to-member types, or if they are not similar at this
2587/// level, returns false and leaves T1 and T2 unchanged. Top-level
2588/// qualifiers on T1 and T2 are ignored. This function will typically
2589/// be called in a loop that successively "unwraps" pointer and
2590/// pointer-to-member types to compare them at each level.
2591bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2592 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2593 *T2PtrType = T2->getAs<PointerType>();
2594 if (T1PtrType && T2PtrType) {
2595 T1 = T1PtrType->getPointeeType();
2596 T2 = T2PtrType->getPointeeType();
2597 return true;
2598 }
2599
2600 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2601 *T2MPType = T2->getAs<MemberPointerType>();
2602 if (T1MPType && T2MPType &&
2603 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2604 QualType(T2MPType->getClass(), 0))) {
2605 T1 = T1MPType->getPointeeType();
2606 T2 = T2MPType->getPointeeType();
2607 return true;
2608 }
2609
2610 if (getLangOptions().ObjC1) {
2611 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2612 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2613 if (T1OPType && T2OPType) {
2614 T1 = T1OPType->getPointeeType();
2615 T2 = T2OPType->getPointeeType();
2616 return true;
2617 }
2618 }
2619
2620 // FIXME: Block pointers, too?
2621
2622 return false;
2623}
2624
Abramo Bagnara25777432010-08-11 22:01:17 +00002625DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name,
2626 SourceLocation NameLoc) {
John McCall80ad16f2009-11-24 18:42:40 +00002627 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002628 // DNInfo work in progress: CHECKME: what about DNLoc?
2629 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2630
John McCall80ad16f2009-11-24 18:42:40 +00002631 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002632 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002633 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002634 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2635 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002636 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00002637 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2638 // DNInfo work in progress: FIXME: source locations?
2639 DeclarationNameLoc DNLoc;
2640 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2641 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2642 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002643 }
2644 }
2645
John McCall0bd6feb2009-12-02 08:04:21 +00002646 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2647 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002648 // DNInfo work in progress: CHECKME: what about DNLoc?
2649 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002650}
2651
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002652TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002653 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2654 if (TemplateTemplateParmDecl *TTP
2655 = dyn_cast<TemplateTemplateParmDecl>(Template))
2656 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2657
2658 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002659 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002660 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002661
John McCall0bd6feb2009-12-02 08:04:21 +00002662 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002663
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002664 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2665 assert(DTN && "Non-dependent template names must refer to template decls.");
2666 return DTN->CanonicalTemplateName;
2667}
2668
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002669bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2670 X = getCanonicalTemplateName(X);
2671 Y = getCanonicalTemplateName(Y);
2672 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2673}
2674
Mike Stump1eb44332009-09-09 15:08:12 +00002675TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002676ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2677 switch (Arg.getKind()) {
2678 case TemplateArgument::Null:
2679 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Douglas Gregor1275ae02009-07-28 23:00:59 +00002681 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002682 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002683
Douglas Gregor1275ae02009-07-28 23:00:59 +00002684 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002685 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002686
Douglas Gregor788cd062009-11-11 01:00:40 +00002687 case TemplateArgument::Template:
2688 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2689
Douglas Gregor1275ae02009-07-28 23:00:59 +00002690 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002691 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002692 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002693
Douglas Gregor1275ae02009-07-28 23:00:59 +00002694 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002695 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002696
Douglas Gregor1275ae02009-07-28 23:00:59 +00002697 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00002698 if (Arg.pack_size() == 0)
2699 return Arg;
2700
Douglas Gregor910f8002010-11-07 23:05:16 +00002701 TemplateArgument *CanonArgs
2702 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00002703 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002704 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002705 AEnd = Arg.pack_end();
2706 A != AEnd; (void)++A, ++Idx)
2707 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002708
Douglas Gregor910f8002010-11-07 23:05:16 +00002709 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00002710 }
2711 }
2712
2713 // Silence GCC warning
2714 assert(false && "Unhandled template argument kind");
2715 return TemplateArgument();
2716}
2717
Douglas Gregord57959a2009-03-27 23:10:48 +00002718NestedNameSpecifier *
2719ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002720 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002721 return 0;
2722
2723 switch (NNS->getKind()) {
2724 case NestedNameSpecifier::Identifier:
2725 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002726 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002727 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2728 NNS->getAsIdentifier());
2729
2730 case NestedNameSpecifier::Namespace:
2731 // A namespace is canonical; build a nested-name-specifier with
2732 // this namespace and no prefix.
2733 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2734
2735 case NestedNameSpecifier::TypeSpec:
2736 case NestedNameSpecifier::TypeSpecWithTemplate: {
2737 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00002738
2739 // If we have some kind of dependent-named type (e.g., "typename T::type"),
2740 // break it apart into its prefix and identifier, then reconsititute those
2741 // as the canonical nested-name-specifier. This is required to canonicalize
2742 // a dependent nested-name-specifier involving typedefs of dependent-name
2743 // types, e.g.,
2744 // typedef typename T::type T1;
2745 // typedef typename T1::type T2;
2746 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
2747 NestedNameSpecifier *Prefix
2748 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
2749 return NestedNameSpecifier::Create(*this, Prefix,
2750 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
2751 }
2752
Douglas Gregor643f8432010-11-04 00:14:23 +00002753 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00002754 if (const DependentTemplateSpecializationType *DTST
2755 = T->getAs<DependentTemplateSpecializationType>()) {
2756 NestedNameSpecifier *Prefix
2757 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
2758 TemplateName Name
2759 = getDependentTemplateName(Prefix, DTST->getIdentifier());
2760 T = getTemplateSpecializationType(Name,
2761 DTST->getArgs(), DTST->getNumArgs());
2762 T = getCanonicalType(T);
2763 }
2764
2765 return NestedNameSpecifier::Create(*this, 0, false, T.getTypePtr());
Douglas Gregord57959a2009-03-27 23:10:48 +00002766 }
2767
2768 case NestedNameSpecifier::Global:
2769 // The global specifier is canonical and unique.
2770 return NNS;
2771 }
2772
2773 // Required to silence a GCC warning
2774 return 0;
2775}
2776
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002777
2778const ArrayType *ASTContext::getAsArrayType(QualType T) {
2779 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002780 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002781 // Handle the common positive case fast.
2782 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2783 return AT;
2784 }
Mike Stump1eb44332009-09-09 15:08:12 +00002785
John McCall0953e762009-09-24 19:53:00 +00002786 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002787 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002788 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002789 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002790
John McCall0953e762009-09-24 19:53:00 +00002791 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002792 // implements C99 6.7.3p8: "If the specification of an array type includes
2793 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002794
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002795 // If we get here, we either have type qualifiers on the type, or we have
2796 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002797 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002798
John McCall0953e762009-09-24 19:53:00 +00002799 QualifierCollector Qs;
John McCall49f4e1c2010-12-10 11:01:00 +00002800 const Type *Ty = Qs.strip(T.getDesugaredType(*this));
Mike Stump1eb44332009-09-09 15:08:12 +00002801
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002802 // If we have a simple case, just return now.
2803 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002804 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002805 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002806
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002807 // Otherwise, we have an array and we have qualifiers on it. Push the
2808 // qualifiers into the array element type and return a new array type.
2809 // Get the canonical version of the element with the extra qualifiers on it.
2810 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002811 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002812
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002813 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2814 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2815 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002816 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002817 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2818 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2819 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002820 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002821
Mike Stump1eb44332009-09-09 15:08:12 +00002822 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002823 = dyn_cast<DependentSizedArrayType>(ATy))
2824 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002825 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00002826 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00002827 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002828 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002829 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002830
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002831 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002832 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00002833 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002834 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002835 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002836 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002837}
2838
Chris Lattnere6327742008-04-02 05:18:44 +00002839/// getArrayDecayedType - Return the properly qualified result of decaying the
2840/// specified array type to a pointer. This operation is non-trivial when
2841/// handling typedefs etc. The canonical type of "T" must be an array type,
2842/// this returns a pointer to a properly qualified element of the array.
2843///
2844/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2845QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002846 // Get the element type with 'getAsArrayType' so that we don't lose any
2847 // typedefs in the element type of the array. This also handles propagation
2848 // of type qualifiers from the array type into the element type if present
2849 // (C99 6.7.3p8).
2850 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2851 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002852
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002853 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002854
2855 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002856 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002857}
2858
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002859QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002860 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002861 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2862 QT = AT->getElementType();
John McCall49f4e1c2010-12-10 11:01:00 +00002863 return Qs.apply(*this, QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002864}
2865
Anders Carlssonfbbce492009-09-25 01:23:32 +00002866QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2867 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002868
Anders Carlssonfbbce492009-09-25 01:23:32 +00002869 if (const ArrayType *AT = getAsArrayType(ElemTy))
2870 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002871
Anders Carlsson6183a992008-12-21 03:44:36 +00002872 return ElemTy;
2873}
2874
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002875/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002876uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002877ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2878 uint64_t ElementCount = 1;
2879 do {
2880 ElementCount *= CA->getSize().getZExtValue();
2881 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2882 } while (CA);
2883 return ElementCount;
2884}
2885
Reid Spencer5f016e22007-07-11 17:01:13 +00002886/// getFloatingRank - Return a relative rank for floating point types.
2887/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002888static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002889 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002890 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002891
John McCall183700f2009-09-21 23:43:11 +00002892 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2893 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002894 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002895 case BuiltinType::Float: return FloatRank;
2896 case BuiltinType::Double: return DoubleRank;
2897 case BuiltinType::LongDouble: return LongDoubleRank;
2898 }
2899}
2900
Mike Stump1eb44332009-09-09 15:08:12 +00002901/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2902/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002903/// 'typeDomain' is a real floating point or complex type.
2904/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002905QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2906 QualType Domain) const {
2907 FloatingRank EltRank = getFloatingRank(Size);
2908 if (Domain->isComplexType()) {
2909 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002910 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002911 case FloatRank: return FloatComplexTy;
2912 case DoubleRank: return DoubleComplexTy;
2913 case LongDoubleRank: return LongDoubleComplexTy;
2914 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002915 }
Chris Lattner1361b112008-04-06 23:58:54 +00002916
2917 assert(Domain->isRealFloatingType() && "Unknown domain!");
2918 switch (EltRank) {
2919 default: assert(0 && "getFloatingRank(): illegal value for rank");
2920 case FloatRank: return FloatTy;
2921 case DoubleRank: return DoubleTy;
2922 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002923 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002924}
2925
Chris Lattner7cfeb082008-04-06 23:55:33 +00002926/// getFloatingTypeOrder - Compare the rank of the two specified floating
2927/// point types, ignoring the domain of the type (i.e. 'double' ==
2928/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002929/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002930int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2931 FloatingRank LHSR = getFloatingRank(LHS);
2932 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002933
Chris Lattnera75cea32008-04-06 23:38:49 +00002934 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002935 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002936 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002937 return 1;
2938 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002939}
2940
Chris Lattnerf52ab252008-04-06 22:59:24 +00002941/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2942/// routine will assert if passed a built-in type that isn't an integer or enum,
2943/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002944unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002945 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002946 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002947 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002948
Eli Friedmana3426752009-07-05 23:44:27 +00002949 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2950 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2951
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002952 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2953 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2954
2955 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2956 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2957
Chris Lattnerf52ab252008-04-06 22:59:24 +00002958 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002959 default: assert(0 && "getIntegerRank(): not a built-in integer");
2960 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002961 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002962 case BuiltinType::Char_S:
2963 case BuiltinType::Char_U:
2964 case BuiltinType::SChar:
2965 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002966 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002967 case BuiltinType::Short:
2968 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002969 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002970 case BuiltinType::Int:
2971 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002972 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002973 case BuiltinType::Long:
2974 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002975 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002976 case BuiltinType::LongLong:
2977 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002978 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002979 case BuiltinType::Int128:
2980 case BuiltinType::UInt128:
2981 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002982 }
2983}
2984
Eli Friedman04e83572009-08-20 04:21:42 +00002985/// \brief Whether this is a promotable bitfield reference according
2986/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2987///
2988/// \returns the type this bit-field will promote to, or NULL if no
2989/// promotion occurs.
2990QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002991 if (E->isTypeDependent() || E->isValueDependent())
2992 return QualType();
2993
Eli Friedman04e83572009-08-20 04:21:42 +00002994 FieldDecl *Field = E->getBitField();
2995 if (!Field)
2996 return QualType();
2997
2998 QualType FT = Field->getType();
2999
3000 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3001 uint64_t BitWidth = BitWidthAP.getZExtValue();
3002 uint64_t IntSize = getTypeSize(IntTy);
3003 // GCC extension compatibility: if the bit-field size is less than or equal
3004 // to the size of int, it gets promoted no matter what its type is.
3005 // For instance, unsigned long bf : 4 gets promoted to signed int.
3006 if (BitWidth < IntSize)
3007 return IntTy;
3008
3009 if (BitWidth == IntSize)
3010 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3011
3012 // Types bigger than int are not subject to promotions, and therefore act
3013 // like the base type.
3014 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3015 // is ridiculous.
3016 return QualType();
3017}
3018
Eli Friedmana95d7572009-08-19 07:44:53 +00003019/// getPromotedIntegerType - Returns the type that Promotable will
3020/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3021/// integer type.
3022QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
3023 assert(!Promotable.isNull());
3024 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003025 if (const EnumType *ET = Promotable->getAs<EnumType>())
3026 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003027 if (Promotable->isSignedIntegerType())
3028 return IntTy;
3029 uint64_t PromotableSize = getTypeSize(Promotable);
3030 uint64_t IntSize = getTypeSize(IntTy);
3031 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3032 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3033}
3034
Mike Stump1eb44332009-09-09 15:08:12 +00003035/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003036/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003037/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003038int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003039 Type *LHSC = getCanonicalType(LHS).getTypePtr();
3040 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003041 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003042
Chris Lattnerf52ab252008-04-06 22:59:24 +00003043 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3044 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003045
Chris Lattner7cfeb082008-04-06 23:55:33 +00003046 unsigned LHSRank = getIntegerRank(LHSC);
3047 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003048
Chris Lattner7cfeb082008-04-06 23:55:33 +00003049 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3050 if (LHSRank == RHSRank) return 0;
3051 return LHSRank > RHSRank ? 1 : -1;
3052 }
Mike Stump1eb44332009-09-09 15:08:12 +00003053
Chris Lattner7cfeb082008-04-06 23:55:33 +00003054 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3055 if (LHSUnsigned) {
3056 // If the unsigned [LHS] type is larger, return it.
3057 if (LHSRank >= RHSRank)
3058 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003059
Chris Lattner7cfeb082008-04-06 23:55:33 +00003060 // If the signed type can represent all values of the unsigned type, it
3061 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003062 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003063 return -1;
3064 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003065
Chris Lattner7cfeb082008-04-06 23:55:33 +00003066 // If the unsigned [RHS] type is larger, return it.
3067 if (RHSRank >= LHSRank)
3068 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003069
Chris Lattner7cfeb082008-04-06 23:55:33 +00003070 // If the signed type can represent all values of the unsigned type, it
3071 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003072 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003073 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003074}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003075
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003076static RecordDecl *
3077CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3078 SourceLocation L, IdentifierInfo *Id) {
3079 if (Ctx.getLangOptions().CPlusPlus)
3080 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3081 else
3082 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3083}
3084
Mike Stump1eb44332009-09-09 15:08:12 +00003085// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00003086QualType ASTContext::getCFConstantStringType() {
3087 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003088 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003089 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003090 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003091 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003092
Anders Carlssonf06273f2007-11-19 00:25:30 +00003093 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003094
Anders Carlsson71993dd2007-08-17 05:31:46 +00003095 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003096 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003097 // int flags;
3098 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003099 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003100 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003101 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003102 FieldTypes[3] = LongTy;
3103
Anders Carlsson71993dd2007-08-17 05:31:46 +00003104 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003105 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003106 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003107 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003108 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003109 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003110 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003111 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003112 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003113 }
3114
Douglas Gregor838db382010-02-11 01:19:42 +00003115 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003116 }
Mike Stump1eb44332009-09-09 15:08:12 +00003117
Anders Carlsson71993dd2007-08-17 05:31:46 +00003118 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003119}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003120
Douglas Gregor319ac892009-04-23 22:29:11 +00003121void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003122 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003123 assert(Rec && "Invalid CFConstantStringType");
3124 CFConstantStringTypeDecl = Rec->getDecl();
3125}
3126
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003127// getNSConstantStringType - Return the type used for constant NSStrings.
3128QualType ASTContext::getNSConstantStringType() {
3129 if (!NSConstantStringTypeDecl) {
3130 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003131 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003132 &Idents.get("__builtin_NSString"));
3133 NSConstantStringTypeDecl->startDefinition();
3134
3135 QualType FieldTypes[3];
3136
3137 // const int *isa;
3138 FieldTypes[0] = getPointerType(IntTy.withConst());
3139 // const char *str;
3140 FieldTypes[1] = getPointerType(CharTy.withConst());
3141 // unsigned int length;
3142 FieldTypes[2] = UnsignedIntTy;
3143
3144 // Create fields
3145 for (unsigned i = 0; i < 3; ++i) {
3146 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3147 SourceLocation(), 0,
3148 FieldTypes[i], /*TInfo=*/0,
3149 /*BitWidth=*/0,
3150 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003151 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003152 NSConstantStringTypeDecl->addDecl(Field);
3153 }
3154
3155 NSConstantStringTypeDecl->completeDefinition();
3156 }
3157
3158 return getTagDeclType(NSConstantStringTypeDecl);
3159}
3160
3161void ASTContext::setNSConstantStringType(QualType T) {
3162 const RecordType *Rec = T->getAs<RecordType>();
3163 assert(Rec && "Invalid NSConstantStringType");
3164 NSConstantStringTypeDecl = Rec->getDecl();
3165}
3166
Mike Stump1eb44332009-09-09 15:08:12 +00003167QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003168 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003169 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003170 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003171 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003172 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003173
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003174 QualType FieldTypes[] = {
3175 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003176 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003177 getPointerType(UnsignedLongTy),
3178 getConstantArrayType(UnsignedLongTy,
3179 llvm::APInt(32, 5), ArrayType::Normal, 0)
3180 };
Mike Stump1eb44332009-09-09 15:08:12 +00003181
Douglas Gregor44b43212008-12-11 16:49:14 +00003182 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003183 FieldDecl *Field = FieldDecl::Create(*this,
3184 ObjCFastEnumerationStateTypeDecl,
3185 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003186 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003187 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003188 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003189 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003190 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003191 }
Mike Stump1eb44332009-09-09 15:08:12 +00003192
Douglas Gregor838db382010-02-11 01:19:42 +00003193 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003194 }
Mike Stump1eb44332009-09-09 15:08:12 +00003195
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003196 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3197}
3198
Mike Stumpadaaad32009-10-20 02:12:22 +00003199QualType ASTContext::getBlockDescriptorType() {
3200 if (BlockDescriptorType)
3201 return getTagDeclType(BlockDescriptorType);
3202
3203 RecordDecl *T;
3204 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003205 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003206 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003207 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003208
3209 QualType FieldTypes[] = {
3210 UnsignedLongTy,
3211 UnsignedLongTy,
3212 };
3213
3214 const char *FieldNames[] = {
3215 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003216 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003217 };
3218
3219 for (size_t i = 0; i < 2; ++i) {
3220 FieldDecl *Field = FieldDecl::Create(*this,
3221 T,
3222 SourceLocation(),
3223 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003224 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003225 /*BitWidth=*/0,
3226 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003227 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003228 T->addDecl(Field);
3229 }
3230
Douglas Gregor838db382010-02-11 01:19:42 +00003231 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003232
3233 BlockDescriptorType = T;
3234
3235 return getTagDeclType(BlockDescriptorType);
3236}
3237
3238void ASTContext::setBlockDescriptorType(QualType T) {
3239 const RecordType *Rec = T->getAs<RecordType>();
3240 assert(Rec && "Invalid BlockDescriptorType");
3241 BlockDescriptorType = Rec->getDecl();
3242}
3243
Mike Stump083c25e2009-10-22 00:49:09 +00003244QualType ASTContext::getBlockDescriptorExtendedType() {
3245 if (BlockDescriptorExtendedType)
3246 return getTagDeclType(BlockDescriptorExtendedType);
3247
3248 RecordDecl *T;
3249 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003250 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003251 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003252 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003253
3254 QualType FieldTypes[] = {
3255 UnsignedLongTy,
3256 UnsignedLongTy,
3257 getPointerType(VoidPtrTy),
3258 getPointerType(VoidPtrTy)
3259 };
3260
3261 const char *FieldNames[] = {
3262 "reserved",
3263 "Size",
3264 "CopyFuncPtr",
3265 "DestroyFuncPtr"
3266 };
3267
3268 for (size_t i = 0; i < 4; ++i) {
3269 FieldDecl *Field = FieldDecl::Create(*this,
3270 T,
3271 SourceLocation(),
3272 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003273 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003274 /*BitWidth=*/0,
3275 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003276 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003277 T->addDecl(Field);
3278 }
3279
Douglas Gregor838db382010-02-11 01:19:42 +00003280 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003281
3282 BlockDescriptorExtendedType = T;
3283
3284 return getTagDeclType(BlockDescriptorExtendedType);
3285}
3286
3287void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3288 const RecordType *Rec = T->getAs<RecordType>();
3289 assert(Rec && "Invalid BlockDescriptorType");
3290 BlockDescriptorExtendedType = Rec->getDecl();
3291}
3292
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003293bool ASTContext::BlockRequiresCopying(QualType Ty) {
3294 if (Ty->isBlockPointerType())
3295 return true;
3296 if (isObjCNSObjectType(Ty))
3297 return true;
3298 if (Ty->isObjCObjectPointerType())
3299 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003300 if (getLangOptions().CPlusPlus) {
3301 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3302 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3303 return RD->hasConstCopyConstructor(*this);
3304
3305 }
3306 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003307 return false;
3308}
3309
Daniel Dunbar4087f272010-08-17 22:39:59 +00003310QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003311 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003312 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003313 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003314 // unsigned int __flags;
3315 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003316 // void *__copy_helper; // as needed
3317 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003318 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003319 // } *
3320
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003321 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3322
3323 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003324 llvm::SmallString<36> Name;
3325 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3326 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003327 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003328 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003329 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003330 T->startDefinition();
3331 QualType Int32Ty = IntTy;
3332 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3333 QualType FieldTypes[] = {
3334 getPointerType(VoidPtrTy),
3335 getPointerType(getTagDeclType(T)),
3336 Int32Ty,
3337 Int32Ty,
3338 getPointerType(VoidPtrTy),
3339 getPointerType(VoidPtrTy),
3340 Ty
3341 };
3342
Daniel Dunbar4087f272010-08-17 22:39:59 +00003343 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003344 "__isa",
3345 "__forwarding",
3346 "__flags",
3347 "__size",
3348 "__copy_helper",
3349 "__destroy_helper",
3350 DeclName,
3351 };
3352
3353 for (size_t i = 0; i < 7; ++i) {
3354 if (!HasCopyAndDispose && i >=4 && i <= 5)
3355 continue;
3356 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3357 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003358 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003359 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003360 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003361 T->addDecl(Field);
3362 }
3363
Douglas Gregor838db382010-02-11 01:19:42 +00003364 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003365
3366 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003367}
3368
3369
3370QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003371 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003372 llvm::SmallVectorImpl<const Expr *> &Layout) {
3373
Mike Stumpadaaad32009-10-20 02:12:22 +00003374 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003375 llvm::SmallString<36> Name;
3376 llvm::raw_svector_ostream(Name) << "__block_literal_"
3377 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003378 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003379 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003380 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003381 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003382 QualType FieldTypes[] = {
3383 getPointerType(VoidPtrTy),
3384 IntTy,
3385 IntTy,
3386 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003387 (BlockHasCopyDispose ?
3388 getPointerType(getBlockDescriptorExtendedType()) :
3389 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003390 };
3391
3392 const char *FieldNames[] = {
3393 "__isa",
3394 "__flags",
3395 "__reserved",
3396 "__FuncPtr",
3397 "__descriptor"
3398 };
3399
3400 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003401 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003402 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003403 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003404 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003405 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003406 T->addDecl(Field);
3407 }
3408
John McCallea1471e2010-05-20 01:18:31 +00003409 for (unsigned i = 0; i < Layout.size(); ++i) {
3410 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003411
John McCallea1471e2010-05-20 01:18:31 +00003412 QualType FieldType = E->getType();
3413 IdentifierInfo *FieldName = 0;
3414 if (isa<CXXThisExpr>(E)) {
3415 FieldName = &Idents.get("this");
3416 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3417 const ValueDecl *D = BDRE->getDecl();
3418 FieldName = D->getIdentifier();
3419 if (BDRE->isByRef())
Daniel Dunbar4087f272010-08-17 22:39:59 +00003420 FieldType = BuildByRefType(D->getName(), FieldType);
John McCallea1471e2010-05-20 01:18:31 +00003421 } else {
3422 // Padding.
3423 assert(isa<ConstantArrayType>(FieldType) &&
3424 isa<DeclRefExpr>(E) &&
3425 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3426 "doesn't match characteristics of padding decl");
3427 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003428
3429 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003430 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003431 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003432 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003433 T->addDecl(Field);
3434 }
3435
Douglas Gregor838db382010-02-11 01:19:42 +00003436 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003437
3438 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003439}
3440
Douglas Gregor319ac892009-04-23 22:29:11 +00003441void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003442 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003443 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3444 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3445}
3446
Anders Carlssone8c49532007-10-29 06:33:42 +00003447// This returns true if a type has been typedefed to BOOL:
3448// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003449static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003450 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003451 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3452 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003453
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003454 return false;
3455}
3456
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003457/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003458/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003459CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003460 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003461
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003462 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003463 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003464 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003465 // Treat arrays as pointers, since that's how they're passed in.
3466 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003467 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003468 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003469}
3470
3471static inline
3472std::string charUnitsToString(const CharUnits &CU) {
3473 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003474}
3475
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003476/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003477/// declaration.
3478void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3479 std::string& S) {
3480 const BlockDecl *Decl = Expr->getBlockDecl();
3481 QualType BlockTy =
3482 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3483 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003484 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003485 // Compute size of all parameters.
3486 // Start with computing size of a pointer in number of bytes.
3487 // FIXME: There might(should) be a better way of doing this computation!
3488 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003489 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3490 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003491 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003492 E = Decl->param_end(); PI != E; ++PI) {
3493 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003494 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003495 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003496 ParmOffset += sz;
3497 }
3498 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003499 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003500 // Block pointer and offset.
3501 S += "@?0";
3502 ParmOffset = PtrSize;
3503
3504 // Argument types.
3505 ParmOffset = PtrSize;
3506 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3507 Decl->param_end(); PI != E; ++PI) {
3508 ParmVarDecl *PVDecl = *PI;
3509 QualType PType = PVDecl->getOriginalType();
3510 if (const ArrayType *AT =
3511 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3512 // Use array's original type only if it has known number of
3513 // elements.
3514 if (!isa<ConstantArrayType>(AT))
3515 PType = PVDecl->getType();
3516 } else if (PType->isFunctionType())
3517 PType = PVDecl->getType();
3518 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003519 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003520 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003521 }
3522}
3523
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003524/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003525/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003526void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003527 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003528 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003529 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003530 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003531 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003532 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003533 // Compute size of all parameters.
3534 // Start with computing size of a pointer in number of bytes.
3535 // FIXME: There might(should) be a better way of doing this computation!
3536 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003537 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003538 // The first two arguments (self and _cmd) are pointers; account for
3539 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003540 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003541 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003542 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003543 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003544 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003545 assert (sz.isPositive() &&
3546 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003547 ParmOffset += sz;
3548 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003549 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003550 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003551 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003552
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003553 // Argument types.
3554 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003555 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003556 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003557 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003558 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003559 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003560 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3561 // Use array's original type only if it has known number of
3562 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003563 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003564 PType = PVDecl->getType();
3565 } else if (PType->isFunctionType())
3566 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003567 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003568 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003569 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003570 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003571 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003572 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003573 }
3574}
3575
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003576/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003577/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003578/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3579/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003580/// Property attributes are stored as a comma-delimited C string. The simple
3581/// attributes readonly and bycopy are encoded as single characters. The
3582/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3583/// encoded as single characters, followed by an identifier. Property types
3584/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003585/// these attributes are defined by the following enumeration:
3586/// @code
3587/// enum PropertyAttributes {
3588/// kPropertyReadOnly = 'R', // property is read-only.
3589/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3590/// kPropertyByref = '&', // property is a reference to the value last assigned
3591/// kPropertyDynamic = 'D', // property is dynamic
3592/// kPropertyGetter = 'G', // followed by getter selector name
3593/// kPropertySetter = 'S', // followed by setter selector name
3594/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3595/// kPropertyType = 't' // followed by old-style type encoding.
3596/// kPropertyWeak = 'W' // 'weak' property
3597/// kPropertyStrong = 'P' // property GC'able
3598/// kPropertyNonAtomic = 'N' // property non-atomic
3599/// };
3600/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003601void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003602 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003603 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003604 // Collect information from the property implementation decl(s).
3605 bool Dynamic = false;
3606 ObjCPropertyImplDecl *SynthesizePID = 0;
3607
3608 // FIXME: Duplicated code due to poor abstraction.
3609 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003610 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003611 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3612 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003613 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003614 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003615 ObjCPropertyImplDecl *PID = *i;
3616 if (PID->getPropertyDecl() == PD) {
3617 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3618 Dynamic = true;
3619 } else {
3620 SynthesizePID = PID;
3621 }
3622 }
3623 }
3624 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003625 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003626 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003627 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003628 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003629 ObjCPropertyImplDecl *PID = *i;
3630 if (PID->getPropertyDecl() == PD) {
3631 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3632 Dynamic = true;
3633 } else {
3634 SynthesizePID = PID;
3635 }
3636 }
Mike Stump1eb44332009-09-09 15:08:12 +00003637 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003638 }
3639 }
3640
3641 // FIXME: This is not very efficient.
3642 S = "T";
3643
3644 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003645 // GCC has some special rules regarding encoding of properties which
3646 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003647 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003648 true /* outermost type */,
3649 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003650
3651 if (PD->isReadOnly()) {
3652 S += ",R";
3653 } else {
3654 switch (PD->getSetterKind()) {
3655 case ObjCPropertyDecl::Assign: break;
3656 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003657 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003658 }
3659 }
3660
3661 // It really isn't clear at all what this means, since properties
3662 // are "dynamic by default".
3663 if (Dynamic)
3664 S += ",D";
3665
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003666 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3667 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003669 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3670 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003671 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003672 }
3673
3674 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3675 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003676 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003677 }
3678
3679 if (SynthesizePID) {
3680 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3681 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003682 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003683 }
3684
3685 // FIXME: OBJCGC: weak & strong
3686}
3687
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003688/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003689/// Another legacy compatibility encoding: 32-bit longs are encoded as
3690/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003691/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3692///
3693void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003694 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003695 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003696 if (BT->getKind() == BuiltinType::ULong &&
3697 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003698 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003699 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003700 if (BT->getKind() == BuiltinType::Long &&
3701 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003702 PointeeTy = IntTy;
3703 }
3704 }
3705}
3706
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003707void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003708 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003709 // We follow the behavior of gcc, expanding structures which are
3710 // directly pointed to, and expanding embedded structures. Note that
3711 // these rules are sufficient to prevent recursive encoding of the
3712 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003713 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003714 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003715}
3716
David Chisnall64fd7e82010-06-04 01:10:52 +00003717static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3718 switch (T->getAs<BuiltinType>()->getKind()) {
3719 default: assert(0 && "Unhandled builtin type kind");
3720 case BuiltinType::Void: return 'v';
3721 case BuiltinType::Bool: return 'B';
3722 case BuiltinType::Char_U:
3723 case BuiltinType::UChar: return 'C';
3724 case BuiltinType::UShort: return 'S';
3725 case BuiltinType::UInt: return 'I';
3726 case BuiltinType::ULong:
3727 return
3728 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3729 case BuiltinType::UInt128: return 'T';
3730 case BuiltinType::ULongLong: return 'Q';
3731 case BuiltinType::Char_S:
3732 case BuiltinType::SChar: return 'c';
3733 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003734 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003735 case BuiltinType::Int: return 'i';
3736 case BuiltinType::Long:
3737 return
3738 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3739 case BuiltinType::LongLong: return 'q';
3740 case BuiltinType::Int128: return 't';
3741 case BuiltinType::Float: return 'f';
3742 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00003743 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00003744 }
3745}
3746
Mike Stump1eb44332009-09-09 15:08:12 +00003747static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003748 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003749 const Expr *E = FD->getBitWidth();
3750 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3751 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003752 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003753 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3754 // The GNU runtime requires more information; bitfields are encoded as b,
3755 // then the offset (in bits) of the first element, then the type of the
3756 // bitfield, then the size in bits. For example, in this structure:
3757 //
3758 // struct
3759 // {
3760 // int integer;
3761 // int flags:2;
3762 // };
3763 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3764 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3765 // information is not especially sensible, but we're stuck with it for
3766 // compatibility with GCC, although providing it breaks anything that
3767 // actually uses runtime introspection and wants to work on both runtimes...
3768 if (!Ctx->getLangOptions().NeXTRuntime) {
3769 const RecordDecl *RD = FD->getParent();
3770 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3771 // FIXME: This same linear search is also used in ExprConstant - it might
3772 // be better if the FieldDecl stored its offset. We'd be increasing the
3773 // size of the object slightly, but saving some time every time it is used.
3774 unsigned i = 0;
3775 for (RecordDecl::field_iterator Field = RD->field_begin(),
3776 FieldEnd = RD->field_end();
3777 Field != FieldEnd; (void)++Field, ++i) {
3778 if (*Field == FD)
3779 break;
3780 }
3781 S += llvm::utostr(RL.getFieldOffset(i));
3782 S += ObjCEncodingForPrimitiveKind(Context, T);
3783 }
3784 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003785 S += llvm::utostr(N);
3786}
3787
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003788// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003789void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3790 bool ExpandPointedToStructures,
3791 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003792 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003793 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003794 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003795 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003796 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003797 return EncodeBitField(this, S, T, FD);
3798 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003799 return;
3800 }
Mike Stump1eb44332009-09-09 15:08:12 +00003801
John McCall183700f2009-09-21 23:43:11 +00003802 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003803 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003804 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003805 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003806 return;
3807 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003808
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003809 // encoding for pointer or r3eference types.
3810 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003811 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003812 if (PT->isObjCSelType()) {
3813 S += ':';
3814 return;
3815 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003816 PointeeTy = PT->getPointeeType();
3817 }
3818 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3819 PointeeTy = RT->getPointeeType();
3820 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003821 bool isReadOnly = false;
3822 // For historical/compatibility reasons, the read-only qualifier of the
3823 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3824 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003825 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003826 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003827 if (OutermostType && T.isConstQualified()) {
3828 isReadOnly = true;
3829 S += 'r';
3830 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003831 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003832 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003833 while (P->getAs<PointerType>())
3834 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003835 if (P.isConstQualified()) {
3836 isReadOnly = true;
3837 S += 'r';
3838 }
3839 }
3840 if (isReadOnly) {
3841 // Another legacy compatibility encoding. Some ObjC qualifier and type
3842 // combinations need to be rearranged.
3843 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003844 if (llvm::StringRef(S).endswith("nr"))
3845 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003846 }
Mike Stump1eb44332009-09-09 15:08:12 +00003847
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003848 if (PointeeTy->isCharType()) {
3849 // char pointer types should be encoded as '*' unless it is a
3850 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003851 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003852 S += '*';
3853 return;
3854 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003855 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003856 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3857 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3858 S += '#';
3859 return;
3860 }
3861 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3862 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3863 S += '@';
3864 return;
3865 }
3866 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003867 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003868 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003869 getLegacyIntegralTypeEncoding(PointeeTy);
3870
Mike Stump1eb44332009-09-09 15:08:12 +00003871 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003872 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003873 return;
3874 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003875
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003876 if (const ArrayType *AT =
3877 // Ignore type qualifiers etc.
3878 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003879 if (isa<IncompleteArrayType>(AT)) {
3880 // Incomplete arrays are encoded as a pointer to the array element.
3881 S += '^';
3882
Mike Stump1eb44332009-09-09 15:08:12 +00003883 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003884 false, ExpandStructures, FD);
3885 } else {
3886 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003887
Anders Carlsson559a8332009-02-22 01:38:57 +00003888 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3889 S += llvm::utostr(CAT->getSize().getZExtValue());
3890 else {
3891 //Variable length arrays are encoded as a regular array with 0 elements.
3892 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3893 S += '0';
3894 }
Mike Stump1eb44332009-09-09 15:08:12 +00003895
3896 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003897 false, ExpandStructures, FD);
3898 S += ']';
3899 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003900 return;
3901 }
Mike Stump1eb44332009-09-09 15:08:12 +00003902
John McCall183700f2009-09-21 23:43:11 +00003903 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003904 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003905 return;
3906 }
Mike Stump1eb44332009-09-09 15:08:12 +00003907
Ted Kremenek6217b802009-07-29 21:53:49 +00003908 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003909 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003910 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003911 // Anonymous structures print as '?'
3912 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3913 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003914 if (ClassTemplateSpecializationDecl *Spec
3915 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3916 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3917 std::string TemplateArgsStr
3918 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003919 TemplateArgs.data(),
3920 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003921 (*this).PrintingPolicy);
3922
3923 S += TemplateArgsStr;
3924 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003925 } else {
3926 S += '?';
3927 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003928 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003929 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003930 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3931 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003932 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003933 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003934 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003935 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003936 S += '"';
3937 }
Mike Stump1eb44332009-09-09 15:08:12 +00003938
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003939 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003940 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003941 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003942 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003943 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003944 QualType qt = Field->getType();
3945 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003946 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003947 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003948 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003949 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003950 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003951 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003952 return;
3953 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00003954
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003955 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003956 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003957 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003958 else
3959 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003960 return;
3961 }
Mike Stump1eb44332009-09-09 15:08:12 +00003962
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003963 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003964 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003965 return;
3966 }
Mike Stump1eb44332009-09-09 15:08:12 +00003967
John McCallc12c5bb2010-05-15 11:32:37 +00003968 // Ignore protocol qualifiers when mangling at this level.
3969 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3970 T = OT->getBaseType();
3971
John McCall0953e762009-09-24 19:53:00 +00003972 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003973 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003974 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003975 S += '{';
3976 const IdentifierInfo *II = OI->getIdentifier();
3977 S += II->getName();
3978 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003979 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
3980 DeepCollectObjCIvars(OI, true, Ivars);
3981 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
3982 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
3983 if (Field->isBitField())
3984 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003985 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003986 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003987 }
3988 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003989 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003990 }
Mike Stump1eb44332009-09-09 15:08:12 +00003991
John McCall183700f2009-09-21 23:43:11 +00003992 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003993 if (OPT->isObjCIdType()) {
3994 S += '@';
3995 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003996 }
Mike Stump1eb44332009-09-09 15:08:12 +00003997
Steve Naroff27d20a22009-10-28 22:03:49 +00003998 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3999 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4000 // Since this is a binary compatibility issue, need to consult with runtime
4001 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004002 S += '#';
4003 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004004 }
Mike Stump1eb44332009-09-09 15:08:12 +00004005
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004006 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004007 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004008 ExpandPointedToStructures,
4009 ExpandStructures, FD);
4010 if (FD || EncodingProperty) {
4011 // Note that we do extended encoding of protocol qualifer list
4012 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004013 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004014 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4015 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004016 S += '<';
4017 S += (*I)->getNameAsString();
4018 S += '>';
4019 }
4020 S += '"';
4021 }
4022 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004023 }
Mike Stump1eb44332009-09-09 15:08:12 +00004024
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004025 QualType PointeeTy = OPT->getPointeeType();
4026 if (!EncodingProperty &&
4027 isa<TypedefType>(PointeeTy.getTypePtr())) {
4028 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004029 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004030 // {...};
4031 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004032 getObjCEncodingForTypeImpl(PointeeTy, S,
4033 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004034 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004035 return;
4036 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004037
4038 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004039 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004040 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004041 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004042 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4043 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004044 S += '<';
4045 S += (*I)->getNameAsString();
4046 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004047 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004048 S += '"';
4049 }
4050 return;
4051 }
Mike Stump1eb44332009-09-09 15:08:12 +00004052
John McCall532ec7b2010-05-17 23:56:34 +00004053 // gcc just blithely ignores member pointers.
4054 // TODO: maybe there should be a mangling for these
4055 if (T->getAs<MemberPointerType>())
4056 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004057
4058 if (T->isVectorType()) {
4059 // This matches gcc's encoding, even though technically it is
4060 // insufficient.
4061 // FIXME. We should do a better job than gcc.
4062 return;
4063 }
4064
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004065 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004066}
4067
Mike Stump1eb44332009-09-09 15:08:12 +00004068void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004069 std::string& S) const {
4070 if (QT & Decl::OBJC_TQ_In)
4071 S += 'n';
4072 if (QT & Decl::OBJC_TQ_Inout)
4073 S += 'N';
4074 if (QT & Decl::OBJC_TQ_Out)
4075 S += 'o';
4076 if (QT & Decl::OBJC_TQ_Bycopy)
4077 S += 'O';
4078 if (QT & Decl::OBJC_TQ_Byref)
4079 S += 'R';
4080 if (QT & Decl::OBJC_TQ_Oneway)
4081 S += 'V';
4082}
4083
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004084void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004085 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004086
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004087 BuiltinVaListType = T;
4088}
4089
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004090void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004091 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00004092}
4093
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004094void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004095 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004096}
4097
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004098void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004099 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004100}
4101
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004102void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004103 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004104}
4105
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004106void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004107 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004108 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004109
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004110 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004111}
4112
John McCall0bd6feb2009-12-02 08:04:21 +00004113/// \brief Retrieve the template name that corresponds to a non-empty
4114/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00004115TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4116 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00004117 unsigned size = End - Begin;
4118 assert(size > 1 && "set is not overloaded!");
4119
4120 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4121 size * sizeof(FunctionTemplateDecl*));
4122 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4123
4124 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004125 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004126 NamedDecl *D = *I;
4127 assert(isa<FunctionTemplateDecl>(D) ||
4128 (isa<UsingShadowDecl>(D) &&
4129 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4130 *Storage++ = D;
4131 }
4132
4133 return TemplateName(OT);
4134}
4135
Douglas Gregor7532dc62009-03-30 22:58:21 +00004136/// \brief Retrieve the template name that represents a qualified
4137/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00004138TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004139 bool TemplateKeyword,
4140 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004141 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004142 llvm::FoldingSetNodeID ID;
4143 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4144
4145 void *InsertPos = 0;
4146 QualifiedTemplateName *QTN =
4147 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4148 if (!QTN) {
4149 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4150 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4151 }
4152
4153 return TemplateName(QTN);
4154}
4155
4156/// \brief Retrieve the template name that represents a dependent
4157/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00004158TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004159 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004160 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004161 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004162
4163 llvm::FoldingSetNodeID ID;
4164 DependentTemplateName::Profile(ID, NNS, Name);
4165
4166 void *InsertPos = 0;
4167 DependentTemplateName *QTN =
4168 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4169
4170 if (QTN)
4171 return TemplateName(QTN);
4172
4173 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4174 if (CanonNNS == NNS) {
4175 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4176 } else {
4177 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4178 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004179 DependentTemplateName *CheckQTN =
4180 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4181 assert(!CheckQTN && "Dependent type name canonicalization broken");
4182 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004183 }
4184
4185 DependentTemplateNames.InsertNode(QTN, InsertPos);
4186 return TemplateName(QTN);
4187}
4188
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004189/// \brief Retrieve the template name that represents a dependent
4190/// template name such as \c MetaFun::template operator+.
4191TemplateName
4192ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4193 OverloadedOperatorKind Operator) {
4194 assert((!NNS || NNS->isDependent()) &&
4195 "Nested name specifier must be dependent");
4196
4197 llvm::FoldingSetNodeID ID;
4198 DependentTemplateName::Profile(ID, NNS, Operator);
4199
4200 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004201 DependentTemplateName *QTN
4202 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004203
4204 if (QTN)
4205 return TemplateName(QTN);
4206
4207 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4208 if (CanonNNS == NNS) {
4209 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4210 } else {
4211 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4212 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004213
4214 DependentTemplateName *CheckQTN
4215 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4216 assert(!CheckQTN && "Dependent template name canonicalization broken");
4217 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004218 }
4219
4220 DependentTemplateNames.InsertNode(QTN, InsertPos);
4221 return TemplateName(QTN);
4222}
4223
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004224/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004225/// TargetInfo, produce the corresponding type. The unsigned @p Type
4226/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004227CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004228 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004229 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004230 case TargetInfo::SignedShort: return ShortTy;
4231 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4232 case TargetInfo::SignedInt: return IntTy;
4233 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4234 case TargetInfo::SignedLong: return LongTy;
4235 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4236 case TargetInfo::SignedLongLong: return LongLongTy;
4237 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4238 }
4239
4240 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004241 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004242}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004243
4244//===----------------------------------------------------------------------===//
4245// Type Predicates.
4246//===----------------------------------------------------------------------===//
4247
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004248/// isObjCNSObjectType - Return true if this is an NSObject object using
4249/// NSObject attribute on a c-style pointer type.
4250/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004251/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004252///
4253bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4254 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4255 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004256 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004257 return true;
4258 }
Mike Stump1eb44332009-09-09 15:08:12 +00004259 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004260}
4261
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004262/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4263/// garbage collection attribute.
4264///
John McCall0953e762009-09-24 19:53:00 +00004265Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4266 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004267 if (getLangOptions().ObjC1 &&
4268 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004269 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004270 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004271 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004272 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004273 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004274 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004275 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004276 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004277 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004278 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004279 // Non-pointers have none gc'able attribute regardless of the attribute
4280 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004281 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004282 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004283 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004284 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004285}
4286
Chris Lattner6ac46a42008-04-07 06:51:04 +00004287//===----------------------------------------------------------------------===//
4288// Type Compatibility Testing
4289//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004290
Mike Stump1eb44332009-09-09 15:08:12 +00004291/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004292/// compatible.
4293static bool areCompatVectorTypes(const VectorType *LHS,
4294 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004295 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004296 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004297 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004298}
4299
Douglas Gregor255210e2010-08-06 10:14:59 +00004300bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4301 QualType SecondVec) {
4302 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4303 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4304
4305 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4306 return true;
4307
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004308 // Treat Neon vector types and most AltiVec vector types as if they are the
4309 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004310 const VectorType *First = FirstVec->getAs<VectorType>();
4311 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004312 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004313 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004314 First->getVectorKind() != VectorType::AltiVecPixel &&
4315 First->getVectorKind() != VectorType::AltiVecBool &&
4316 Second->getVectorKind() != VectorType::AltiVecPixel &&
4317 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004318 return true;
4319
4320 return false;
4321}
4322
Steve Naroff4084c302009-07-23 01:01:38 +00004323//===----------------------------------------------------------------------===//
4324// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4325//===----------------------------------------------------------------------===//
4326
4327/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4328/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004329bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4330 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004331 if (lProto == rProto)
4332 return true;
4333 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4334 E = rProto->protocol_end(); PI != E; ++PI)
4335 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4336 return true;
4337 return false;
4338}
4339
Steve Naroff4084c302009-07-23 01:01:38 +00004340/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4341/// return true if lhs's protocols conform to rhs's protocol; false
4342/// otherwise.
4343bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4344 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4345 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4346 return false;
4347}
4348
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004349/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4350/// Class<p1, ...>.
4351bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4352 QualType rhs) {
4353 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4354 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4355 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4356
4357 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4358 E = lhsQID->qual_end(); I != E; ++I) {
4359 bool match = false;
4360 ObjCProtocolDecl *lhsProto = *I;
4361 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4362 E = rhsOPT->qual_end(); J != E; ++J) {
4363 ObjCProtocolDecl *rhsProto = *J;
4364 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4365 match = true;
4366 break;
4367 }
4368 }
4369 if (!match)
4370 return false;
4371 }
4372 return true;
4373}
4374
Steve Naroff4084c302009-07-23 01:01:38 +00004375/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4376/// ObjCQualifiedIDType.
4377bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4378 bool compare) {
4379 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004380 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004381 lhs->isObjCIdType() || lhs->isObjCClassType())
4382 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004383 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004384 rhs->isObjCIdType() || rhs->isObjCClassType())
4385 return true;
4386
4387 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004388 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004389
Steve Naroff4084c302009-07-23 01:01:38 +00004390 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004391
Steve Naroff4084c302009-07-23 01:01:38 +00004392 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004393 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004394 // make sure we check the class hierarchy.
4395 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4396 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4397 E = lhsQID->qual_end(); I != E; ++I) {
4398 // when comparing an id<P> on lhs with a static type on rhs,
4399 // see if static class implements all of id's protocols, directly or
4400 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004401 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004402 return false;
4403 }
4404 }
4405 // If there are no qualifiers and no interface, we have an 'id'.
4406 return true;
4407 }
Mike Stump1eb44332009-09-09 15:08:12 +00004408 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004409 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4410 E = lhsQID->qual_end(); I != E; ++I) {
4411 ObjCProtocolDecl *lhsProto = *I;
4412 bool match = false;
4413
4414 // when comparing an id<P> on lhs with a static type on rhs,
4415 // see if static class implements all of id's protocols, directly or
4416 // through its super class and categories.
4417 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4418 E = rhsOPT->qual_end(); J != E; ++J) {
4419 ObjCProtocolDecl *rhsProto = *J;
4420 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4421 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4422 match = true;
4423 break;
4424 }
4425 }
Mike Stump1eb44332009-09-09 15:08:12 +00004426 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004427 // make sure we check the class hierarchy.
4428 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4429 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4430 E = lhsQID->qual_end(); I != E; ++I) {
4431 // when comparing an id<P> on lhs with a static type on rhs,
4432 // see if static class implements all of id's protocols, directly or
4433 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004434 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004435 match = true;
4436 break;
4437 }
4438 }
4439 }
4440 if (!match)
4441 return false;
4442 }
Mike Stump1eb44332009-09-09 15:08:12 +00004443
Steve Naroff4084c302009-07-23 01:01:38 +00004444 return true;
4445 }
Mike Stump1eb44332009-09-09 15:08:12 +00004446
Steve Naroff4084c302009-07-23 01:01:38 +00004447 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4448 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4449
Mike Stump1eb44332009-09-09 15:08:12 +00004450 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004451 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004452 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004453 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4454 E = lhsOPT->qual_end(); I != E; ++I) {
4455 ObjCProtocolDecl *lhsProto = *I;
4456 bool match = false;
4457
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004458 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00004459 // see if static class implements all of id's protocols, directly or
4460 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004461 // First, lhs protocols in the qualifier list must be found, direct
4462 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00004463 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4464 E = rhsQID->qual_end(); J != E; ++J) {
4465 ObjCProtocolDecl *rhsProto = *J;
4466 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4467 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4468 match = true;
4469 break;
4470 }
4471 }
4472 if (!match)
4473 return false;
4474 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004475
4476 // Static class's protocols, or its super class or category protocols
4477 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4478 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4479 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4480 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4481 // This is rather dubious but matches gcc's behavior. If lhs has
4482 // no type qualifier and its class has no static protocol(s)
4483 // assume that it is mismatch.
4484 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4485 return false;
4486 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4487 LHSInheritedProtocols.begin(),
4488 E = LHSInheritedProtocols.end(); I != E; ++I) {
4489 bool match = false;
4490 ObjCProtocolDecl *lhsProto = (*I);
4491 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4492 E = rhsQID->qual_end(); J != E; ++J) {
4493 ObjCProtocolDecl *rhsProto = *J;
4494 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4495 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4496 match = true;
4497 break;
4498 }
4499 }
4500 if (!match)
4501 return false;
4502 }
4503 }
Steve Naroff4084c302009-07-23 01:01:38 +00004504 return true;
4505 }
4506 return false;
4507}
4508
Eli Friedman3d815e72008-08-22 00:56:42 +00004509/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004510/// compatible for assignment from RHS to LHS. This handles validation of any
4511/// protocol qualifiers on the LHS or RHS.
4512///
Steve Naroff14108da2009-07-10 23:34:53 +00004513bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4514 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004515 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4516 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4517
Steve Naroffde2e22d2009-07-15 18:40:39 +00004518 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004519 if (LHS->isObjCUnqualifiedIdOrClass() ||
4520 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004521 return true;
4522
John McCallc12c5bb2010-05-15 11:32:37 +00004523 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004524 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4525 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004526 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004527
4528 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4529 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4530 QualType(RHSOPT,0));
4531
John McCallc12c5bb2010-05-15 11:32:37 +00004532 // If we have 2 user-defined types, fall into that path.
4533 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004534 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Steve Naroff4084c302009-07-23 01:01:38 +00004536 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004537}
4538
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004539/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4540/// for providing type-safty for objective-c pointers used to pass/return
4541/// arguments in block literals. When passed as arguments, passing 'A*' where
4542/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4543/// not OK. For the return type, the opposite is not OK.
4544bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4545 const ObjCObjectPointerType *LHSOPT,
4546 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004547 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004548 return true;
4549
4550 if (LHSOPT->isObjCBuiltinType()) {
4551 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4552 }
4553
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004554 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004555 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4556 QualType(RHSOPT,0),
4557 false);
4558
4559 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4560 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4561 if (LHS && RHS) { // We have 2 user-defined types.
4562 if (LHS != RHS) {
4563 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4564 return false;
4565 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4566 return true;
4567 }
4568 else
4569 return true;
4570 }
4571 return false;
4572}
4573
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004574/// getIntersectionOfProtocols - This routine finds the intersection of set
4575/// of protocols inherited from two distinct objective-c pointer objects.
4576/// It is used to build composite qualifier list of the composite type of
4577/// the conditional expression involving two objective-c pointer objects.
4578static
4579void getIntersectionOfProtocols(ASTContext &Context,
4580 const ObjCObjectPointerType *LHSOPT,
4581 const ObjCObjectPointerType *RHSOPT,
4582 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4583
John McCallc12c5bb2010-05-15 11:32:37 +00004584 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4585 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4586 assert(LHS->getInterface() && "LHS must have an interface base");
4587 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004588
4589 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4590 unsigned LHSNumProtocols = LHS->getNumProtocols();
4591 if (LHSNumProtocols > 0)
4592 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4593 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004594 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004595 Context.CollectInheritedProtocols(LHS->getInterface(),
4596 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004597 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4598 LHSInheritedProtocols.end());
4599 }
4600
4601 unsigned RHSNumProtocols = RHS->getNumProtocols();
4602 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004603 ObjCProtocolDecl **RHSProtocols =
4604 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004605 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4606 if (InheritedProtocolSet.count(RHSProtocols[i]))
4607 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4608 }
4609 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004610 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004611 Context.CollectInheritedProtocols(RHS->getInterface(),
4612 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004613 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4614 RHSInheritedProtocols.begin(),
4615 E = RHSInheritedProtocols.end(); I != E; ++I)
4616 if (InheritedProtocolSet.count((*I)))
4617 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004618 }
4619}
4620
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004621/// areCommonBaseCompatible - Returns common base class of the two classes if
4622/// one found. Note that this is O'2 algorithm. But it will be called as the
4623/// last type comparison in a ?-exp of ObjC pointer types before a
4624/// warning is issued. So, its invokation is extremely rare.
4625QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004626 const ObjCObjectPointerType *Lptr,
4627 const ObjCObjectPointerType *Rptr) {
4628 const ObjCObjectType *LHS = Lptr->getObjectType();
4629 const ObjCObjectType *RHS = Rptr->getObjectType();
4630 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4631 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4632 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004633 return QualType();
4634
John McCallc12c5bb2010-05-15 11:32:37 +00004635 while ((LDecl = LDecl->getSuperClass())) {
4636 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004637 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004638 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4639 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4640
4641 QualType Result = QualType(LHS, 0);
4642 if (!Protocols.empty())
4643 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4644 Result = getObjCObjectPointerType(Result);
4645 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004646 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004647 }
4648
4649 return QualType();
4650}
4651
John McCallc12c5bb2010-05-15 11:32:37 +00004652bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4653 const ObjCObjectType *RHS) {
4654 assert(LHS->getInterface() && "LHS is not an interface type");
4655 assert(RHS->getInterface() && "RHS is not an interface type");
4656
Chris Lattner6ac46a42008-04-07 06:51:04 +00004657 // Verify that the base decls are compatible: the RHS must be a subclass of
4658 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004659 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004660 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004661
Chris Lattner6ac46a42008-04-07 06:51:04 +00004662 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4663 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004664 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004665 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004666
Chris Lattner6ac46a42008-04-07 06:51:04 +00004667 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4668 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004669 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004670 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004671
John McCallc12c5bb2010-05-15 11:32:37 +00004672 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4673 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004674 LHSPI != LHSPE; LHSPI++) {
4675 bool RHSImplementsProtocol = false;
4676
4677 // If the RHS doesn't implement the protocol on the left, the types
4678 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004679 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4680 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004681 RHSPI != RHSPE; RHSPI++) {
4682 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004683 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004684 break;
4685 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004686 }
4687 // FIXME: For better diagnostics, consider passing back the protocol name.
4688 if (!RHSImplementsProtocol)
4689 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004690 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004691 // The RHS implements all protocols listed on the LHS.
4692 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004693}
4694
Steve Naroff389bf462009-02-12 17:52:19 +00004695bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4696 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004697 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4698 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004699
Steve Naroff14108da2009-07-10 23:34:53 +00004700 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004701 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004702
4703 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4704 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004705}
4706
Douglas Gregor569c3162010-08-07 11:51:51 +00004707bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4708 return canAssignObjCInterfaces(
4709 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4710 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4711}
4712
Mike Stump1eb44332009-09-09 15:08:12 +00004713/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004714/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004715/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004716/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00004717bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4718 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004719 if (getLangOptions().CPlusPlus)
4720 return hasSameType(LHS, RHS);
4721
Douglas Gregor447234d2010-07-29 15:18:02 +00004722 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00004723}
4724
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004725bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4726 return !mergeTypes(LHS, RHS, true).isNull();
4727}
4728
Peter Collingbourne48466752010-10-24 18:30:18 +00004729/// mergeTransparentUnionType - if T is a transparent union type and a member
4730/// of T is compatible with SubType, return the merged type, else return
4731/// QualType()
4732QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
4733 bool OfBlockPointer,
4734 bool Unqualified) {
4735 if (const RecordType *UT = T->getAsUnionType()) {
4736 RecordDecl *UD = UT->getDecl();
4737 if (UD->hasAttr<TransparentUnionAttr>()) {
4738 for (RecordDecl::field_iterator it = UD->field_begin(),
4739 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00004740 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00004741 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
4742 if (!MT.isNull())
4743 return MT;
4744 }
4745 }
4746 }
4747
4748 return QualType();
4749}
4750
4751/// mergeFunctionArgumentTypes - merge two types which appear as function
4752/// argument types
4753QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
4754 bool OfBlockPointer,
4755 bool Unqualified) {
4756 // GNU extension: two types are compatible if they appear as a function
4757 // argument, one of the types is a transparent union type and the other
4758 // type is compatible with a union member
4759 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
4760 Unqualified);
4761 if (!lmerge.isNull())
4762 return lmerge;
4763
4764 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
4765 Unqualified);
4766 if (!rmerge.isNull())
4767 return rmerge;
4768
4769 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
4770}
4771
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004772QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00004773 bool OfBlockPointer,
4774 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00004775 const FunctionType *lbase = lhs->getAs<FunctionType>();
4776 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004777 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4778 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004779 bool allLTypes = true;
4780 bool allRTypes = true;
4781
4782 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004783 QualType retType;
4784 if (OfBlockPointer)
Douglas Gregor447234d2010-07-29 15:18:02 +00004785 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4786 Unqualified);
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004787 else
John McCall8cc246c2010-12-15 01:06:38 +00004788 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
4789 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004790 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004791
4792 if (Unqualified)
4793 retType = retType.getUnqualifiedType();
4794
4795 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4796 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4797 if (Unqualified) {
4798 LRetType = LRetType.getUnqualifiedType();
4799 RRetType = RRetType.getUnqualifiedType();
4800 }
4801
4802 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004803 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00004804 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004805 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00004806
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004807 // FIXME: double check this
4808 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4809 // rbase->getRegParmAttr() != 0 &&
4810 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004811 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4812 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00004813
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004814 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00004815 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004816 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004817
John McCall8cc246c2010-12-15 01:06:38 +00004818 // Regparm is part of the calling convention.
4819 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
4820 return QualType();
4821
4822 // It's noreturn if either type is.
4823 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
4824 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4825 if (NoReturn != lbaseInfo.getNoReturn())
4826 allLTypes = false;
4827 if (NoReturn != rbaseInfo.getNoReturn())
4828 allRTypes = false;
4829
4830 FunctionType::ExtInfo einfo(NoReturn,
4831 lbaseInfo.getRegParm(),
4832 lbaseInfo.getCC());
John McCalle23cf432010-12-14 08:05:40 +00004833
Eli Friedman3d815e72008-08-22 00:56:42 +00004834 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004835 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4836 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004837 unsigned lproto_nargs = lproto->getNumArgs();
4838 unsigned rproto_nargs = rproto->getNumArgs();
4839
4840 // Compatible functions must have the same number of arguments
4841 if (lproto_nargs != rproto_nargs)
4842 return QualType();
4843
4844 // Variadic and non-variadic functions aren't compatible
4845 if (lproto->isVariadic() != rproto->isVariadic())
4846 return QualType();
4847
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004848 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4849 return QualType();
4850
Eli Friedman3d815e72008-08-22 00:56:42 +00004851 // Check argument compatibility
4852 llvm::SmallVector<QualType, 10> types;
4853 for (unsigned i = 0; i < lproto_nargs; i++) {
4854 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4855 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00004856 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
4857 OfBlockPointer,
4858 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004859 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004860
4861 if (Unqualified)
4862 argtype = argtype.getUnqualifiedType();
4863
Eli Friedman3d815e72008-08-22 00:56:42 +00004864 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00004865 if (Unqualified) {
4866 largtype = largtype.getUnqualifiedType();
4867 rargtype = rargtype.getUnqualifiedType();
4868 }
4869
Chris Lattner61710852008-10-05 17:34:18 +00004870 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4871 allLTypes = false;
4872 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4873 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004874 }
4875 if (allLTypes) return lhs;
4876 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00004877
4878 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
4879 EPI.ExtInfo = einfo;
4880 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00004881 }
4882
4883 if (lproto) allRTypes = false;
4884 if (rproto) allLTypes = false;
4885
Douglas Gregor72564e72009-02-26 23:50:07 +00004886 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004887 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004888 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004889 if (proto->isVariadic()) return QualType();
4890 // Check that the types are compatible with the types that
4891 // would result from default argument promotions (C99 6.7.5.3p15).
4892 // The only types actually affected are promotable integer
4893 // types and floats, which would be passed as a different
4894 // type depending on whether the prototype is visible.
4895 unsigned proto_nargs = proto->getNumArgs();
4896 for (unsigned i = 0; i < proto_nargs; ++i) {
4897 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004898
4899 // Look at the promotion type of enum types, since that is the type used
4900 // to pass enum values.
4901 if (const EnumType *Enum = argTy->getAs<EnumType>())
4902 argTy = Enum->getDecl()->getPromotionType();
4903
Eli Friedman3d815e72008-08-22 00:56:42 +00004904 if (argTy->isPromotableIntegerType() ||
4905 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4906 return QualType();
4907 }
4908
4909 if (allLTypes) return lhs;
4910 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00004911
4912 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
4913 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00004914 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004915 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00004916 }
4917
4918 if (allLTypes) return lhs;
4919 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00004920 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00004921}
4922
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004923QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00004924 bool OfBlockPointer,
4925 bool Unqualified) {
Bill Wendling43d69752007-12-03 07:33:35 +00004926 // C++ [expr]: If an expression initially has the type "reference to T", the
4927 // type is adjusted to "T" prior to any further analysis, the expression
4928 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004929 // expression is an lvalue unless the reference is an rvalue reference and
4930 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004931 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4932 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00004933
4934 if (Unqualified) {
4935 LHS = LHS.getUnqualifiedType();
4936 RHS = RHS.getUnqualifiedType();
4937 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004938
Eli Friedman3d815e72008-08-22 00:56:42 +00004939 QualType LHSCan = getCanonicalType(LHS),
4940 RHSCan = getCanonicalType(RHS);
4941
4942 // If two types are identical, they are compatible.
4943 if (LHSCan == RHSCan)
4944 return LHS;
4945
John McCall0953e762009-09-24 19:53:00 +00004946 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004947 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4948 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004949 if (LQuals != RQuals) {
4950 // If any of these qualifiers are different, we have a type
4951 // mismatch.
4952 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4953 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4954 return QualType();
4955
4956 // Exactly one GC qualifier difference is allowed: __strong is
4957 // okay if the other type has no GC qualifier but is an Objective
4958 // C object pointer (i.e. implicitly strong by default). We fix
4959 // this by pretending that the unqualified type was actually
4960 // qualified __strong.
4961 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4962 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4963 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4964
4965 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4966 return QualType();
4967
4968 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4969 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4970 }
4971 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4972 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4973 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004974 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004975 }
4976
4977 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004978
Eli Friedman852d63b2009-06-01 01:22:52 +00004979 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4980 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004981
Chris Lattner1adb8832008-01-14 05:45:46 +00004982 // We want to consider the two function types to be the same for these
4983 // comparisons, just force one to the other.
4984 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4985 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004986
4987 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004988 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4989 LHSClass = Type::ConstantArray;
4990 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4991 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004992
John McCallc12c5bb2010-05-15 11:32:37 +00004993 // ObjCInterfaces are just specialized ObjCObjects.
4994 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4995 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4996
Nate Begeman213541a2008-04-18 23:10:10 +00004997 // Canonicalize ExtVector -> Vector.
4998 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4999 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005000
Chris Lattnera36a61f2008-04-07 05:43:21 +00005001 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005002 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005003 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005004 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005005 // Compatibility is based on the underlying type, not the promotion
5006 // type.
John McCall183700f2009-09-21 23:43:11 +00005007 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005008 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5009 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005010 }
John McCall183700f2009-09-21 23:43:11 +00005011 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005012 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5013 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005014 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005015
Eli Friedman3d815e72008-08-22 00:56:42 +00005016 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005017 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005018
Steve Naroff4a746782008-01-09 22:43:08 +00005019 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005020 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005021#define TYPE(Class, Base)
5022#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005023#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005024#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5025#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5026#include "clang/AST/TypeNodes.def"
5027 assert(false && "Non-canonical and dependent types shouldn't get here");
5028 return QualType();
5029
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005030 case Type::LValueReference:
5031 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005032 case Type::MemberPointer:
5033 assert(false && "C++ should never be in mergeTypes");
5034 return QualType();
5035
John McCallc12c5bb2010-05-15 11:32:37 +00005036 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005037 case Type::IncompleteArray:
5038 case Type::VariableArray:
5039 case Type::FunctionProto:
5040 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005041 assert(false && "Types are eliminated above");
5042 return QualType();
5043
Chris Lattner1adb8832008-01-14 05:45:46 +00005044 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005045 {
5046 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005047 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5048 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005049 if (Unqualified) {
5050 LHSPointee = LHSPointee.getUnqualifiedType();
5051 RHSPointee = RHSPointee.getUnqualifiedType();
5052 }
5053 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5054 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005055 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005056 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005057 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005058 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005059 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005060 return getPointerType(ResultType);
5061 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005062 case Type::BlockPointer:
5063 {
5064 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005065 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5066 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005067 if (Unqualified) {
5068 LHSPointee = LHSPointee.getUnqualifiedType();
5069 RHSPointee = RHSPointee.getUnqualifiedType();
5070 }
5071 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5072 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005073 if (ResultType.isNull()) return QualType();
5074 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5075 return LHS;
5076 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5077 return RHS;
5078 return getBlockPointerType(ResultType);
5079 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005080 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005081 {
5082 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5083 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5084 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5085 return QualType();
5086
5087 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5088 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005089 if (Unqualified) {
5090 LHSElem = LHSElem.getUnqualifiedType();
5091 RHSElem = RHSElem.getUnqualifiedType();
5092 }
5093
5094 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005095 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005096 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5097 return LHS;
5098 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5099 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005100 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5101 ArrayType::ArraySizeModifier(), 0);
5102 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5103 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005104 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5105 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005106 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5107 return LHS;
5108 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5109 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005110 if (LVAT) {
5111 // FIXME: This isn't correct! But tricky to implement because
5112 // the array's size has to be the size of LHS, but the type
5113 // has to be different.
5114 return LHS;
5115 }
5116 if (RVAT) {
5117 // FIXME: This isn't correct! But tricky to implement because
5118 // the array's size has to be the size of RHS, but the type
5119 // has to be different.
5120 return RHS;
5121 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005122 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5123 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005124 return getIncompleteArrayType(ResultType,
5125 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005126 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005127 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005128 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005129 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005130 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005131 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005132 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005133 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005134 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005135 case Type::Complex:
5136 // Distinct complex types are incompatible.
5137 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005138 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005139 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005140 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5141 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005142 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005143 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005144 case Type::ObjCObject: {
5145 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005146 // FIXME: This should be type compatibility, e.g. whether
5147 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005148 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5149 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5150 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005151 return LHS;
5152
Eli Friedman3d815e72008-08-22 00:56:42 +00005153 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005154 }
Steve Naroff14108da2009-07-10 23:34:53 +00005155 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005156 if (OfBlockPointer) {
5157 if (canAssignObjCInterfacesInBlockPointer(
5158 LHS->getAs<ObjCObjectPointerType>(),
5159 RHS->getAs<ObjCObjectPointerType>()))
5160 return LHS;
5161 return QualType();
5162 }
John McCall183700f2009-09-21 23:43:11 +00005163 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5164 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005165 return LHS;
5166
Steve Naroffbc76dd02008-12-10 22:14:21 +00005167 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005168 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005169 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005170
5171 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005172}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005173
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005174/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5175/// 'RHS' attributes and returns the merged version; including for function
5176/// return types.
5177QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5178 QualType LHSCan = getCanonicalType(LHS),
5179 RHSCan = getCanonicalType(RHS);
5180 // If two types are identical, they are compatible.
5181 if (LHSCan == RHSCan)
5182 return LHS;
5183 if (RHSCan->isFunctionType()) {
5184 if (!LHSCan->isFunctionType())
5185 return QualType();
5186 QualType OldReturnType =
5187 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5188 QualType NewReturnType =
5189 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5190 QualType ResReturnType =
5191 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5192 if (ResReturnType.isNull())
5193 return QualType();
5194 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5195 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5196 // In either case, use OldReturnType to build the new function type.
5197 const FunctionType *F = LHS->getAs<FunctionType>();
5198 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005199 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5200 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005201 QualType ResultType
5202 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005203 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005204 return ResultType;
5205 }
5206 }
5207 return QualType();
5208 }
5209
5210 // If the qualifiers are different, the types can still be merged.
5211 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5212 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5213 if (LQuals != RQuals) {
5214 // If any of these qualifiers are different, we have a type mismatch.
5215 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5216 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5217 return QualType();
5218
5219 // Exactly one GC qualifier difference is allowed: __strong is
5220 // okay if the other type has no GC qualifier but is an Objective
5221 // C object pointer (i.e. implicitly strong by default). We fix
5222 // this by pretending that the unqualified type was actually
5223 // qualified __strong.
5224 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5225 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5226 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5227
5228 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5229 return QualType();
5230
5231 if (GC_L == Qualifiers::Strong)
5232 return LHS;
5233 if (GC_R == Qualifiers::Strong)
5234 return RHS;
5235 return QualType();
5236 }
5237
5238 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5239 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5240 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5241 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5242 if (ResQT == LHSBaseQT)
5243 return LHS;
5244 if (ResQT == RHSBaseQT)
5245 return RHS;
5246 }
5247 return QualType();
5248}
5249
Chris Lattner5426bf62008-04-07 07:01:58 +00005250//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005251// Integer Predicates
5252//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005253
Eli Friedmanad74a752008-06-28 06:23:08 +00005254unsigned ASTContext::getIntWidth(QualType T) {
John McCall842aef82009-12-09 09:09:27 +00005255 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005256 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005257 if (T->isBooleanType())
5258 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005259 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005260 return (unsigned)getTypeSize(T);
5261}
5262
5263QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005264 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005265
5266 // Turn <4 x signed int> -> <4 x unsigned int>
5267 if (const VectorType *VTy = T->getAs<VectorType>())
5268 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005269 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005270
5271 // For enums, we return the unsigned version of the base type.
5272 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005273 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005274
5275 const BuiltinType *BTy = T->getAs<BuiltinType>();
5276 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005277 switch (BTy->getKind()) {
5278 case BuiltinType::Char_S:
5279 case BuiltinType::SChar:
5280 return UnsignedCharTy;
5281 case BuiltinType::Short:
5282 return UnsignedShortTy;
5283 case BuiltinType::Int:
5284 return UnsignedIntTy;
5285 case BuiltinType::Long:
5286 return UnsignedLongTy;
5287 case BuiltinType::LongLong:
5288 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005289 case BuiltinType::Int128:
5290 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005291 default:
5292 assert(0 && "Unexpected signed integer type");
5293 return QualType();
5294 }
5295}
5296
Douglas Gregor2cf26342009-04-09 22:27:44 +00005297ExternalASTSource::~ExternalASTSource() { }
5298
5299void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005300
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005301ASTMutationListener::~ASTMutationListener() { }
5302
Chris Lattner86df27b2009-06-14 00:45:47 +00005303
5304//===----------------------------------------------------------------------===//
5305// Builtin Type Computation
5306//===----------------------------------------------------------------------===//
5307
5308/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00005309/// pointer over the consumed characters. This returns the resultant type. If
5310/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5311/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5312/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00005313///
5314/// RequiresICE is filled in on return to indicate whether the value is required
5315/// to be an Integer Constant Expression.
Mike Stump1eb44332009-09-09 15:08:12 +00005316static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005317 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00005318 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00005319 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005320 // Modifiers.
5321 int HowLong = 0;
5322 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00005323 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005324
Chris Lattner33daae62010-10-01 22:42:38 +00005325 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00005326 bool Done = false;
5327 while (!Done) {
5328 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005329 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005330 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00005331 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005332 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005333 case 'S':
5334 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5335 assert(!Signed && "Can't use 'S' modifier multiple times!");
5336 Signed = true;
5337 break;
5338 case 'U':
5339 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5340 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5341 Unsigned = true;
5342 break;
5343 case 'L':
5344 assert(HowLong <= 2 && "Can't have LLLL modifier");
5345 ++HowLong;
5346 break;
5347 }
5348 }
5349
5350 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005351
Chris Lattner86df27b2009-06-14 00:45:47 +00005352 // Read the base type.
5353 switch (*Str++) {
5354 default: assert(0 && "Unknown builtin type letter!");
5355 case 'v':
5356 assert(HowLong == 0 && !Signed && !Unsigned &&
5357 "Bad modifiers used with 'v'!");
5358 Type = Context.VoidTy;
5359 break;
5360 case 'f':
5361 assert(HowLong == 0 && !Signed && !Unsigned &&
5362 "Bad modifiers used with 'f'!");
5363 Type = Context.FloatTy;
5364 break;
5365 case 'd':
5366 assert(HowLong < 2 && !Signed && !Unsigned &&
5367 "Bad modifiers used with 'd'!");
5368 if (HowLong)
5369 Type = Context.LongDoubleTy;
5370 else
5371 Type = Context.DoubleTy;
5372 break;
5373 case 's':
5374 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5375 if (Unsigned)
5376 Type = Context.UnsignedShortTy;
5377 else
5378 Type = Context.ShortTy;
5379 break;
5380 case 'i':
5381 if (HowLong == 3)
5382 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5383 else if (HowLong == 2)
5384 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5385 else if (HowLong == 1)
5386 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5387 else
5388 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5389 break;
5390 case 'c':
5391 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5392 if (Signed)
5393 Type = Context.SignedCharTy;
5394 else if (Unsigned)
5395 Type = Context.UnsignedCharTy;
5396 else
5397 Type = Context.CharTy;
5398 break;
5399 case 'b': // boolean
5400 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5401 Type = Context.BoolTy;
5402 break;
5403 case 'z': // size_t.
5404 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5405 Type = Context.getSizeType();
5406 break;
5407 case 'F':
5408 Type = Context.getCFConstantStringType();
5409 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00005410 case 'G':
5411 Type = Context.getObjCIdType();
5412 break;
5413 case 'H':
5414 Type = Context.getObjCSelType();
5415 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005416 case 'a':
5417 Type = Context.getBuiltinVaListType();
5418 assert(!Type.isNull() && "builtin va list type not initialized!");
5419 break;
5420 case 'A':
5421 // This is a "reference" to a va_list; however, what exactly
5422 // this means depends on how va_list is defined. There are two
5423 // different kinds of va_list: ones passed by value, and ones
5424 // passed by reference. An example of a by-value va_list is
5425 // x86, where va_list is a char*. An example of by-ref va_list
5426 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5427 // we want this argument to be a char*&; for x86-64, we want
5428 // it to be a __va_list_tag*.
5429 Type = Context.getBuiltinVaListType();
5430 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00005431 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00005432 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00005433 else
Chris Lattner86df27b2009-06-14 00:45:47 +00005434 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005435 break;
5436 case 'V': {
5437 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005438 unsigned NumElements = strtoul(Str, &End, 10);
5439 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00005440 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005441
Chris Lattner14e0e742010-10-01 22:53:11 +00005442 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5443 RequiresICE, false);
5444 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00005445
5446 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005447 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00005448 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00005449 break;
5450 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005451 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00005452 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5453 false);
5454 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00005455 Type = Context.getComplexType(ElementType);
5456 break;
5457 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005458 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005459 Type = Context.getFILEType();
5460 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005461 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005462 return QualType();
5463 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005464 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005465 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005466 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005467 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005468 else
5469 Type = Context.getjmp_bufType();
5470
Mike Stumpfd612db2009-07-28 23:47:15 +00005471 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005472 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005473 return QualType();
5474 }
5475 break;
Mike Stump782fa302009-07-28 02:25:19 +00005476 }
Mike Stump1eb44332009-09-09 15:08:12 +00005477
Chris Lattner33daae62010-10-01 22:42:38 +00005478 // If there are modifiers and if we're allowed to parse them, go for it.
5479 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00005480 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005481 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00005482 default: Done = true; --Str; break;
5483 case '*':
5484 case '&': {
5485 // Both pointers and references can have their pointee types
5486 // qualified with an address space.
5487 char *End;
5488 unsigned AddrSpace = strtoul(Str, &End, 10);
5489 if (End != Str && AddrSpace != 0) {
5490 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5491 Str = End;
5492 }
5493 if (c == '*')
5494 Type = Context.getPointerType(Type);
5495 else
5496 Type = Context.getLValueReferenceType(Type);
5497 break;
5498 }
5499 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5500 case 'C':
5501 Type = Type.withConst();
5502 break;
5503 case 'D':
5504 Type = Context.getVolatileType(Type);
5505 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005506 }
5507 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00005508
Chris Lattner14e0e742010-10-01 22:53:11 +00005509 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00005510 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00005511
Chris Lattner86df27b2009-06-14 00:45:47 +00005512 return Type;
5513}
5514
5515/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00005516QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00005517 GetBuiltinTypeError &Error,
5518 unsigned *IntegerConstantArgs) {
Chris Lattner33daae62010-10-01 22:42:38 +00005519 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00005520
Chris Lattner86df27b2009-06-14 00:45:47 +00005521 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005522
Chris Lattner14e0e742010-10-01 22:53:11 +00005523 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00005524 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00005525 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5526 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005527 if (Error != GE_None)
5528 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00005529
5530 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5531
Chris Lattner86df27b2009-06-14 00:45:47 +00005532 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00005533 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005534 if (Error != GE_None)
5535 return QualType();
5536
Chris Lattner14e0e742010-10-01 22:53:11 +00005537 // If this argument is required to be an IntegerConstantExpression and the
5538 // caller cares, fill in the bitmask we return.
5539 if (RequiresICE && IntegerConstantArgs)
5540 *IntegerConstantArgs |= 1 << ArgTypes.size();
5541
Chris Lattner86df27b2009-06-14 00:45:47 +00005542 // Do array -> pointer decay. The builtin should use the decayed type.
5543 if (Ty->isArrayType())
5544 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005545
Chris Lattner86df27b2009-06-14 00:45:47 +00005546 ArgTypes.push_back(Ty);
5547 }
5548
5549 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5550 "'.' should only occur at end of builtin type list!");
5551
John McCall00ccbef2010-12-21 00:44:39 +00005552 FunctionType::ExtInfo EI;
5553 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5554
5555 bool Variadic = (TypeStr[0] == '.');
5556
5557 // We really shouldn't be making a no-proto type here, especially in C++.
5558 if (ArgTypes.empty() && Variadic)
5559 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005560
John McCalle23cf432010-12-14 08:05:40 +00005561 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00005562 EPI.ExtInfo = EI;
5563 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00005564
5565 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00005566}
Eli Friedmana95d7572009-08-19 07:44:53 +00005567
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005568GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5569 GVALinkage External = GVA_StrongExternal;
5570
5571 Linkage L = FD->getLinkage();
5572 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5573 FD->getType()->getLinkage() == UniqueExternalLinkage)
5574 L = UniqueExternalLinkage;
5575
5576 switch (L) {
5577 case NoLinkage:
5578 case InternalLinkage:
5579 case UniqueExternalLinkage:
5580 return GVA_Internal;
5581
5582 case ExternalLinkage:
5583 switch (FD->getTemplateSpecializationKind()) {
5584 case TSK_Undeclared:
5585 case TSK_ExplicitSpecialization:
5586 External = GVA_StrongExternal;
5587 break;
5588
5589 case TSK_ExplicitInstantiationDefinition:
5590 return GVA_ExplicitTemplateInstantiation;
5591
5592 case TSK_ExplicitInstantiationDeclaration:
5593 case TSK_ImplicitInstantiation:
5594 External = GVA_TemplateInstantiation;
5595 break;
5596 }
5597 }
5598
5599 if (!FD->isInlined())
5600 return External;
5601
5602 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5603 // GNU or C99 inline semantics. Determine whether this symbol should be
5604 // externally visible.
5605 if (FD->isInlineDefinitionExternallyVisible())
5606 return External;
5607
5608 // C99 inline semantics, where the symbol is not externally visible.
5609 return GVA_C99Inline;
5610 }
5611
5612 // C++0x [temp.explicit]p9:
5613 // [ Note: The intent is that an inline function that is the subject of
5614 // an explicit instantiation declaration will still be implicitly
5615 // instantiated when used so that the body can be considered for
5616 // inlining, but that no out-of-line copy of the inline function would be
5617 // generated in the translation unit. -- end note ]
5618 if (FD->getTemplateSpecializationKind()
5619 == TSK_ExplicitInstantiationDeclaration)
5620 return GVA_C99Inline;
5621
5622 return GVA_CXXInline;
5623}
5624
5625GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5626 // If this is a static data member, compute the kind of template
5627 // specialization. Otherwise, this variable is not part of a
5628 // template.
5629 TemplateSpecializationKind TSK = TSK_Undeclared;
5630 if (VD->isStaticDataMember())
5631 TSK = VD->getTemplateSpecializationKind();
5632
5633 Linkage L = VD->getLinkage();
5634 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5635 VD->getType()->getLinkage() == UniqueExternalLinkage)
5636 L = UniqueExternalLinkage;
5637
5638 switch (L) {
5639 case NoLinkage:
5640 case InternalLinkage:
5641 case UniqueExternalLinkage:
5642 return GVA_Internal;
5643
5644 case ExternalLinkage:
5645 switch (TSK) {
5646 case TSK_Undeclared:
5647 case TSK_ExplicitSpecialization:
5648 return GVA_StrongExternal;
5649
5650 case TSK_ExplicitInstantiationDeclaration:
5651 llvm_unreachable("Variable should not be instantiated");
5652 // Fall through to treat this like any other instantiation.
5653
5654 case TSK_ExplicitInstantiationDefinition:
5655 return GVA_ExplicitTemplateInstantiation;
5656
5657 case TSK_ImplicitInstantiation:
5658 return GVA_TemplateInstantiation;
5659 }
5660 }
5661
5662 return GVA_StrongExternal;
5663}
5664
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00005665bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005666 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5667 if (!VD->isFileVarDecl())
5668 return false;
5669 } else if (!isa<FunctionDecl>(D))
5670 return false;
5671
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005672 // Weak references don't produce any output by themselves.
5673 if (D->hasAttr<WeakRefAttr>())
5674 return false;
5675
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005676 // Aliases and used decls are required.
5677 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5678 return true;
5679
5680 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5681 // Forward declarations aren't required.
5682 if (!FD->isThisDeclarationADefinition())
5683 return false;
5684
5685 // Constructors and destructors are required.
5686 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5687 return true;
5688
5689 // The key function for a class is required.
5690 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5691 const CXXRecordDecl *RD = MD->getParent();
5692 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5693 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5694 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5695 return true;
5696 }
5697 }
5698
5699 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5700
5701 // static, static inline, always_inline, and extern inline functions can
5702 // always be deferred. Normal inline functions can be deferred in C99/C++.
5703 // Implicit template instantiations can also be deferred in C++.
5704 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5705 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5706 return false;
5707 return true;
5708 }
5709
5710 const VarDecl *VD = cast<VarDecl>(D);
5711 assert(VD->isFileVarDecl() && "Expected file scoped var");
5712
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005713 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5714 return false;
5715
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005716 // Structs that have non-trivial constructors or destructors are required.
5717
5718 // FIXME: Handle references.
5719 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5720 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005721 if (RD->hasDefinition() &&
5722 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005723 return true;
5724 }
5725 }
5726
5727 GVALinkage L = GetGVALinkageForVariable(VD);
5728 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5729 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5730 return false;
5731 }
5732
5733 return true;
5734}
Charles Davis071cc7d2010-08-16 03:33:14 +00005735
Charles Davisee743f92010-11-09 18:04:24 +00005736CallingConv ASTContext::getDefaultMethodCallConv() {
5737 // Pass through to the C++ ABI object
5738 return ABI->getDefaultMethodCallConv();
5739}
5740
Anders Carlssondae0cb52010-11-25 01:51:53 +00005741bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) {
5742 // Pass through to the C++ ABI object
5743 return ABI->isNearlyEmpty(RD);
5744}
5745
Charles Davis071cc7d2010-08-16 03:33:14 +00005746CXXABI::~CXXABI() {}