blob: 90279d8db1a5488fdef1e1dbf56ba1fa1a19cf9c [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()),
112 0));
113 else
114 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
115 cast<TemplateTemplateParmDecl>(*P)));
116 }
117
118 TemplateTemplateParmDecl *CanonTTP
119 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
120 SourceLocation(), TTP->getDepth(),
121 TTP->getPosition(), 0,
122 TemplateParameterList::Create(*this, SourceLocation(),
123 SourceLocation(),
124 CanonParams.data(),
125 CanonParams.size(),
126 SourceLocation()));
127
128 // Get the new insert position for the node we care about.
129 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
130 assert(Canonical == 0 && "Shouldn't be in the map!");
131 (void)Canonical;
132
133 // Create the canonical template template parameter entry.
134 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
135 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
136 return CanonTTP;
137}
138
Charles Davis071cc7d2010-08-16 03:33:14 +0000139CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000140 if (!LangOpts.CPlusPlus) return 0;
141
Charles Davis20cf7172010-08-19 02:18:14 +0000142 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000143 case CXXABI_ARM:
144 return CreateARMCXXABI(*this);
145 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000146 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000147 case CXXABI_Microsoft:
148 return CreateMicrosoftCXXABI(*this);
149 }
John McCallee79a4c2010-08-21 22:46:04 +0000150 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000151}
152
Chris Lattner61710852008-10-05 17:34:18 +0000153ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000154 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000155 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000156 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000157 unsigned size_reserve) :
John McCallef990012010-06-11 11:07:21 +0000158 TemplateSpecializationTypes(this_()),
159 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000160 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
161 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000162 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000163 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCallbf1a0282010-06-04 23:28:52 +0000164 NullTypeSourceInfo(QualType()),
Charles Davis071cc7d2010-08-16 03:33:14 +0000165 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000166 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000167 BuiltinInfo(builtins),
168 DeclarationNames(*this),
Argyrios Kyrtzidis9a44b5f2010-10-28 09:29:35 +0000169 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000170 LastSDM(0, 0),
171 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000172 ObjCIdRedefinitionType = QualType();
173 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000174 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000175 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000176 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000177 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000178}
179
Reid Spencer5f016e22007-07-11 17:01:13 +0000180ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000181 // Release the DenseMaps associated with DeclContext objects.
182 // FIXME: Is this the ideal solution?
183 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000184
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000185 // Call all of the deallocation functions.
186 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
187 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000188
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000189 // Release all of the memory associated with overridden C++ methods.
190 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
191 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
192 OM != OMEnd; ++OM)
193 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000194
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000195 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000196 // because they can contain DenseMaps.
197 for (llvm::DenseMap<const ObjCContainerDecl*,
198 const ASTRecordLayout*>::iterator
199 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
200 // Increment in loop to prevent using deallocated memory.
201 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
202 R->Destroy(*this);
203
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000204 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
205 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
206 // Increment in loop to prevent using deallocated memory.
207 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
208 R->Destroy(*this);
209 }
Douglas Gregor63200642010-08-30 16:49:28 +0000210
211 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
212 AEnd = DeclAttrs.end();
213 A != AEnd; ++A)
214 A->second->~AttrVec();
215}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000216
Douglas Gregor00545312010-05-23 18:26:36 +0000217void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
218 Deallocations.push_back(std::make_pair(Callback, Data));
219}
220
Mike Stump1eb44332009-09-09 15:08:12 +0000221void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000222ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
223 ExternalSource.reset(Source.take());
224}
225
Reid Spencer5f016e22007-07-11 17:01:13 +0000226void ASTContext::PrintStats() const {
227 fprintf(stderr, "*** AST Context Stats:\n");
228 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000229
Douglas Gregordbe833d2009-05-26 14:40:08 +0000230 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000231#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000232#define ABSTRACT_TYPE(Name, Parent)
233#include "clang/AST/TypeNodes.def"
234 0 // Extra
235 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000236
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
238 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000239 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000240 }
241
Douglas Gregordbe833d2009-05-26 14:40:08 +0000242 unsigned Idx = 0;
243 unsigned TotalBytes = 0;
244#define TYPE(Name, Parent) \
245 if (counts[Idx]) \
246 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
247 TotalBytes += counts[Idx] * sizeof(Name##Type); \
248 ++Idx;
249#define ABSTRACT_TYPE(Name, Parent)
250#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Douglas Gregordbe833d2009-05-26 14:40:08 +0000252 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000253
Douglas Gregor4923aa22010-07-02 20:37:36 +0000254 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000255 fprintf(stderr, " %u/%u implicit default constructors created\n",
256 NumImplicitDefaultConstructorsDeclared,
257 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000258 fprintf(stderr, " %u/%u implicit copy constructors created\n",
259 NumImplicitCopyConstructorsDeclared,
260 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000261 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
262 NumImplicitCopyAssignmentOperatorsDeclared,
263 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000264 fprintf(stderr, " %u/%u implicit destructors created\n",
265 NumImplicitDestructorsDeclared, NumImplicitDestructors);
266
Douglas Gregor2cf26342009-04-09 22:27:44 +0000267 if (ExternalSource.get()) {
268 fprintf(stderr, "\n");
269 ExternalSource->PrintStats();
270 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000271
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000272 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000273}
274
275
John McCalle27ec8a2009-10-23 23:03:21 +0000276void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000277 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000278 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000279 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000280}
281
Reid Spencer5f016e22007-07-11 17:01:13 +0000282void ASTContext::InitBuiltinTypes() {
283 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 // C99 6.2.5p19.
286 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000287
Reid Spencer5f016e22007-07-11 17:01:13 +0000288 // C99 6.2.5p2.
289 InitBuiltinType(BoolTy, BuiltinType::Bool);
290 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000291 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000292 InitBuiltinType(CharTy, BuiltinType::Char_S);
293 else
294 InitBuiltinType(CharTy, BuiltinType::Char_U);
295 // C99 6.2.5p4.
296 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
297 InitBuiltinType(ShortTy, BuiltinType::Short);
298 InitBuiltinType(IntTy, BuiltinType::Int);
299 InitBuiltinType(LongTy, BuiltinType::Long);
300 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 // C99 6.2.5p6.
303 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
304 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
305 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
306 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
307 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 // C99 6.2.5p10.
310 InitBuiltinType(FloatTy, BuiltinType::Float);
311 InitBuiltinType(DoubleTy, BuiltinType::Double);
312 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000313
Chris Lattner2df9ced2009-04-30 02:43:43 +0000314 // GNU extension, 128-bit integers.
315 InitBuiltinType(Int128Ty, BuiltinType::Int128);
316 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
317
Chris Lattner3a250322009-02-26 23:43:47 +0000318 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
319 InitBuiltinType(WCharTy, BuiltinType::WChar);
320 else // C99
321 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000322
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000323 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
324 InitBuiltinType(Char16Ty, BuiltinType::Char16);
325 else // C99
326 Char16Ty = getFromTargetType(Target.getChar16Type());
327
328 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
329 InitBuiltinType(Char32Ty, BuiltinType::Char32);
330 else // C99
331 Char32Ty = getFromTargetType(Target.getChar32Type());
332
Douglas Gregor898574e2008-12-05 23:32:09 +0000333 // Placeholder type for type-dependent expressions whose type is
334 // completely unknown. No code should ever check a type against
335 // DependentTy and users should never see it; however, it is here to
336 // help diagnose failures to properly check for type-dependent
337 // expressions.
338 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000339
John McCall2a984ca2010-10-12 00:20:44 +0000340 // Placeholder type for functions.
341 InitBuiltinType(OverloadTy, BuiltinType::Overload);
342
Mike Stump1eb44332009-09-09 15:08:12 +0000343 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000344 // not yet been deduced.
John McCall2a984ca2010-10-12 00:20:44 +0000345 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 // C99 6.2.5p11.
348 FloatComplexTy = getComplexType(FloatTy);
349 DoubleComplexTy = getComplexType(DoubleTy);
350 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000351
Steve Naroff7e219e42007-10-15 14:41:52 +0000352 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Steve Naroffde2e22d2009-07-15 18:40:39 +0000354 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
355 ObjCIdTypedefType = QualType();
356 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000357 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000359 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000360 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
361 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000362 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000363
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000364 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000366 // void * type
367 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000368
369 // nullptr type (C++0x 2.14.7)
370 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000371}
372
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000373Diagnostic &ASTContext::getDiagnostics() const {
374 return SourceMgr.getDiagnostics();
375}
376
Douglas Gregor63200642010-08-30 16:49:28 +0000377AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
378 AttrVec *&Result = DeclAttrs[D];
379 if (!Result) {
380 void *Mem = Allocate(sizeof(AttrVec));
381 Result = new (Mem) AttrVec;
382 }
383
384 return *Result;
385}
386
387/// \brief Erase the attributes corresponding to the given declaration.
388void ASTContext::eraseDeclAttrs(const Decl *D) {
389 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
390 if (Pos != DeclAttrs.end()) {
391 Pos->second->~AttrVec();
392 DeclAttrs.erase(Pos);
393 }
394}
395
396
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000397MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000398ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000399 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000400 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000401 = InstantiatedFromStaticDataMember.find(Var);
402 if (Pos == InstantiatedFromStaticDataMember.end())
403 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Douglas Gregor7caa6822009-07-24 20:34:43 +0000405 return Pos->second;
406}
407
Mike Stump1eb44332009-09-09 15:08:12 +0000408void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000409ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000410 TemplateSpecializationKind TSK,
411 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000412 assert(Inst->isStaticDataMember() && "Not a static data member");
413 assert(Tmpl->isStaticDataMember() && "Not a static data member");
414 assert(!InstantiatedFromStaticDataMember[Inst] &&
415 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000416 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000417 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000418}
419
John McCall7ba107a2009-11-18 02:36:19 +0000420NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000421ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000422 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000423 = InstantiatedFromUsingDecl.find(UUD);
424 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000425 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Anders Carlsson0d8df782009-08-29 19:37:28 +0000427 return Pos->second;
428}
429
430void
John McCalled976492009-12-04 22:46:56 +0000431ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
432 assert((isa<UsingDecl>(Pattern) ||
433 isa<UnresolvedUsingValueDecl>(Pattern) ||
434 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
435 "pattern decl is not a using decl");
436 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
437 InstantiatedFromUsingDecl[Inst] = Pattern;
438}
439
440UsingShadowDecl *
441ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
442 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
443 = InstantiatedFromUsingShadowDecl.find(Inst);
444 if (Pos == InstantiatedFromUsingShadowDecl.end())
445 return 0;
446
447 return Pos->second;
448}
449
450void
451ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
452 UsingShadowDecl *Pattern) {
453 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
454 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000455}
456
Anders Carlssond8b285f2009-09-01 04:26:58 +0000457FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
458 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
459 = InstantiatedFromUnnamedFieldDecl.find(Field);
460 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
461 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Anders Carlssond8b285f2009-09-01 04:26:58 +0000463 return Pos->second;
464}
465
466void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
467 FieldDecl *Tmpl) {
468 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
469 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
470 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
471 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Anders Carlssond8b285f2009-09-01 04:26:58 +0000473 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
474}
475
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000476ASTContext::overridden_cxx_method_iterator
477ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
478 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
479 = OverriddenMethods.find(Method);
480 if (Pos == OverriddenMethods.end())
481 return 0;
482
483 return Pos->second.begin();
484}
485
486ASTContext::overridden_cxx_method_iterator
487ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
488 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
489 = OverriddenMethods.find(Method);
490 if (Pos == OverriddenMethods.end())
491 return 0;
492
493 return Pos->second.end();
494}
495
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000496unsigned
497ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
498 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
499 = OverriddenMethods.find(Method);
500 if (Pos == OverriddenMethods.end())
501 return 0;
502
503 return Pos->second.size();
504}
505
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000506void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
507 const CXXMethodDecl *Overridden) {
508 OverriddenMethods[Method].push_back(Overridden);
509}
510
Chris Lattner464175b2007-07-18 17:52:12 +0000511//===----------------------------------------------------------------------===//
512// Type Sizing and Analysis
513//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000514
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000515/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
516/// scalar floating point type.
517const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000518 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000519 assert(BT && "Not a floating point type!");
520 switch (BT->getKind()) {
521 default: assert(0 && "Not a floating point type!");
522 case BuiltinType::Float: return Target.getFloatFormat();
523 case BuiltinType::Double: return Target.getDoubleFormat();
524 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
525 }
526}
527
Ken Dyck8b752f12010-01-27 17:10:57 +0000528/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000529/// specified decl. Note that bitfields do not have a valid alignment, so
530/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000531/// If @p RefAsPointee, references are treated like their underlying type
532/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000533CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000534 unsigned Align = Target.getCharWidth();
535
John McCall4081a5c2010-10-08 18:24:19 +0000536 bool UseAlignAttrOnly = false;
537 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
538 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000539
John McCall4081a5c2010-10-08 18:24:19 +0000540 // __attribute__((aligned)) can increase or decrease alignment
541 // *except* on a struct or struct member, where it only increases
542 // alignment unless 'packed' is also specified.
543 //
544 // It is an error for [[align]] to decrease alignment, so we can
545 // ignore that possibility; Sema should diagnose it.
546 if (isa<FieldDecl>(D)) {
547 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
548 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
549 } else {
550 UseAlignAttrOnly = true;
551 }
552 }
553
554 if (UseAlignAttrOnly) {
555 // ignore type of value
556 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000557 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000558 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000559 if (RefAsPointee)
560 T = RT->getPointeeType();
561 else
562 T = getPointerType(RT->getPointeeType());
563 }
564 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindola6deecb02010-06-04 23:15:27 +0000565 unsigned MinWidth = Target.getLargeArrayMinWidth();
566 unsigned ArrayAlign = Target.getLargeArrayAlign();
567 if (isa<VariableArrayType>(T) && MinWidth != 0)
568 Align = std::max(Align, ArrayAlign);
569 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
570 unsigned Size = getTypeSize(CT);
571 if (MinWidth != 0 && MinWidth <= Size)
572 Align = std::max(Align, ArrayAlign);
573 }
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000574 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000575 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
576 T = cast<ArrayType>(T)->getElementType();
577
578 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
579 }
Charles Davis05f62472010-02-23 04:52:00 +0000580 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
581 // In the case of a field in a packed struct, we want the minimum
582 // of the alignment of the field and the alignment of the struct.
583 Align = std::min(Align,
584 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
585 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000586 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000587
Ken Dyck8b752f12010-01-27 17:10:57 +0000588 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000589}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000590
John McCallea1471e2010-05-20 01:18:31 +0000591std::pair<CharUnits, CharUnits>
592ASTContext::getTypeInfoInChars(const Type *T) {
593 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
594 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
595 CharUnits::fromQuantity(Info.second / getCharWidth()));
596}
597
598std::pair<CharUnits, CharUnits>
599ASTContext::getTypeInfoInChars(QualType T) {
600 return getTypeInfoInChars(T.getTypePtr());
601}
602
Chris Lattnera7674d82007-07-13 22:13:22 +0000603/// getTypeSize - Return the size of the specified type, in bits. This method
604/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000605///
606/// FIXME: Pointers into different addr spaces could have different sizes and
607/// alignment requirements: getPointerInfo should take an AddrSpace, this
608/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000609std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000610ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000611 uint64_t Width=0;
612 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000613 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000614#define TYPE(Class, Base)
615#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000616#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000617#define DEPENDENT_TYPE(Class, Base) case Type::Class:
618#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000619 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000620 break;
621
Chris Lattner692233e2007-07-13 22:27:08 +0000622 case Type::FunctionNoProto:
623 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000624 // GCC extension: alignof(function) = 32 bits
625 Width = 0;
626 Align = 32;
627 break;
628
Douglas Gregor72564e72009-02-26 23:50:07 +0000629 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000630 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000631 Width = 0;
632 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
633 break;
634
Steve Narofffb22d962007-08-30 01:06:46 +0000635 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000636 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Chris Lattner98be4942008-03-05 18:54:05 +0000638 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000639 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000640 Align = EltInfo.second;
641 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000642 }
Nate Begeman213541a2008-04-18 23:10:10 +0000643 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000644 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000645 const VectorType *VT = cast<VectorType>(T);
646 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
647 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000648 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000649 // If the alignment is not a power of 2, round up to the next power of 2.
650 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000651 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000652 Align = llvm::NextPowerOf2(Align);
653 Width = llvm::RoundUpToAlignment(Width, Align);
654 }
Chris Lattner030d8842007-07-19 22:06:24 +0000655 break;
656 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000657
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000658 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000659 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000660 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000661 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000662 // GCC extension: alignof(void) = 8 bits.
663 Width = 0;
664 Align = 8;
665 break;
666
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000667 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000668 Width = Target.getBoolWidth();
669 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000670 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000671 case BuiltinType::Char_S:
672 case BuiltinType::Char_U:
673 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000674 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000675 Width = Target.getCharWidth();
676 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000677 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000678 case BuiltinType::WChar:
679 Width = Target.getWCharWidth();
680 Align = Target.getWCharAlign();
681 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000682 case BuiltinType::Char16:
683 Width = Target.getChar16Width();
684 Align = Target.getChar16Align();
685 break;
686 case BuiltinType::Char32:
687 Width = Target.getChar32Width();
688 Align = Target.getChar32Align();
689 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000690 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000691 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000692 Width = Target.getShortWidth();
693 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000694 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000695 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000696 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000697 Width = Target.getIntWidth();
698 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000699 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000700 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000701 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000702 Width = Target.getLongWidth();
703 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000704 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000705 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000706 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000707 Width = Target.getLongLongWidth();
708 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000709 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000710 case BuiltinType::Int128:
711 case BuiltinType::UInt128:
712 Width = 128;
713 Align = 128; // int128_t is 128-bit aligned on all targets.
714 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000715 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000716 Width = Target.getFloatWidth();
717 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000718 break;
719 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000720 Width = Target.getDoubleWidth();
721 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000722 break;
723 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000724 Width = Target.getLongDoubleWidth();
725 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000726 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000727 case BuiltinType::NullPtr:
728 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
729 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000730 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000731 case BuiltinType::ObjCId:
732 case BuiltinType::ObjCClass:
733 case BuiltinType::ObjCSel:
734 Width = Target.getPointerWidth(0);
735 Align = Target.getPointerAlign(0);
736 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000737 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000738 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000739 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000740 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000741 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000742 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000743 case Type::BlockPointer: {
744 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
745 Width = Target.getPointerWidth(AS);
746 Align = Target.getPointerAlign(AS);
747 break;
748 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000749 case Type::LValueReference:
750 case Type::RValueReference: {
751 // alignof and sizeof should never enter this code path here, so we go
752 // the pointer route.
753 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
754 Width = Target.getPointerWidth(AS);
755 Align = Target.getPointerAlign(AS);
756 break;
757 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000758 case Type::Pointer: {
759 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000760 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000761 Align = Target.getPointerAlign(AS);
762 break;
763 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000764 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000765 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000766 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000767 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000768 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000769 Align = PtrDiffInfo.second;
770 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000771 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000772 case Type::Complex: {
773 // Complex types have the same alignment as their elements, but twice the
774 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000775 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000776 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000777 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000778 Align = EltInfo.second;
779 break;
780 }
John McCallc12c5bb2010-05-15 11:32:37 +0000781 case Type::ObjCObject:
782 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000783 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000784 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000785 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
786 Width = Layout.getSize();
787 Align = Layout.getAlignment();
788 break;
789 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000790 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000791 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000792 const TagType *TT = cast<TagType>(T);
793
794 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000795 Width = 1;
796 Align = 1;
797 break;
798 }
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Daniel Dunbar1d751182008-11-08 05:48:37 +0000800 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000801 return getTypeInfo(ET->getDecl()->getIntegerType());
802
Daniel Dunbar1d751182008-11-08 05:48:37 +0000803 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000804 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
805 Width = Layout.getSize();
806 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000807 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000808 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000809
Chris Lattner9fcfe922009-10-22 05:17:15 +0000810 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000811 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
812 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000813
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000814 case Type::Paren:
815 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
816
Douglas Gregor18857642009-04-30 17:32:17 +0000817 case Type::Typedef: {
818 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000819 std::pair<uint64_t, unsigned> Info
820 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
821 Align = std::max(Typedef->getMaxAlignment(), Info.second);
822 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000823 break;
Chris Lattner71763312008-04-06 22:05:18 +0000824 }
Douglas Gregor18857642009-04-30 17:32:17 +0000825
826 case Type::TypeOfExpr:
827 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
828 .getTypePtr());
829
830 case Type::TypeOf:
831 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
832
Anders Carlsson395b4752009-06-24 19:06:50 +0000833 case Type::Decltype:
834 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
835 .getTypePtr());
836
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000837 case Type::Elaborated:
838 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Douglas Gregor18857642009-04-30 17:32:17 +0000840 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000841 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000842 "Cannot request the size of a dependent type");
843 // FIXME: this is likely to be wrong once we support template
844 // aliases, since a template alias could refer to a typedef that
845 // has an __aligned__ attribute on it.
846 return getTypeInfo(getCanonicalType(T));
847 }
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Chris Lattner464175b2007-07-18 17:52:12 +0000849 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000850 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000851}
852
Ken Dyckbdc601b2009-12-22 14:23:30 +0000853/// getTypeSizeInChars - Return the size of the specified type, in characters.
854/// This method does not work on incomplete types.
855CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000856 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000857}
858CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000859 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000860}
861
Ken Dyck16e20cc2010-01-26 17:25:18 +0000862/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000863/// characters. This method does not work on incomplete types.
864CharUnits ASTContext::getTypeAlignInChars(QualType T) {
865 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
866}
867CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
868 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
869}
870
Chris Lattner34ebde42009-01-27 18:08:34 +0000871/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
872/// type for the current target in bits. This can be different than the ABI
873/// alignment in cases where it is beneficial for performance to overalign
874/// a data type.
875unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
876 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000877
878 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000879 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000880 T = CT->getElementType().getTypePtr();
881 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
882 T->isSpecificBuiltinType(BuiltinType::LongLong))
883 return std::max(ABIAlign, (unsigned)getTypeSize(T));
884
Chris Lattner34ebde42009-01-27 18:08:34 +0000885 return ABIAlign;
886}
887
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000888/// ShallowCollectObjCIvars -
889/// Collect all ivars, including those synthesized, in the current class.
890///
891void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000892 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000893 // FIXME. This need be removed but there are two many places which
894 // assume const-ness of ObjCInterfaceDecl
895 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
896 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
897 Iv= Iv->getNextIvar())
898 Ivars.push_back(Iv);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000899}
900
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000901/// DeepCollectObjCIvars -
902/// This routine first collects all declared, but not synthesized, ivars in
903/// super class and then collects all ivars, including those synthesized for
904/// current class. This routine is used for implementation of current class
905/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000906///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000907void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
908 bool leafClass,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000909 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000910 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
911 DeepCollectObjCIvars(SuperClass, false, Ivars);
912 if (!leafClass) {
913 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
914 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000915 Ivars.push_back(*I);
916 }
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000917 else
918 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian98200742009-05-12 18:14:29 +0000919}
920
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000921/// CollectInheritedProtocols - Collect all protocols in current class and
922/// those inherited by it.
923void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000924 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000925 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +0000926 // We can use protocol_iterator here instead of
927 // all_referenced_protocol_iterator since we are walking all categories.
928 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
929 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000930 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000931 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000932 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000933 PE = Proto->protocol_end(); P != PE; ++P) {
934 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000935 CollectInheritedProtocols(*P, Protocols);
936 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000937 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000938
939 // Categories of this Interface.
940 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
941 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
942 CollectInheritedProtocols(CDeclChain, Protocols);
943 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
944 while (SD) {
945 CollectInheritedProtocols(SD, Protocols);
946 SD = SD->getSuperClass();
947 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000948 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +0000949 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000950 PE = OC->protocol_end(); P != PE; ++P) {
951 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000952 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000953 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
954 PE = Proto->protocol_end(); P != PE; ++P)
955 CollectInheritedProtocols(*P, Protocols);
956 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000957 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000958 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
959 PE = OP->protocol_end(); P != PE; ++P) {
960 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000961 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000962 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
963 PE = Proto->protocol_end(); P != PE; ++P)
964 CollectInheritedProtocols(*P, Protocols);
965 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000966 }
967}
968
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000969unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
970 unsigned count = 0;
971 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000972 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
973 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000974 count += CDecl->ivar_size();
975
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000976 // Count ivar defined in this class's implementation. This
977 // includes synthesized ivars.
978 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +0000979 count += ImplDecl->ivar_size();
980
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000981 return count;
982}
983
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000984/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
985ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
986 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
987 I = ObjCImpls.find(D);
988 if (I != ObjCImpls.end())
989 return cast<ObjCImplementationDecl>(I->second);
990 return 0;
991}
992/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
993ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
994 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
995 I = ObjCImpls.find(D);
996 if (I != ObjCImpls.end())
997 return cast<ObjCCategoryImplDecl>(I->second);
998 return 0;
999}
1000
1001/// \brief Set the implementation of ObjCInterfaceDecl.
1002void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1003 ObjCImplementationDecl *ImplD) {
1004 assert(IFaceD && ImplD && "Passed null params");
1005 ObjCImpls[IFaceD] = ImplD;
1006}
1007/// \brief Set the implementation of ObjCCategoryDecl.
1008void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1009 ObjCCategoryImplDecl *ImplD) {
1010 assert(CatD && ImplD && "Passed null params");
1011 ObjCImpls[CatD] = ImplD;
1012}
1013
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001014/// \brief Get the copy initialization expression of VarDecl,or NULL if
1015/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001016Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001017 assert(VD && "Passed null params");
1018 assert(VD->hasAttr<BlocksAttr>() &&
1019 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001020 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001021 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001022 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1023}
1024
1025/// \brief Set the copy inialization expression of a block var decl.
1026void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1027 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001028 assert(VD->hasAttr<BlocksAttr>() &&
1029 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001030 BlockVarCopyInits[VD] = Init;
1031}
1032
John McCalla93c9342009-12-07 02:54:59 +00001033/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001034///
John McCalla93c9342009-12-07 02:54:59 +00001035/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001036/// the TypeLoc wrappers.
1037///
1038/// \param T the type that will be the basis for type source info. This type
1039/// should refer to how the declarator was written in source code, not to
1040/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001041TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001042 unsigned DataSize) {
1043 if (!DataSize)
1044 DataSize = TypeLoc::getFullDataSizeForType(T);
1045 else
1046 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001047 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001048
John McCalla93c9342009-12-07 02:54:59 +00001049 TypeSourceInfo *TInfo =
1050 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1051 new (TInfo) TypeSourceInfo(T);
1052 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001053}
1054
John McCalla93c9342009-12-07 02:54:59 +00001055TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001056 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001057 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001058 DI->getTypeLoc().initialize(L);
1059 return DI;
1060}
1061
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001062const ASTRecordLayout &
1063ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1064 return getObjCLayout(D, 0);
1065}
1066
1067const ASTRecordLayout &
1068ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1069 return getObjCLayout(D->getClassInterface(), D);
1070}
1071
Chris Lattnera7674d82007-07-13 22:13:22 +00001072//===----------------------------------------------------------------------===//
1073// Type creation/memoization methods
1074//===----------------------------------------------------------------------===//
1075
John McCall0953e762009-09-24 19:53:00 +00001076QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1077 unsigned Fast = Quals.getFastQualifiers();
1078 Quals.removeFastQualifiers();
1079
1080 // Check if we've already instantiated this type.
1081 llvm::FoldingSetNodeID ID;
1082 ExtQuals::Profile(ID, TypeNode, Quals);
1083 void *InsertPos = 0;
1084 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1085 assert(EQ->getQualifiers() == Quals);
1086 QualType T = QualType(EQ, Fast);
1087 return T;
1088 }
1089
John McCall49f4e1c2010-12-10 11:01:00 +00001090 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001091 ExtQualNodes.InsertNode(New, InsertPos);
1092 QualType T = QualType(New, Fast);
1093 return T;
1094}
1095
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001096QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001097 QualType CanT = getCanonicalType(T);
1098 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001099 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001100
John McCall0953e762009-09-24 19:53:00 +00001101 // If we are composing extended qualifiers together, merge together
1102 // into one ExtQuals node.
1103 QualifierCollector Quals;
1104 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001105
John McCall0953e762009-09-24 19:53:00 +00001106 // If this type already has an address space specified, it cannot get
1107 // another one.
1108 assert(!Quals.hasAddressSpace() &&
1109 "Type cannot be in multiple addr spaces!");
1110 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001111
John McCall0953e762009-09-24 19:53:00 +00001112 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001113}
1114
Chris Lattnerb7d25532009-02-18 22:53:11 +00001115QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001116 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001117 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001118 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001119 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001121 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001122 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001123 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001124 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1125 return getPointerType(ResultType);
1126 }
1127 }
Mike Stump1eb44332009-09-09 15:08:12 +00001128
John McCall0953e762009-09-24 19:53:00 +00001129 // If we are composing extended qualifiers together, merge together
1130 // into one ExtQuals node.
1131 QualifierCollector Quals;
1132 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001133
John McCall0953e762009-09-24 19:53:00 +00001134 // If this type already has an ObjCGC specified, it cannot get
1135 // another one.
1136 assert(!Quals.hasObjCGCAttr() &&
1137 "Type cannot have multiple ObjCGCs!");
1138 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001139
John McCall0953e762009-09-24 19:53:00 +00001140 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001141}
Chris Lattnera7674d82007-07-13 22:13:22 +00001142
John McCalle6a365d2010-12-19 02:44:49 +00001143const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1144 FunctionType::ExtInfo Info) {
1145 if (T->getExtInfo() == Info)
1146 return T;
1147
1148 QualType Result;
1149 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1150 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1151 } else {
1152 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1153 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1154 EPI.ExtInfo = Info;
1155 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1156 FPT->getNumArgs(), EPI);
1157 }
1158
1159 return cast<FunctionType>(Result.getTypePtr());
1160}
1161
Reid Spencer5f016e22007-07-11 17:01:13 +00001162/// getComplexType - Return the uniqued reference to the type for a complex
1163/// number with the specified element type.
1164QualType ASTContext::getComplexType(QualType T) {
1165 // Unique pointers, to guarantee there is only one pointer of a particular
1166 // structure.
1167 llvm::FoldingSetNodeID ID;
1168 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Reid Spencer5f016e22007-07-11 17:01:13 +00001170 void *InsertPos = 0;
1171 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1172 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Reid Spencer5f016e22007-07-11 17:01:13 +00001174 // If the pointee type isn't canonical, this won't be a canonical type either,
1175 // so fill in the canonical type field.
1176 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001177 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001178 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 // Get the new insert position for the node we care about.
1181 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001182 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 }
John McCall6b304a02009-09-24 23:30:46 +00001184 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001185 Types.push_back(New);
1186 ComplexTypes.InsertNode(New, InsertPos);
1187 return QualType(New, 0);
1188}
1189
Reid Spencer5f016e22007-07-11 17:01:13 +00001190/// getPointerType - Return the uniqued reference to the type for a pointer to
1191/// the specified type.
1192QualType ASTContext::getPointerType(QualType T) {
1193 // Unique pointers, to guarantee there is only one pointer of a particular
1194 // structure.
1195 llvm::FoldingSetNodeID ID;
1196 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Reid Spencer5f016e22007-07-11 17:01:13 +00001198 void *InsertPos = 0;
1199 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1200 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 // If the pointee type isn't canonical, this won't be a canonical type either,
1203 // so fill in the canonical type field.
1204 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001205 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001206 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 // Get the new insert position for the node we care about.
1209 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001210 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001211 }
John McCall6b304a02009-09-24 23:30:46 +00001212 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 Types.push_back(New);
1214 PointerTypes.InsertNode(New, InsertPos);
1215 return QualType(New, 0);
1216}
1217
Mike Stump1eb44332009-09-09 15:08:12 +00001218/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001219/// a pointer to the specified block.
1220QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001221 assert(T->isFunctionType() && "block of function types only");
1222 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001223 // structure.
1224 llvm::FoldingSetNodeID ID;
1225 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Steve Naroff5618bd42008-08-27 16:04:49 +00001227 void *InsertPos = 0;
1228 if (BlockPointerType *PT =
1229 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1230 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001231
1232 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001233 // type either so fill in the canonical type field.
1234 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001235 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001236 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Steve Naroff5618bd42008-08-27 16:04:49 +00001238 // Get the new insert position for the node we care about.
1239 BlockPointerType *NewIP =
1240 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001241 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001242 }
John McCall6b304a02009-09-24 23:30:46 +00001243 BlockPointerType *New
1244 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001245 Types.push_back(New);
1246 BlockPointerTypes.InsertNode(New, InsertPos);
1247 return QualType(New, 0);
1248}
1249
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001250/// getLValueReferenceType - Return the uniqued reference to the type for an
1251/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001252QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001253 // Unique pointers, to guarantee there is only one pointer of a particular
1254 // structure.
1255 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001256 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001257
1258 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001259 if (LValueReferenceType *RT =
1260 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001262
John McCall54e14c42009-10-22 22:37:11 +00001263 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1264
Reid Spencer5f016e22007-07-11 17:01:13 +00001265 // If the referencee type isn't canonical, this won't be a canonical type
1266 // either, so fill in the canonical type field.
1267 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001268 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1269 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1270 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001271
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001273 LValueReferenceType *NewIP =
1274 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001275 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001276 }
1277
John McCall6b304a02009-09-24 23:30:46 +00001278 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001279 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1280 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001281 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001282 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001283
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001284 return QualType(New, 0);
1285}
1286
1287/// getRValueReferenceType - Return the uniqued reference to the type for an
1288/// rvalue reference to the specified type.
1289QualType ASTContext::getRValueReferenceType(QualType T) {
1290 // Unique pointers, to guarantee there is only one pointer of a particular
1291 // structure.
1292 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001293 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001294
1295 void *InsertPos = 0;
1296 if (RValueReferenceType *RT =
1297 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1298 return QualType(RT, 0);
1299
John McCall54e14c42009-10-22 22:37:11 +00001300 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1301
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001302 // If the referencee type isn't canonical, this won't be a canonical type
1303 // either, so fill in the canonical type field.
1304 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001305 if (InnerRef || !T.isCanonical()) {
1306 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1307 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001308
1309 // Get the new insert position for the node we care about.
1310 RValueReferenceType *NewIP =
1311 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1312 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1313 }
1314
John McCall6b304a02009-09-24 23:30:46 +00001315 RValueReferenceType *New
1316 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001317 Types.push_back(New);
1318 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 return QualType(New, 0);
1320}
1321
Sebastian Redlf30208a2009-01-24 21:16:55 +00001322/// getMemberPointerType - Return the uniqued reference to the type for a
1323/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001324QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001325 // Unique pointers, to guarantee there is only one pointer of a particular
1326 // structure.
1327 llvm::FoldingSetNodeID ID;
1328 MemberPointerType::Profile(ID, T, Cls);
1329
1330 void *InsertPos = 0;
1331 if (MemberPointerType *PT =
1332 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1333 return QualType(PT, 0);
1334
1335 // If the pointee or class type isn't canonical, this won't be a canonical
1336 // type either, so fill in the canonical type field.
1337 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001338 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001339 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1340
1341 // Get the new insert position for the node we care about.
1342 MemberPointerType *NewIP =
1343 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1344 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1345 }
John McCall6b304a02009-09-24 23:30:46 +00001346 MemberPointerType *New
1347 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001348 Types.push_back(New);
1349 MemberPointerTypes.InsertNode(New, InsertPos);
1350 return QualType(New, 0);
1351}
1352
Mike Stump1eb44332009-09-09 15:08:12 +00001353/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001354/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001355QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001356 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001357 ArrayType::ArraySizeModifier ASM,
1358 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001359 assert((EltTy->isDependentType() ||
1360 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001361 "Constant array of VLAs is illegal!");
1362
Chris Lattner38aeec72009-05-13 04:12:56 +00001363 // Convert the array size into a canonical width matching the pointer size for
1364 // the target.
1365 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001366 ArySize =
1367 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001370 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Reid Spencer5f016e22007-07-11 17:01:13 +00001372 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001373 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001374 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 // If the element type isn't canonical, this won't be a canonical type either,
1378 // so fill in the canonical type field.
1379 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001380 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001381 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001382 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001384 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001385 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001386 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 }
Mike Stump1eb44332009-09-09 15:08:12 +00001388
John McCall6b304a02009-09-24 23:30:46 +00001389 ConstantArrayType *New = new(*this,TypeAlignment)
1390 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001391 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 Types.push_back(New);
1393 return QualType(New, 0);
1394}
1395
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001396/// getIncompleteArrayType - Returns a unique reference to the type for a
1397/// incomplete array of the specified element type.
1398QualType ASTContext::getUnknownSizeVariableArrayType(QualType Ty) {
1399 QualType ElemTy = getBaseElementType(Ty);
1400 DeclarationName Name;
1401 llvm::SmallVector<QualType, 8> ATypes;
1402 QualType ATy = Ty;
1403 while (const ArrayType *AT = getAsArrayType(ATy)) {
1404 ATypes.push_back(ATy);
1405 ATy = AT->getElementType();
1406 }
1407 for (int i = ATypes.size() - 1; i >= 0; i--) {
1408 if (const VariableArrayType *VAT = getAsVariableArrayType(ATypes[i])) {
1409 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Star,
1410 0, VAT->getBracketsRange());
1411 }
1412 else if (const ConstantArrayType *CAT = getAsConstantArrayType(ATypes[i])) {
1413 llvm::APSInt ConstVal(CAT->getSize());
1414 ElemTy = getConstantArrayType(ElemTy, ConstVal, ArrayType::Normal, 0);
1415 }
1416 else if (getAsIncompleteArrayType(ATypes[i])) {
1417 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Normal,
1418 0, SourceRange());
1419 }
1420 else
1421 assert(false && "DependentArrayType is seen");
1422 }
1423 return ElemTy;
1424}
1425
1426/// getVariableArrayDecayedType - Returns a vla type where known sizes
1427/// are replaced with [*]
1428QualType ASTContext::getVariableArrayDecayedType(QualType Ty) {
1429 if (Ty->isPointerType()) {
1430 QualType BaseType = Ty->getAs<PointerType>()->getPointeeType();
1431 if (isa<VariableArrayType>(BaseType)) {
1432 ArrayType *AT = dyn_cast<ArrayType>(BaseType);
1433 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1434 if (VAT->getSizeExpr()) {
1435 Ty = getUnknownSizeVariableArrayType(BaseType);
1436 Ty = getPointerType(Ty);
1437 }
1438 }
1439 }
1440 return Ty;
1441}
1442
1443
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001444/// getVariableArrayType - Returns a non-unique reference to the type for a
1445/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001446QualType ASTContext::getVariableArrayType(QualType EltTy,
1447 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001448 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001449 unsigned EltTypeQuals,
1450 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001451 // Since we don't unique expressions, it isn't possible to unique VLA's
1452 // that have an expression provided for their size.
Douglas Gregor715e9c82010-05-23 16:10:32 +00001453 QualType CanonType;
1454
1455 if (!EltTy.isCanonical()) {
Douglas Gregor715e9c82010-05-23 16:10:32 +00001456 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1457 EltTypeQuals, Brackets);
1458 }
1459
John McCall6b304a02009-09-24 23:30:46 +00001460 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor715e9c82010-05-23 16:10:32 +00001461 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001462
1463 VariableArrayTypes.push_back(New);
1464 Types.push_back(New);
1465 return QualType(New, 0);
1466}
1467
Douglas Gregor898574e2008-12-05 23:32:09 +00001468/// getDependentSizedArrayType - Returns a non-unique reference to
1469/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001470/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001471QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1472 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001473 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001474 unsigned EltTypeQuals,
1475 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001476 assert((!NumElts || NumElts->isTypeDependent() ||
1477 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001478 "Size must be type- or value-dependent!");
1479
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001480 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001481 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001482 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001483
Douglas Gregor32adc8b2010-10-26 00:51:02 +00001484 QualType CanonicalEltTy = getCanonicalType(EltTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001485 if (NumElts) {
1486 // Dependently-sized array types that do not have a specified
1487 // number of elements will have their sizes deduced from an
1488 // initializer.
Douglas Gregor32adc8b2010-10-26 00:51:02 +00001489 DependentSizedArrayType::Profile(ID, *this, CanonicalEltTy, ASM,
Douglas Gregorcb78d882009-11-19 18:03:26 +00001490 EltTypeQuals, NumElts);
1491
1492 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1493 }
1494
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001495 DependentSizedArrayType *New;
1496 if (Canon) {
1497 // We already have a canonical version of this array type; use it as
1498 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001499 New = new (*this, TypeAlignment)
1500 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1501 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor32adc8b2010-10-26 00:51:02 +00001502 } else if (CanonicalEltTy == EltTy) {
1503 // This is a canonical type. Record it.
1504 New = new (*this, TypeAlignment)
1505 DependentSizedArrayType(*this, EltTy, QualType(),
1506 NumElts, ASM, EltTypeQuals, Brackets);
1507
1508 if (NumElts) {
1509#ifndef NDEBUG
1510 DependentSizedArrayType *CanonCheck
1511 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1512 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1513 (void)CanonCheck;
1514#endif
1515 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001516 }
Douglas Gregor32adc8b2010-10-26 00:51:02 +00001517 } else {
1518 QualType Canon = getDependentSizedArrayType(CanonicalEltTy, NumElts,
1519 ASM, EltTypeQuals,
1520 SourceRange());
1521 New = new (*this, TypeAlignment)
1522 DependentSizedArrayType(*this, EltTy, Canon,
1523 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001524 }
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Douglas Gregor898574e2008-12-05 23:32:09 +00001526 Types.push_back(New);
1527 return QualType(New, 0);
1528}
1529
Eli Friedmanc5773c42008-02-15 18:16:39 +00001530QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1531 ArrayType::ArraySizeModifier ASM,
1532 unsigned EltTypeQuals) {
1533 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001534 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001535
1536 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001537 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001538 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1539 return QualType(ATP, 0);
1540
1541 // If the element type isn't canonical, this won't be a canonical type
1542 // either, so fill in the canonical type field.
1543 QualType Canonical;
1544
John McCall467b27b2009-10-22 20:10:53 +00001545 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001546 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001547 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001548
1549 // Get the new insert position for the node we care about.
1550 IncompleteArrayType *NewIP =
1551 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001552 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001553 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001554
John McCall6b304a02009-09-24 23:30:46 +00001555 IncompleteArrayType *New = new (*this, TypeAlignment)
1556 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001557
1558 IncompleteArrayTypes.InsertNode(New, InsertPos);
1559 Types.push_back(New);
1560 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001561}
1562
Steve Naroff73322922007-07-18 18:00:27 +00001563/// getVectorType - Return the unique reference to a vector type of
1564/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001565QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001566 VectorType::VectorKind VecKind) {
Chris Lattner33daae62010-10-01 22:42:38 +00001567 BuiltinType *BaseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Chris Lattner33daae62010-10-01 22:42:38 +00001569 BaseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1570 assert(BaseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 // Check if we've already instantiated a vector of this type.
1573 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001574 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 void *InsertPos = 0;
1577 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1578 return QualType(VTP, 0);
1579
1580 // If the element type isn't canonical, this won't be a canonical type either,
1581 // so fill in the canonical type field.
1582 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001583 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001584 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 // Get the new insert position for the node we care about.
1587 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001588 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 }
John McCall6b304a02009-09-24 23:30:46 +00001590 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001591 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 VectorTypes.InsertNode(New, InsertPos);
1593 Types.push_back(New);
1594 return QualType(New, 0);
1595}
1596
Nate Begeman213541a2008-04-18 23:10:10 +00001597/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001598/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001599QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001600 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Chris Lattnerf52ab252008-04-06 22:59:24 +00001602 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001603 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Steve Naroff73322922007-07-18 18:00:27 +00001605 // Check if we've already instantiated a vector of this type.
1606 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001607 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001608 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001609 void *InsertPos = 0;
1610 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1611 return QualType(VTP, 0);
1612
1613 // If the element type isn't canonical, this won't be a canonical type either,
1614 // so fill in the canonical type field.
1615 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001616 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001617 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Steve Naroff73322922007-07-18 18:00:27 +00001619 // Get the new insert position for the node we care about.
1620 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001621 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001622 }
John McCall6b304a02009-09-24 23:30:46 +00001623 ExtVectorType *New = new (*this, TypeAlignment)
1624 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001625 VectorTypes.InsertNode(New, InsertPos);
1626 Types.push_back(New);
1627 return QualType(New, 0);
1628}
1629
Mike Stump1eb44332009-09-09 15:08:12 +00001630QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001631 Expr *SizeExpr,
1632 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001633 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001634 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001635 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001637 void *InsertPos = 0;
1638 DependentSizedExtVectorType *Canon
1639 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1640 DependentSizedExtVectorType *New;
1641 if (Canon) {
1642 // We already have a canonical version of this array type; use it as
1643 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001644 New = new (*this, TypeAlignment)
1645 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1646 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001647 } else {
1648 QualType CanonVecTy = getCanonicalType(vecType);
1649 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001650 New = new (*this, TypeAlignment)
1651 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1652 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001653
1654 DependentSizedExtVectorType *CanonCheck
1655 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1656 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1657 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001658 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1659 } else {
1660 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1661 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001662 New = new (*this, TypeAlignment)
1663 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001664 }
1665 }
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001667 Types.push_back(New);
1668 return QualType(New, 0);
1669}
1670
Douglas Gregor72564e72009-02-26 23:50:07 +00001671/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001672///
Rafael Espindola264ba482010-03-30 20:24:48 +00001673QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1674 const FunctionType::ExtInfo &Info) {
1675 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001676 // Unique functions, to guarantee there is only one function of a particular
1677 // structure.
1678 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001679 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Reid Spencer5f016e22007-07-11 17:01:13 +00001681 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001682 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001683 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Reid Spencer5f016e22007-07-11 17:01:13 +00001686 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001687 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001688 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001689 Canonical =
1690 getFunctionNoProtoType(getCanonicalType(ResultTy),
1691 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Reid Spencer5f016e22007-07-11 17:01:13 +00001693 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001694 FunctionNoProtoType *NewIP =
1695 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001696 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 }
Mike Stump1eb44332009-09-09 15:08:12 +00001698
John McCall6b304a02009-09-24 23:30:46 +00001699 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001700 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001701 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001702 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 return QualType(New, 0);
1704}
1705
1706/// getFunctionType - Return a normal function type with a typed argument
1707/// list. isVariadic indicates whether the argument list includes '...'.
John McCalle23cf432010-12-14 08:05:40 +00001708QualType ASTContext::getFunctionType(QualType ResultTy,
1709 const QualType *ArgArray, unsigned NumArgs,
1710 const FunctionProtoType::ExtProtoInfo &EPI) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 // Unique functions, to guarantee there is only one function of a particular
1712 // structure.
1713 llvm::FoldingSetNodeID ID;
John McCalle23cf432010-12-14 08:05:40 +00001714 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00001715
1716 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001717 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001718 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001719 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001720
1721 // Determine whether the type being created is already canonical or not.
John McCalle23cf432010-12-14 08:05:40 +00001722 bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001724 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 isCanonical = false;
1726
John McCalle23cf432010-12-14 08:05:40 +00001727 const CallingConv CallConv = EPI.ExtInfo.getCC();
1728
Reid Spencer5f016e22007-07-11 17:01:13 +00001729 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001730 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001732 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001733 llvm::SmallVector<QualType, 16> CanonicalArgs;
1734 CanonicalArgs.reserve(NumArgs);
1735 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001736 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001737
John McCalle23cf432010-12-14 08:05:40 +00001738 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1739 if (CanonicalEPI.HasExceptionSpec) {
1740 CanonicalEPI.HasExceptionSpec = false;
1741 CanonicalEPI.HasAnyExceptionSpec = false;
1742 CanonicalEPI.NumExceptions = 0;
1743 }
1744 CanonicalEPI.ExtInfo
1745 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1746
Chris Lattnerf52ab252008-04-06 22:59:24 +00001747 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001748 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00001749 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00001750
Reid Spencer5f016e22007-07-11 17:01:13 +00001751 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001752 FunctionProtoType *NewIP =
1753 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001754 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001755 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001756
Douglas Gregor72564e72009-02-26 23:50:07 +00001757 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001758 // for two variable size arrays (for parameter and exception types) at the
1759 // end of them.
John McCalle23cf432010-12-14 08:05:40 +00001760 size_t Size = sizeof(FunctionProtoType) +
1761 NumArgs * sizeof(QualType) +
1762 EPI.NumExceptions * sizeof(QualType);
1763 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
1764 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001766 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 return QualType(FTP, 0);
1768}
1769
John McCall3cb0ebd2010-03-10 03:28:59 +00001770#ifndef NDEBUG
1771static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1772 if (!isa<CXXRecordDecl>(D)) return false;
1773 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1774 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1775 return true;
1776 if (RD->getDescribedClassTemplate() &&
1777 !isa<ClassTemplateSpecializationDecl>(RD))
1778 return true;
1779 return false;
1780}
1781#endif
1782
1783/// getInjectedClassNameType - Return the unique reference to the
1784/// injected class name type for the specified templated declaration.
1785QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1786 QualType TST) {
1787 assert(NeedsInjectedClassNameType(Decl));
1788 if (Decl->TypeForDecl) {
1789 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001790 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00001791 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1792 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1793 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1794 } else {
John McCall31f17ec2010-04-27 00:57:59 +00001795 Decl->TypeForDecl =
1796 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall3cb0ebd2010-03-10 03:28:59 +00001797 Types.push_back(Decl->TypeForDecl);
1798 }
1799 return QualType(Decl->TypeForDecl, 0);
1800}
1801
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001802/// getTypeDeclType - Return the unique reference to the type for the
1803/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001804QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001805 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001806 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001807
John McCall19c85762010-02-16 03:57:14 +00001808 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001809 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001810
John McCallbecb8d52010-03-10 06:48:02 +00001811 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1812 "Template type parameter types are always available.");
1813
John McCall19c85762010-02-16 03:57:14 +00001814 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001815 assert(!Record->getPreviousDeclaration() &&
1816 "struct/union has previous declaration");
1817 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001818 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001819 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001820 assert(!Enum->getPreviousDeclaration() &&
1821 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001822 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001823 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001824 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1825 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001826 } else
John McCallbecb8d52010-03-10 06:48:02 +00001827 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001828
John McCallbecb8d52010-03-10 06:48:02 +00001829 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001830 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001831}
1832
Reid Spencer5f016e22007-07-11 17:01:13 +00001833/// getTypedefType - Return the unique reference to the type for the
1834/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001835QualType
1836ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001837 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001839 if (Canonical.isNull())
1840 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001841 Decl->TypeForDecl = new(*this, TypeAlignment)
1842 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001843 Types.push_back(Decl->TypeForDecl);
1844 return QualType(Decl->TypeForDecl, 0);
1845}
1846
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001847QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1848 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1849
1850 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1851 if (PrevDecl->TypeForDecl)
1852 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1853
1854 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1855 Types.push_back(Decl->TypeForDecl);
1856 return QualType(Decl->TypeForDecl, 0);
1857}
1858
1859QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1860 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1861
1862 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1863 if (PrevDecl->TypeForDecl)
1864 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1865
1866 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1867 Types.push_back(Decl->TypeForDecl);
1868 return QualType(Decl->TypeForDecl, 0);
1869}
1870
John McCall49a832b2009-10-18 09:09:24 +00001871/// \brief Retrieve a substitution-result type.
1872QualType
1873ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1874 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001875 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001876 && "replacement types must always be canonical");
1877
1878 llvm::FoldingSetNodeID ID;
1879 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1880 void *InsertPos = 0;
1881 SubstTemplateTypeParmType *SubstParm
1882 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1883
1884 if (!SubstParm) {
1885 SubstParm = new (*this, TypeAlignment)
1886 SubstTemplateTypeParmType(Parm, Replacement);
1887 Types.push_back(SubstParm);
1888 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1889 }
1890
1891 return QualType(SubstParm, 0);
1892}
1893
Douglas Gregorfab9d672009-02-05 23:33:38 +00001894/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001895/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001896/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001897QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001898 bool ParameterPack,
Douglas Gregorefed5c82010-06-16 15:23:05 +00001899 IdentifierInfo *Name) {
Douglas Gregorfab9d672009-02-05 23:33:38 +00001900 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00001901 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001902 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001903 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001904 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1905
1906 if (TypeParm)
1907 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Douglas Gregorefed5c82010-06-16 15:23:05 +00001909 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001910 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00001911 TypeParm = new (*this, TypeAlignment)
1912 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001913
1914 TemplateTypeParmType *TypeCheck
1915 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1916 assert(!TypeCheck && "Template type parameter canonical type broken");
1917 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001918 } else
John McCall6b304a02009-09-24 23:30:46 +00001919 TypeParm = new (*this, TypeAlignment)
1920 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001921
1922 Types.push_back(TypeParm);
1923 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1924
1925 return QualType(TypeParm, 0);
1926}
1927
John McCall3cb0ebd2010-03-10 03:28:59 +00001928TypeSourceInfo *
1929ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1930 SourceLocation NameLoc,
1931 const TemplateArgumentListInfo &Args,
1932 QualType CanonType) {
1933 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1934
1935 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1936 TemplateSpecializationTypeLoc TL
1937 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1938 TL.setTemplateNameLoc(NameLoc);
1939 TL.setLAngleLoc(Args.getLAngleLoc());
1940 TL.setRAngleLoc(Args.getRAngleLoc());
1941 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1942 TL.setArgLocInfo(i, Args[i].getLocInfo());
1943 return DI;
1944}
1945
Mike Stump1eb44332009-09-09 15:08:12 +00001946QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001947ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001948 const TemplateArgumentListInfo &Args,
John McCall71d74bc2010-06-13 09:25:03 +00001949 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001950 unsigned NumArgs = Args.size();
1951
John McCall833ca992009-10-29 08:12:44 +00001952 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1953 ArgVec.reserve(NumArgs);
1954 for (unsigned i = 0; i != NumArgs; ++i)
1955 ArgVec.push_back(Args[i].getArgument());
1956
John McCall31f17ec2010-04-27 00:57:59 +00001957 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001958 Canon);
John McCall833ca992009-10-29 08:12:44 +00001959}
1960
1961QualType
1962ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001963 const TemplateArgument *Args,
1964 unsigned NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00001965 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001966 if (!Canon.isNull())
1967 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001968 else
1969 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001970
Douglas Gregor1275ae02009-07-28 23:00:59 +00001971 // Allocate the (non-canonical) template specialization type, but don't
1972 // try to unique it: these types typically have location information that
1973 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001974 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001975 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001976 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001977 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00001978 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00001979 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001980 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Douglas Gregor55f6b142009-02-09 18:46:07 +00001982 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001983 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001984}
1985
Mike Stump1eb44332009-09-09 15:08:12 +00001986QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00001987ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1988 const TemplateArgument *Args,
1989 unsigned NumArgs) {
1990 // Build the canonical template specialization type.
1991 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1992 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1993 CanonArgs.reserve(NumArgs);
1994 for (unsigned I = 0; I != NumArgs; ++I)
1995 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1996
1997 // Determine whether this canonical template specialization type already
1998 // exists.
1999 llvm::FoldingSetNodeID ID;
2000 TemplateSpecializationType::Profile(ID, CanonTemplate,
2001 CanonArgs.data(), NumArgs, *this);
2002
2003 void *InsertPos = 0;
2004 TemplateSpecializationType *Spec
2005 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2006
2007 if (!Spec) {
2008 // Allocate a new canonical template specialization type.
2009 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2010 sizeof(TemplateArgument) * NumArgs),
2011 TypeAlignment);
2012 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2013 CanonArgs.data(), NumArgs,
2014 QualType());
2015 Types.push_back(Spec);
2016 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2017 }
2018
2019 assert(Spec->isDependentType() &&
2020 "Non-dependent template-id type must have a canonical type");
2021 return QualType(Spec, 0);
2022}
2023
2024QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002025ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2026 NestedNameSpecifier *NNS,
2027 QualType NamedType) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002028 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002029 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002030
2031 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002032 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002033 if (T)
2034 return QualType(T, 0);
2035
Douglas Gregor789b1f62010-02-04 18:10:26 +00002036 QualType Canon = NamedType;
2037 if (!Canon.isCanonical()) {
2038 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002039 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2040 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002041 (void)CheckT;
2042 }
2043
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002044 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002045 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002046 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002047 return QualType(T, 0);
2048}
2049
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002050QualType
2051ASTContext::getParenType(QualType InnerType) {
2052 llvm::FoldingSetNodeID ID;
2053 ParenType::Profile(ID, InnerType);
2054
2055 void *InsertPos = 0;
2056 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2057 if (T)
2058 return QualType(T, 0);
2059
2060 QualType Canon = InnerType;
2061 if (!Canon.isCanonical()) {
2062 Canon = getCanonicalType(InnerType);
2063 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2064 assert(!CheckT && "Paren canonical type broken");
2065 (void)CheckT;
2066 }
2067
2068 T = new (*this) ParenType(InnerType, Canon);
2069 Types.push_back(T);
2070 ParenTypes.InsertNode(T, InsertPos);
2071 return QualType(T, 0);
2072}
2073
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002074QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2075 NestedNameSpecifier *NNS,
2076 const IdentifierInfo *Name,
2077 QualType Canon) {
Douglas Gregord57959a2009-03-27 23:10:48 +00002078 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2079
2080 if (Canon.isNull()) {
2081 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002082 ElaboratedTypeKeyword CanonKeyword = Keyword;
2083 if (Keyword == ETK_None)
2084 CanonKeyword = ETK_Typename;
2085
2086 if (CanonNNS != NNS || CanonKeyword != Keyword)
2087 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002088 }
2089
2090 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002091 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002092
2093 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002094 DependentNameType *T
2095 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002096 if (T)
2097 return QualType(T, 0);
2098
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002099 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002100 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002101 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002102 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002103}
2104
Mike Stump1eb44332009-09-09 15:08:12 +00002105QualType
John McCall33500952010-06-11 00:33:02 +00002106ASTContext::getDependentTemplateSpecializationType(
2107 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002108 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002109 const IdentifierInfo *Name,
2110 const TemplateArgumentListInfo &Args) {
2111 // TODO: avoid this copy
2112 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2113 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2114 ArgCopy.push_back(Args[I].getArgument());
2115 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2116 ArgCopy.size(),
2117 ArgCopy.data());
2118}
2119
2120QualType
2121ASTContext::getDependentTemplateSpecializationType(
2122 ElaboratedTypeKeyword Keyword,
2123 NestedNameSpecifier *NNS,
2124 const IdentifierInfo *Name,
2125 unsigned NumArgs,
2126 const TemplateArgument *Args) {
Douglas Gregor17343172009-04-01 00:28:59 +00002127 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2128
Douglas Gregor789b1f62010-02-04 18:10:26 +00002129 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002130 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2131 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002132
2133 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002134 DependentTemplateSpecializationType *T
2135 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002136 if (T)
2137 return QualType(T, 0);
2138
John McCall33500952010-06-11 00:33:02 +00002139 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002140
John McCall33500952010-06-11 00:33:02 +00002141 ElaboratedTypeKeyword CanonKeyword = Keyword;
2142 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2143
2144 bool AnyNonCanonArgs = false;
2145 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2146 for (unsigned I = 0; I != NumArgs; ++I) {
2147 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2148 if (!CanonArgs[I].structurallyEquals(Args[I]))
2149 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002150 }
2151
John McCall33500952010-06-11 00:33:02 +00002152 QualType Canon;
2153 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2154 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2155 Name, NumArgs,
2156 CanonArgs.data());
2157
2158 // Find the insert position again.
2159 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2160 }
2161
2162 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2163 sizeof(TemplateArgument) * NumArgs),
2164 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002165 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002166 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002167 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002168 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002169 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002170}
2171
Douglas Gregor7536dd52010-12-20 02:24:11 +00002172QualType ASTContext::getPackExpansionType(QualType Pattern) {
2173 llvm::FoldingSetNodeID ID;
2174 PackExpansionType::Profile(ID, Pattern);
2175
2176 assert(Pattern->containsUnexpandedParameterPack() &&
2177 "Pack expansions must expand one or more parameter packs");
2178 void *InsertPos = 0;
2179 PackExpansionType *T
2180 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2181 if (T)
2182 return QualType(T, 0);
2183
2184 QualType Canon;
2185 if (!Pattern.isCanonical()) {
2186 Canon = getPackExpansionType(getCanonicalType(Pattern));
2187
2188 // Find the insert position again.
2189 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2190 }
2191
2192 T = new (*this) PackExpansionType(Pattern, Canon);
2193 Types.push_back(T);
2194 PackExpansionTypes.InsertNode(T, InsertPos);
2195 return QualType(T, 0);
2196}
2197
Chris Lattner88cb27a2008-04-07 04:56:42 +00002198/// CmpProtocolNames - Comparison predicate for sorting protocols
2199/// alphabetically.
2200static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2201 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002202 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002203}
2204
John McCallc12c5bb2010-05-15 11:32:37 +00002205static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002206 unsigned NumProtocols) {
2207 if (NumProtocols == 0) return true;
2208
2209 for (unsigned i = 1; i != NumProtocols; ++i)
2210 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2211 return false;
2212 return true;
2213}
2214
2215static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002216 unsigned &NumProtocols) {
2217 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002218
Chris Lattner88cb27a2008-04-07 04:56:42 +00002219 // Sort protocols, keyed by name.
2220 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2221
2222 // Remove duplicates.
2223 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2224 NumProtocols = ProtocolsEnd-Protocols;
2225}
2226
John McCallc12c5bb2010-05-15 11:32:37 +00002227QualType ASTContext::getObjCObjectType(QualType BaseType,
2228 ObjCProtocolDecl * const *Protocols,
2229 unsigned NumProtocols) {
2230 // If the base type is an interface and there aren't any protocols
2231 // to add, then the interface type will do just fine.
2232 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2233 return BaseType;
2234
2235 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002236 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002237 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002238 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002239 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2240 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002241
John McCallc12c5bb2010-05-15 11:32:37 +00002242 // Build the canonical type, which has the canonical base type and
2243 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002244 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002245 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2246 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2247 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002248 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2249 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002250 unsigned UniqueCount = NumProtocols;
2251
John McCall54e14c42009-10-22 22:37:11 +00002252 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002253 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2254 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002255 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002256 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2257 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002258 }
2259
2260 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002261 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2262 }
2263
2264 unsigned Size = sizeof(ObjCObjectTypeImpl);
2265 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2266 void *Mem = Allocate(Size, TypeAlignment);
2267 ObjCObjectTypeImpl *T =
2268 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2269
2270 Types.push_back(T);
2271 ObjCObjectTypes.InsertNode(T, InsertPos);
2272 return QualType(T, 0);
2273}
2274
2275/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2276/// the given object type.
2277QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2278 llvm::FoldingSetNodeID ID;
2279 ObjCObjectPointerType::Profile(ID, ObjectT);
2280
2281 void *InsertPos = 0;
2282 if (ObjCObjectPointerType *QT =
2283 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2284 return QualType(QT, 0);
2285
2286 // Find the canonical object type.
2287 QualType Canonical;
2288 if (!ObjectT.isCanonical()) {
2289 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2290
2291 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002292 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2293 }
2294
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002295 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002296 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2297 ObjCObjectPointerType *QType =
2298 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002300 Types.push_back(QType);
2301 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002302 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002303}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002304
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002305/// getObjCInterfaceType - Return the unique reference to the type for the
2306/// specified ObjC interface decl. The list of protocols is optional.
2307QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2308 if (Decl->TypeForDecl)
2309 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002311 // FIXME: redeclarations?
2312 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2313 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2314 Decl->TypeForDecl = T;
2315 Types.push_back(T);
2316 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002317}
2318
Douglas Gregor72564e72009-02-26 23:50:07 +00002319/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2320/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002321/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002322/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002323/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002324QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002325 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002326 if (tofExpr->isTypeDependent()) {
2327 llvm::FoldingSetNodeID ID;
2328 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002329
Douglas Gregorb1975722009-07-30 23:18:24 +00002330 void *InsertPos = 0;
2331 DependentTypeOfExprType *Canon
2332 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2333 if (Canon) {
2334 // We already have a "canonical" version of an identical, dependent
2335 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002336 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002337 QualType((TypeOfExprType*)Canon, 0));
2338 }
2339 else {
2340 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002341 Canon
2342 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002343 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2344 toe = Canon;
2345 }
2346 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002347 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002348 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002349 }
Steve Naroff9752f252007-08-01 18:02:17 +00002350 Types.push_back(toe);
2351 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002352}
2353
Steve Naroff9752f252007-08-01 18:02:17 +00002354/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2355/// TypeOfType AST's. The only motivation to unique these nodes would be
2356/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002357/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002358/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002359QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002360 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002361 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002362 Types.push_back(tot);
2363 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002364}
2365
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002366/// getDecltypeForExpr - Given an expr, will return the decltype for that
2367/// expression, according to the rules in C++0x [dcl.type.simple]p4
2368static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002369 if (e->isTypeDependent())
2370 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002371
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002372 // If e is an id expression or a class member access, decltype(e) is defined
2373 // as the type of the entity named by e.
2374 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2375 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2376 return VD->getType();
2377 }
2378 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2379 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2380 return FD->getType();
2381 }
2382 // If e is a function call or an invocation of an overloaded operator,
2383 // (parentheses around e are ignored), decltype(e) is defined as the
2384 // return type of that function.
2385 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2386 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002387
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002388 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002389
2390 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002391 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002392 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002393 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002395 return T;
2396}
2397
Anders Carlsson395b4752009-06-24 19:06:50 +00002398/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2399/// DecltypeType AST's. The only motivation to unique these nodes would be
2400/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002401/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002402/// on canonical type's (which are always unique).
2403QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002404 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002405 if (e->isTypeDependent()) {
2406 llvm::FoldingSetNodeID ID;
2407 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002408
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002409 void *InsertPos = 0;
2410 DependentDecltypeType *Canon
2411 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2412 if (Canon) {
2413 // We already have a "canonical" version of an equivalent, dependent
2414 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002415 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002416 QualType((DecltypeType*)Canon, 0));
2417 }
2418 else {
2419 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002420 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002421 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2422 dt = Canon;
2423 }
2424 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002425 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002426 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002427 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002428 Types.push_back(dt);
2429 return QualType(dt, 0);
2430}
2431
Reid Spencer5f016e22007-07-11 17:01:13 +00002432/// getTagDeclType - Return the unique reference to the type for the
2433/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002434QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002435 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002436 // FIXME: What is the design on getTagDeclType when it requires casting
2437 // away const? mutable?
2438 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002439}
2440
Mike Stump1eb44332009-09-09 15:08:12 +00002441/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2442/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2443/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002444CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002445 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002446}
2447
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002448/// getSignedWCharType - Return the type of "signed wchar_t".
2449/// Used when in C++, as a GCC extension.
2450QualType ASTContext::getSignedWCharType() const {
2451 // FIXME: derive from "Target" ?
2452 return WCharTy;
2453}
2454
2455/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2456/// Used when in C++, as a GCC extension.
2457QualType ASTContext::getUnsignedWCharType() const {
2458 // FIXME: derive from "Target" ?
2459 return UnsignedIntTy;
2460}
2461
Chris Lattner8b9023b2007-07-13 03:05:23 +00002462/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2463/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2464QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002465 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002466}
2467
Chris Lattnere6327742008-04-02 05:18:44 +00002468//===----------------------------------------------------------------------===//
2469// Type Operators
2470//===----------------------------------------------------------------------===//
2471
John McCall54e14c42009-10-22 22:37:11 +00002472CanQualType ASTContext::getCanonicalParamType(QualType T) {
2473 // Push qualifiers into arrays, and then discard any remaining
2474 // qualifiers.
2475 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002476 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002477 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002478 QualType Result;
2479 if (isa<ArrayType>(Ty)) {
2480 Result = getArrayDecayedType(QualType(Ty,0));
2481 } else if (isa<FunctionType>(Ty)) {
2482 Result = getPointerType(QualType(Ty, 0));
2483 } else {
2484 Result = QualType(Ty, 0);
2485 }
2486
2487 return CanQualType::CreateUnsafe(Result);
2488}
2489
Chris Lattner77c96472008-04-06 22:41:35 +00002490/// getCanonicalType - Return the canonical (structural) type corresponding to
2491/// the specified potentially non-canonical type. The non-canonical version
2492/// of a type may have many "decorated" versions of types. Decorators can
2493/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2494/// to be free of any of these, allowing two canonical types to be compared
2495/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002496CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002497 QualifierCollector Quals;
2498 const Type *Ptr = Quals.strip(T);
2499 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002500
John McCall0953e762009-09-24 19:53:00 +00002501 // The canonical internal type will be the canonical type *except*
2502 // that we push type qualifiers down through array types.
2503
2504 // If there are no new qualifiers to push down, stop here.
2505 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002506 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002507
John McCall0953e762009-09-24 19:53:00 +00002508 // If the type qualifiers are on an array type, get the canonical
2509 // type of the array with the qualifiers applied to the element
2510 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002511 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2512 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002513 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002514
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002515 // Get the canonical version of the element with the extra qualifiers on it.
2516 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002517 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002518 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002519
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002520 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002521 return CanQualType::CreateUnsafe(
2522 getConstantArrayType(NewEltTy, CAT->getSize(),
2523 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002524 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002525 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002526 return CanQualType::CreateUnsafe(
2527 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002528 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002529
Douglas Gregor898574e2008-12-05 23:32:09 +00002530 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002531 return CanQualType::CreateUnsafe(
2532 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00002533 DSAT->getSizeExpr(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002534 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002535 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002536 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002537
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002538 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002539 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00002540 VAT->getSizeExpr(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002541 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002542 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002543 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002544}
2545
Chandler Carruth28e318c2009-12-29 07:16:59 +00002546QualType ASTContext::getUnqualifiedArrayType(QualType T,
2547 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002548 Quals = T.getQualifiers();
Douglas Gregor9dadd942010-05-17 18:45:21 +00002549 const ArrayType *AT = getAsArrayType(T);
2550 if (!AT) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002551 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002552 }
2553
Chandler Carruth28e318c2009-12-29 07:16:59 +00002554 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002555 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002556 if (Elt == UnqualElt)
2557 return T;
2558
Douglas Gregor9dadd942010-05-17 18:45:21 +00002559 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002560 return getConstantArrayType(UnqualElt, CAT->getSize(),
2561 CAT->getSizeModifier(), 0);
2562 }
2563
Douglas Gregor9dadd942010-05-17 18:45:21 +00002564 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth28e318c2009-12-29 07:16:59 +00002565 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2566 }
2567
Douglas Gregor9dadd942010-05-17 18:45:21 +00002568 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2569 return getVariableArrayType(UnqualElt,
John McCall3fa5cae2010-10-26 07:05:15 +00002570 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00002571 VAT->getSizeModifier(),
2572 VAT->getIndexTypeCVRQualifiers(),
2573 VAT->getBracketsRange());
2574 }
2575
2576 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall3fa5cae2010-10-26 07:05:15 +00002577 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002578 DSAT->getSizeModifier(), 0,
2579 SourceRange());
2580}
2581
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002582/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2583/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2584/// they point to and return true. If T1 and T2 aren't pointer types
2585/// or pointer-to-member types, or if they are not similar at this
2586/// level, returns false and leaves T1 and T2 unchanged. Top-level
2587/// qualifiers on T1 and T2 are ignored. This function will typically
2588/// be called in a loop that successively "unwraps" pointer and
2589/// pointer-to-member types to compare them at each level.
2590bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2591 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2592 *T2PtrType = T2->getAs<PointerType>();
2593 if (T1PtrType && T2PtrType) {
2594 T1 = T1PtrType->getPointeeType();
2595 T2 = T2PtrType->getPointeeType();
2596 return true;
2597 }
2598
2599 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2600 *T2MPType = T2->getAs<MemberPointerType>();
2601 if (T1MPType && T2MPType &&
2602 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2603 QualType(T2MPType->getClass(), 0))) {
2604 T1 = T1MPType->getPointeeType();
2605 T2 = T2MPType->getPointeeType();
2606 return true;
2607 }
2608
2609 if (getLangOptions().ObjC1) {
2610 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2611 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2612 if (T1OPType && T2OPType) {
2613 T1 = T1OPType->getPointeeType();
2614 T2 = T2OPType->getPointeeType();
2615 return true;
2616 }
2617 }
2618
2619 // FIXME: Block pointers, too?
2620
2621 return false;
2622}
2623
Abramo Bagnara25777432010-08-11 22:01:17 +00002624DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name,
2625 SourceLocation NameLoc) {
John McCall80ad16f2009-11-24 18:42:40 +00002626 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002627 // DNInfo work in progress: CHECKME: what about DNLoc?
2628 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2629
John McCall80ad16f2009-11-24 18:42:40 +00002630 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002631 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002632 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002633 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2634 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002635 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00002636 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2637 // DNInfo work in progress: FIXME: source locations?
2638 DeclarationNameLoc DNLoc;
2639 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2640 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2641 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002642 }
2643 }
2644
John McCall0bd6feb2009-12-02 08:04:21 +00002645 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2646 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002647 // DNInfo work in progress: CHECKME: what about DNLoc?
2648 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002649}
2650
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002651TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002652 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2653 if (TemplateTemplateParmDecl *TTP
2654 = dyn_cast<TemplateTemplateParmDecl>(Template))
2655 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2656
2657 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002658 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002659 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002660
John McCall0bd6feb2009-12-02 08:04:21 +00002661 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002662
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002663 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2664 assert(DTN && "Non-dependent template names must refer to template decls.");
2665 return DTN->CanonicalTemplateName;
2666}
2667
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002668bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2669 X = getCanonicalTemplateName(X);
2670 Y = getCanonicalTemplateName(Y);
2671 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2672}
2673
Mike Stump1eb44332009-09-09 15:08:12 +00002674TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002675ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2676 switch (Arg.getKind()) {
2677 case TemplateArgument::Null:
2678 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Douglas Gregor1275ae02009-07-28 23:00:59 +00002680 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002681 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002682
Douglas Gregor1275ae02009-07-28 23:00:59 +00002683 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002684 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002685
Douglas Gregor788cd062009-11-11 01:00:40 +00002686 case TemplateArgument::Template:
2687 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2688
Douglas Gregor1275ae02009-07-28 23:00:59 +00002689 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002690 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002691 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002692
Douglas Gregor1275ae02009-07-28 23:00:59 +00002693 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002694 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Douglas Gregor1275ae02009-07-28 23:00:59 +00002696 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00002697 if (Arg.pack_size() == 0)
2698 return Arg;
2699
Douglas Gregor910f8002010-11-07 23:05:16 +00002700 TemplateArgument *CanonArgs
2701 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00002702 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002703 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002704 AEnd = Arg.pack_end();
2705 A != AEnd; (void)++A, ++Idx)
2706 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002707
Douglas Gregor910f8002010-11-07 23:05:16 +00002708 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00002709 }
2710 }
2711
2712 // Silence GCC warning
2713 assert(false && "Unhandled template argument kind");
2714 return TemplateArgument();
2715}
2716
Douglas Gregord57959a2009-03-27 23:10:48 +00002717NestedNameSpecifier *
2718ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002719 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002720 return 0;
2721
2722 switch (NNS->getKind()) {
2723 case NestedNameSpecifier::Identifier:
2724 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002725 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002726 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2727 NNS->getAsIdentifier());
2728
2729 case NestedNameSpecifier::Namespace:
2730 // A namespace is canonical; build a nested-name-specifier with
2731 // this namespace and no prefix.
2732 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2733
2734 case NestedNameSpecifier::TypeSpec:
2735 case NestedNameSpecifier::TypeSpecWithTemplate: {
2736 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00002737
2738 // If we have some kind of dependent-named type (e.g., "typename T::type"),
2739 // break it apart into its prefix and identifier, then reconsititute those
2740 // as the canonical nested-name-specifier. This is required to canonicalize
2741 // a dependent nested-name-specifier involving typedefs of dependent-name
2742 // types, e.g.,
2743 // typedef typename T::type T1;
2744 // typedef typename T1::type T2;
2745 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
2746 NestedNameSpecifier *Prefix
2747 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
2748 return NestedNameSpecifier::Create(*this, Prefix,
2749 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
2750 }
2751
Douglas Gregor643f8432010-11-04 00:14:23 +00002752 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00002753 if (const DependentTemplateSpecializationType *DTST
2754 = T->getAs<DependentTemplateSpecializationType>()) {
2755 NestedNameSpecifier *Prefix
2756 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
2757 TemplateName Name
2758 = getDependentTemplateName(Prefix, DTST->getIdentifier());
2759 T = getTemplateSpecializationType(Name,
2760 DTST->getArgs(), DTST->getNumArgs());
2761 T = getCanonicalType(T);
2762 }
2763
2764 return NestedNameSpecifier::Create(*this, 0, false, T.getTypePtr());
Douglas Gregord57959a2009-03-27 23:10:48 +00002765 }
2766
2767 case NestedNameSpecifier::Global:
2768 // The global specifier is canonical and unique.
2769 return NNS;
2770 }
2771
2772 // Required to silence a GCC warning
2773 return 0;
2774}
2775
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002776
2777const ArrayType *ASTContext::getAsArrayType(QualType T) {
2778 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002779 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002780 // Handle the common positive case fast.
2781 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2782 return AT;
2783 }
Mike Stump1eb44332009-09-09 15:08:12 +00002784
John McCall0953e762009-09-24 19:53:00 +00002785 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002786 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002787 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002788 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002789
John McCall0953e762009-09-24 19:53:00 +00002790 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002791 // implements C99 6.7.3p8: "If the specification of an array type includes
2792 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002793
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002794 // If we get here, we either have type qualifiers on the type, or we have
2795 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002796 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002797
John McCall0953e762009-09-24 19:53:00 +00002798 QualifierCollector Qs;
John McCall49f4e1c2010-12-10 11:01:00 +00002799 const Type *Ty = Qs.strip(T.getDesugaredType(*this));
Mike Stump1eb44332009-09-09 15:08:12 +00002800
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002801 // If we have a simple case, just return now.
2802 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002803 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002804 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002805
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002806 // Otherwise, we have an array and we have qualifiers on it. Push the
2807 // qualifiers into the array element type and return a new array type.
2808 // Get the canonical version of the element with the extra qualifiers on it.
2809 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002810 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002811
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002812 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2813 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2814 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002815 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002816 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2817 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2818 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002819 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002820
Mike Stump1eb44332009-09-09 15:08:12 +00002821 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002822 = dyn_cast<DependentSizedArrayType>(ATy))
2823 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002824 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00002825 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00002826 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002827 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002828 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002829
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002830 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002831 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00002832 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002833 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002834 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002835 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002836}
2837
Chris Lattnere6327742008-04-02 05:18:44 +00002838/// getArrayDecayedType - Return the properly qualified result of decaying the
2839/// specified array type to a pointer. This operation is non-trivial when
2840/// handling typedefs etc. The canonical type of "T" must be an array type,
2841/// this returns a pointer to a properly qualified element of the array.
2842///
2843/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2844QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002845 // Get the element type with 'getAsArrayType' so that we don't lose any
2846 // typedefs in the element type of the array. This also handles propagation
2847 // of type qualifiers from the array type into the element type if present
2848 // (C99 6.7.3p8).
2849 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2850 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002852 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002853
2854 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002855 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002856}
2857
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002858QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002859 QualifierCollector Qs;
Benjamin Kramer02379412010-04-27 17:12:11 +00002860 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2861 QT = AT->getElementType();
John McCall49f4e1c2010-12-10 11:01:00 +00002862 return Qs.apply(*this, QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002863}
2864
Anders Carlssonfbbce492009-09-25 01:23:32 +00002865QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2866 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002867
Anders Carlssonfbbce492009-09-25 01:23:32 +00002868 if (const ArrayType *AT = getAsArrayType(ElemTy))
2869 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002870
Anders Carlsson6183a992008-12-21 03:44:36 +00002871 return ElemTy;
2872}
2873
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002874/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002875uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002876ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2877 uint64_t ElementCount = 1;
2878 do {
2879 ElementCount *= CA->getSize().getZExtValue();
2880 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2881 } while (CA);
2882 return ElementCount;
2883}
2884
Reid Spencer5f016e22007-07-11 17:01:13 +00002885/// getFloatingRank - Return a relative rank for floating point types.
2886/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002887static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002888 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002889 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002890
John McCall183700f2009-09-21 23:43:11 +00002891 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2892 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002893 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002894 case BuiltinType::Float: return FloatRank;
2895 case BuiltinType::Double: return DoubleRank;
2896 case BuiltinType::LongDouble: return LongDoubleRank;
2897 }
2898}
2899
Mike Stump1eb44332009-09-09 15:08:12 +00002900/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2901/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002902/// 'typeDomain' is a real floating point or complex type.
2903/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002904QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2905 QualType Domain) const {
2906 FloatingRank EltRank = getFloatingRank(Size);
2907 if (Domain->isComplexType()) {
2908 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002909 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002910 case FloatRank: return FloatComplexTy;
2911 case DoubleRank: return DoubleComplexTy;
2912 case LongDoubleRank: return LongDoubleComplexTy;
2913 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002914 }
Chris Lattner1361b112008-04-06 23:58:54 +00002915
2916 assert(Domain->isRealFloatingType() && "Unknown domain!");
2917 switch (EltRank) {
2918 default: assert(0 && "getFloatingRank(): illegal value for rank");
2919 case FloatRank: return FloatTy;
2920 case DoubleRank: return DoubleTy;
2921 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002922 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002923}
2924
Chris Lattner7cfeb082008-04-06 23:55:33 +00002925/// getFloatingTypeOrder - Compare the rank of the two specified floating
2926/// point types, ignoring the domain of the type (i.e. 'double' ==
2927/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002928/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002929int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2930 FloatingRank LHSR = getFloatingRank(LHS);
2931 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002932
Chris Lattnera75cea32008-04-06 23:38:49 +00002933 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002934 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002935 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002936 return 1;
2937 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002938}
2939
Chris Lattnerf52ab252008-04-06 22:59:24 +00002940/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2941/// routine will assert if passed a built-in type that isn't an integer or enum,
2942/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002943unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002944 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002945 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002946 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002947
Eli Friedmana3426752009-07-05 23:44:27 +00002948 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2949 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2950
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002951 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2952 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2953
2954 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2955 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2956
Chris Lattnerf52ab252008-04-06 22:59:24 +00002957 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002958 default: assert(0 && "getIntegerRank(): not a built-in integer");
2959 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002960 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002961 case BuiltinType::Char_S:
2962 case BuiltinType::Char_U:
2963 case BuiltinType::SChar:
2964 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002965 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002966 case BuiltinType::Short:
2967 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002968 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002969 case BuiltinType::Int:
2970 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002971 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002972 case BuiltinType::Long:
2973 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002974 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002975 case BuiltinType::LongLong:
2976 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002977 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002978 case BuiltinType::Int128:
2979 case BuiltinType::UInt128:
2980 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002981 }
2982}
2983
Eli Friedman04e83572009-08-20 04:21:42 +00002984/// \brief Whether this is a promotable bitfield reference according
2985/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2986///
2987/// \returns the type this bit-field will promote to, or NULL if no
2988/// promotion occurs.
2989QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregorceafbde2010-05-24 20:13:53 +00002990 if (E->isTypeDependent() || E->isValueDependent())
2991 return QualType();
2992
Eli Friedman04e83572009-08-20 04:21:42 +00002993 FieldDecl *Field = E->getBitField();
2994 if (!Field)
2995 return QualType();
2996
2997 QualType FT = Field->getType();
2998
2999 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3000 uint64_t BitWidth = BitWidthAP.getZExtValue();
3001 uint64_t IntSize = getTypeSize(IntTy);
3002 // GCC extension compatibility: if the bit-field size is less than or equal
3003 // to the size of int, it gets promoted no matter what its type is.
3004 // For instance, unsigned long bf : 4 gets promoted to signed int.
3005 if (BitWidth < IntSize)
3006 return IntTy;
3007
3008 if (BitWidth == IntSize)
3009 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3010
3011 // Types bigger than int are not subject to promotions, and therefore act
3012 // like the base type.
3013 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3014 // is ridiculous.
3015 return QualType();
3016}
3017
Eli Friedmana95d7572009-08-19 07:44:53 +00003018/// getPromotedIntegerType - Returns the type that Promotable will
3019/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3020/// integer type.
3021QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
3022 assert(!Promotable.isNull());
3023 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003024 if (const EnumType *ET = Promotable->getAs<EnumType>())
3025 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003026 if (Promotable->isSignedIntegerType())
3027 return IntTy;
3028 uint64_t PromotableSize = getTypeSize(Promotable);
3029 uint64_t IntSize = getTypeSize(IntTy);
3030 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3031 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3032}
3033
Mike Stump1eb44332009-09-09 15:08:12 +00003034/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003035/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003036/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003037int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003038 Type *LHSC = getCanonicalType(LHS).getTypePtr();
3039 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003040 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Chris Lattnerf52ab252008-04-06 22:59:24 +00003042 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3043 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Chris Lattner7cfeb082008-04-06 23:55:33 +00003045 unsigned LHSRank = getIntegerRank(LHSC);
3046 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003047
Chris Lattner7cfeb082008-04-06 23:55:33 +00003048 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3049 if (LHSRank == RHSRank) return 0;
3050 return LHSRank > RHSRank ? 1 : -1;
3051 }
Mike Stump1eb44332009-09-09 15:08:12 +00003052
Chris Lattner7cfeb082008-04-06 23:55:33 +00003053 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3054 if (LHSUnsigned) {
3055 // If the unsigned [LHS] type is larger, return it.
3056 if (LHSRank >= RHSRank)
3057 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003058
Chris Lattner7cfeb082008-04-06 23:55:33 +00003059 // If the signed type can represent all values of the unsigned type, it
3060 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003061 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003062 return -1;
3063 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003064
Chris Lattner7cfeb082008-04-06 23:55:33 +00003065 // If the unsigned [RHS] type is larger, return it.
3066 if (RHSRank >= LHSRank)
3067 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003068
Chris Lattner7cfeb082008-04-06 23:55:33 +00003069 // If the signed type can represent all values of the unsigned type, it
3070 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003071 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003072 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003073}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003074
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003075static RecordDecl *
3076CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3077 SourceLocation L, IdentifierInfo *Id) {
3078 if (Ctx.getLangOptions().CPlusPlus)
3079 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3080 else
3081 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3082}
3083
Mike Stump1eb44332009-09-09 15:08:12 +00003084// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00003085QualType ASTContext::getCFConstantStringType() {
3086 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003087 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003088 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003089 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003090 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003091
Anders Carlssonf06273f2007-11-19 00:25:30 +00003092 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003093
Anders Carlsson71993dd2007-08-17 05:31:46 +00003094 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003095 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003096 // int flags;
3097 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003098 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003099 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003100 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003101 FieldTypes[3] = LongTy;
3102
Anders Carlsson71993dd2007-08-17 05:31:46 +00003103 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003104 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003105 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003106 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003107 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003108 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003109 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003110 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003111 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003112 }
3113
Douglas Gregor838db382010-02-11 01:19:42 +00003114 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003115 }
Mike Stump1eb44332009-09-09 15:08:12 +00003116
Anders Carlsson71993dd2007-08-17 05:31:46 +00003117 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003118}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003119
Douglas Gregor319ac892009-04-23 22:29:11 +00003120void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003121 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003122 assert(Rec && "Invalid CFConstantStringType");
3123 CFConstantStringTypeDecl = Rec->getDecl();
3124}
3125
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003126// getNSConstantStringType - Return the type used for constant NSStrings.
3127QualType ASTContext::getNSConstantStringType() {
3128 if (!NSConstantStringTypeDecl) {
3129 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003130 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003131 &Idents.get("__builtin_NSString"));
3132 NSConstantStringTypeDecl->startDefinition();
3133
3134 QualType FieldTypes[3];
3135
3136 // const int *isa;
3137 FieldTypes[0] = getPointerType(IntTy.withConst());
3138 // const char *str;
3139 FieldTypes[1] = getPointerType(CharTy.withConst());
3140 // unsigned int length;
3141 FieldTypes[2] = UnsignedIntTy;
3142
3143 // Create fields
3144 for (unsigned i = 0; i < 3; ++i) {
3145 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3146 SourceLocation(), 0,
3147 FieldTypes[i], /*TInfo=*/0,
3148 /*BitWidth=*/0,
3149 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003150 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003151 NSConstantStringTypeDecl->addDecl(Field);
3152 }
3153
3154 NSConstantStringTypeDecl->completeDefinition();
3155 }
3156
3157 return getTagDeclType(NSConstantStringTypeDecl);
3158}
3159
3160void ASTContext::setNSConstantStringType(QualType T) {
3161 const RecordType *Rec = T->getAs<RecordType>();
3162 assert(Rec && "Invalid NSConstantStringType");
3163 NSConstantStringTypeDecl = Rec->getDecl();
3164}
3165
Mike Stump1eb44332009-09-09 15:08:12 +00003166QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003167 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003168 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003169 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003170 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003171 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003172
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003173 QualType FieldTypes[] = {
3174 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003175 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003176 getPointerType(UnsignedLongTy),
3177 getConstantArrayType(UnsignedLongTy,
3178 llvm::APInt(32, 5), ArrayType::Normal, 0)
3179 };
Mike Stump1eb44332009-09-09 15:08:12 +00003180
Douglas Gregor44b43212008-12-11 16:49:14 +00003181 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003182 FieldDecl *Field = FieldDecl::Create(*this,
3183 ObjCFastEnumerationStateTypeDecl,
3184 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003185 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003186 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003187 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003188 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003189 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003190 }
Mike Stump1eb44332009-09-09 15:08:12 +00003191
Douglas Gregor838db382010-02-11 01:19:42 +00003192 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003193 }
Mike Stump1eb44332009-09-09 15:08:12 +00003194
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003195 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3196}
3197
Mike Stumpadaaad32009-10-20 02:12:22 +00003198QualType ASTContext::getBlockDescriptorType() {
3199 if (BlockDescriptorType)
3200 return getTagDeclType(BlockDescriptorType);
3201
3202 RecordDecl *T;
3203 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003204 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003205 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003206 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003207
3208 QualType FieldTypes[] = {
3209 UnsignedLongTy,
3210 UnsignedLongTy,
3211 };
3212
3213 const char *FieldNames[] = {
3214 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003215 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003216 };
3217
3218 for (size_t i = 0; i < 2; ++i) {
3219 FieldDecl *Field = FieldDecl::Create(*this,
3220 T,
3221 SourceLocation(),
3222 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003223 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003224 /*BitWidth=*/0,
3225 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003226 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003227 T->addDecl(Field);
3228 }
3229
Douglas Gregor838db382010-02-11 01:19:42 +00003230 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003231
3232 BlockDescriptorType = T;
3233
3234 return getTagDeclType(BlockDescriptorType);
3235}
3236
3237void ASTContext::setBlockDescriptorType(QualType T) {
3238 const RecordType *Rec = T->getAs<RecordType>();
3239 assert(Rec && "Invalid BlockDescriptorType");
3240 BlockDescriptorType = Rec->getDecl();
3241}
3242
Mike Stump083c25e2009-10-22 00:49:09 +00003243QualType ASTContext::getBlockDescriptorExtendedType() {
3244 if (BlockDescriptorExtendedType)
3245 return getTagDeclType(BlockDescriptorExtendedType);
3246
3247 RecordDecl *T;
3248 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003249 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003250 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003251 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003252
3253 QualType FieldTypes[] = {
3254 UnsignedLongTy,
3255 UnsignedLongTy,
3256 getPointerType(VoidPtrTy),
3257 getPointerType(VoidPtrTy)
3258 };
3259
3260 const char *FieldNames[] = {
3261 "reserved",
3262 "Size",
3263 "CopyFuncPtr",
3264 "DestroyFuncPtr"
3265 };
3266
3267 for (size_t i = 0; i < 4; ++i) {
3268 FieldDecl *Field = FieldDecl::Create(*this,
3269 T,
3270 SourceLocation(),
3271 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003272 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003273 /*BitWidth=*/0,
3274 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003275 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003276 T->addDecl(Field);
3277 }
3278
Douglas Gregor838db382010-02-11 01:19:42 +00003279 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003280
3281 BlockDescriptorExtendedType = T;
3282
3283 return getTagDeclType(BlockDescriptorExtendedType);
3284}
3285
3286void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3287 const RecordType *Rec = T->getAs<RecordType>();
3288 assert(Rec && "Invalid BlockDescriptorType");
3289 BlockDescriptorExtendedType = Rec->getDecl();
3290}
3291
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003292bool ASTContext::BlockRequiresCopying(QualType Ty) {
3293 if (Ty->isBlockPointerType())
3294 return true;
3295 if (isObjCNSObjectType(Ty))
3296 return true;
3297 if (Ty->isObjCObjectPointerType())
3298 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003299 if (getLangOptions().CPlusPlus) {
3300 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3301 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3302 return RD->hasConstCopyConstructor(*this);
3303
3304 }
3305 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003306 return false;
3307}
3308
Daniel Dunbar4087f272010-08-17 22:39:59 +00003309QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003310 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003311 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003312 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003313 // unsigned int __flags;
3314 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003315 // void *__copy_helper; // as needed
3316 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003317 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003318 // } *
3319
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003320 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3321
3322 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003323 llvm::SmallString<36> Name;
3324 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3325 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003326 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003327 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003328 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003329 T->startDefinition();
3330 QualType Int32Ty = IntTy;
3331 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3332 QualType FieldTypes[] = {
3333 getPointerType(VoidPtrTy),
3334 getPointerType(getTagDeclType(T)),
3335 Int32Ty,
3336 Int32Ty,
3337 getPointerType(VoidPtrTy),
3338 getPointerType(VoidPtrTy),
3339 Ty
3340 };
3341
Daniel Dunbar4087f272010-08-17 22:39:59 +00003342 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003343 "__isa",
3344 "__forwarding",
3345 "__flags",
3346 "__size",
3347 "__copy_helper",
3348 "__destroy_helper",
3349 DeclName,
3350 };
3351
3352 for (size_t i = 0; i < 7; ++i) {
3353 if (!HasCopyAndDispose && i >=4 && i <= 5)
3354 continue;
3355 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3356 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003357 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003358 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003359 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003360 T->addDecl(Field);
3361 }
3362
Douglas Gregor838db382010-02-11 01:19:42 +00003363 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003364
3365 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003366}
3367
3368
3369QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003370 bool BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +00003371 llvm::SmallVectorImpl<const Expr *> &Layout) {
3372
Mike Stumpadaaad32009-10-20 02:12:22 +00003373 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003374 llvm::SmallString<36> Name;
3375 llvm::raw_svector_ostream(Name) << "__block_literal_"
3376 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003377 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003378 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003379 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003380 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003381 QualType FieldTypes[] = {
3382 getPointerType(VoidPtrTy),
3383 IntTy,
3384 IntTy,
3385 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003386 (BlockHasCopyDispose ?
3387 getPointerType(getBlockDescriptorExtendedType()) :
3388 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003389 };
3390
3391 const char *FieldNames[] = {
3392 "__isa",
3393 "__flags",
3394 "__reserved",
3395 "__FuncPtr",
3396 "__descriptor"
3397 };
3398
3399 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003400 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003401 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003402 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003403 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003404 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003405 T->addDecl(Field);
3406 }
3407
John McCallea1471e2010-05-20 01:18:31 +00003408 for (unsigned i = 0; i < Layout.size(); ++i) {
3409 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003410
John McCallea1471e2010-05-20 01:18:31 +00003411 QualType FieldType = E->getType();
3412 IdentifierInfo *FieldName = 0;
3413 if (isa<CXXThisExpr>(E)) {
3414 FieldName = &Idents.get("this");
3415 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3416 const ValueDecl *D = BDRE->getDecl();
3417 FieldName = D->getIdentifier();
3418 if (BDRE->isByRef())
Daniel Dunbar4087f272010-08-17 22:39:59 +00003419 FieldType = BuildByRefType(D->getName(), FieldType);
John McCallea1471e2010-05-20 01:18:31 +00003420 } else {
3421 // Padding.
3422 assert(isa<ConstantArrayType>(FieldType) &&
3423 isa<DeclRefExpr>(E) &&
3424 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3425 "doesn't match characteristics of padding decl");
3426 }
Mike Stumpea26cb52009-10-21 03:49:08 +00003427
3428 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003429 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003430 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003431 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003432 T->addDecl(Field);
3433 }
3434
Douglas Gregor838db382010-02-11 01:19:42 +00003435 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003436
3437 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003438}
3439
Douglas Gregor319ac892009-04-23 22:29:11 +00003440void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003441 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003442 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3443 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3444}
3445
Anders Carlssone8c49532007-10-29 06:33:42 +00003446// This returns true if a type has been typedefed to BOOL:
3447// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003448static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003449 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003450 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3451 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003452
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003453 return false;
3454}
3455
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003456/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003457/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003458CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003459 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003460
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003461 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003462 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003463 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003464 // Treat arrays as pointers, since that's how they're passed in.
3465 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003466 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003467 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003468}
3469
3470static inline
3471std::string charUnitsToString(const CharUnits &CU) {
3472 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003473}
3474
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003475/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003476/// declaration.
3477void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3478 std::string& S) {
3479 const BlockDecl *Decl = Expr->getBlockDecl();
3480 QualType BlockTy =
3481 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3482 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003483 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003484 // Compute size of all parameters.
3485 // Start with computing size of a pointer in number of bytes.
3486 // FIXME: There might(should) be a better way of doing this computation!
3487 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003488 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3489 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003490 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003491 E = Decl->param_end(); PI != E; ++PI) {
3492 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003493 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003494 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003495 ParmOffset += sz;
3496 }
3497 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003498 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003499 // Block pointer and offset.
3500 S += "@?0";
3501 ParmOffset = PtrSize;
3502
3503 // Argument types.
3504 ParmOffset = PtrSize;
3505 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3506 Decl->param_end(); PI != E; ++PI) {
3507 ParmVarDecl *PVDecl = *PI;
3508 QualType PType = PVDecl->getOriginalType();
3509 if (const ArrayType *AT =
3510 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3511 // Use array's original type only if it has known number of
3512 // elements.
3513 if (!isa<ConstantArrayType>(AT))
3514 PType = PVDecl->getType();
3515 } else if (PType->isFunctionType())
3516 PType = PVDecl->getType();
3517 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003518 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003519 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003520 }
3521}
3522
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003523/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003524/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003525void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003526 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003527 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003528 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003529 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003530 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003531 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003532 // Compute size of all parameters.
3533 // Start with computing size of a pointer in number of bytes.
3534 // FIXME: There might(should) be a better way of doing this computation!
3535 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003536 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003537 // The first two arguments (self and _cmd) are pointers; account for
3538 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003539 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003540 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003541 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003542 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003543 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003544 assert (sz.isPositive() &&
3545 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003546 ParmOffset += sz;
3547 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003548 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003549 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003550 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003551
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003552 // Argument types.
3553 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003554 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003555 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003556 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003557 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003558 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003559 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3560 // Use array's original type only if it has known number of
3561 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003562 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003563 PType = PVDecl->getType();
3564 } else if (PType->isFunctionType())
3565 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003566 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003567 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003568 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003569 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003570 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003571 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003572 }
3573}
3574
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003575/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003576/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003577/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3578/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003579/// Property attributes are stored as a comma-delimited C string. The simple
3580/// attributes readonly and bycopy are encoded as single characters. The
3581/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3582/// encoded as single characters, followed by an identifier. Property types
3583/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003584/// these attributes are defined by the following enumeration:
3585/// @code
3586/// enum PropertyAttributes {
3587/// kPropertyReadOnly = 'R', // property is read-only.
3588/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3589/// kPropertyByref = '&', // property is a reference to the value last assigned
3590/// kPropertyDynamic = 'D', // property is dynamic
3591/// kPropertyGetter = 'G', // followed by getter selector name
3592/// kPropertySetter = 'S', // followed by setter selector name
3593/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3594/// kPropertyType = 't' // followed by old-style type encoding.
3595/// kPropertyWeak = 'W' // 'weak' property
3596/// kPropertyStrong = 'P' // property GC'able
3597/// kPropertyNonAtomic = 'N' // property non-atomic
3598/// };
3599/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003600void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003601 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003602 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003603 // Collect information from the property implementation decl(s).
3604 bool Dynamic = false;
3605 ObjCPropertyImplDecl *SynthesizePID = 0;
3606
3607 // FIXME: Duplicated code due to poor abstraction.
3608 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003609 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003610 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3611 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003612 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003613 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003614 ObjCPropertyImplDecl *PID = *i;
3615 if (PID->getPropertyDecl() == PD) {
3616 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3617 Dynamic = true;
3618 } else {
3619 SynthesizePID = PID;
3620 }
3621 }
3622 }
3623 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003624 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003625 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003626 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003627 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003628 ObjCPropertyImplDecl *PID = *i;
3629 if (PID->getPropertyDecl() == PD) {
3630 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3631 Dynamic = true;
3632 } else {
3633 SynthesizePID = PID;
3634 }
3635 }
Mike Stump1eb44332009-09-09 15:08:12 +00003636 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003637 }
3638 }
3639
3640 // FIXME: This is not very efficient.
3641 S = "T";
3642
3643 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003644 // GCC has some special rules regarding encoding of properties which
3645 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003646 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003647 true /* outermost type */,
3648 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003649
3650 if (PD->isReadOnly()) {
3651 S += ",R";
3652 } else {
3653 switch (PD->getSetterKind()) {
3654 case ObjCPropertyDecl::Assign: break;
3655 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003656 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003657 }
3658 }
3659
3660 // It really isn't clear at all what this means, since properties
3661 // are "dynamic by default".
3662 if (Dynamic)
3663 S += ",D";
3664
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003665 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3666 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003667
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003668 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3669 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003670 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003671 }
3672
3673 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3674 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003675 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003676 }
3677
3678 if (SynthesizePID) {
3679 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3680 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003681 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003682 }
3683
3684 // FIXME: OBJCGC: weak & strong
3685}
3686
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003687/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003688/// Another legacy compatibility encoding: 32-bit longs are encoded as
3689/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003690/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3691///
3692void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003693 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003694 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003695 if (BT->getKind() == BuiltinType::ULong &&
3696 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003697 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003698 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003699 if (BT->getKind() == BuiltinType::Long &&
3700 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003701 PointeeTy = IntTy;
3702 }
3703 }
3704}
3705
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003706void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003707 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003708 // We follow the behavior of gcc, expanding structures which are
3709 // directly pointed to, and expanding embedded structures. Note that
3710 // these rules are sufficient to prevent recursive encoding of the
3711 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003712 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003713 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003714}
3715
David Chisnall64fd7e82010-06-04 01:10:52 +00003716static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3717 switch (T->getAs<BuiltinType>()->getKind()) {
3718 default: assert(0 && "Unhandled builtin type kind");
3719 case BuiltinType::Void: return 'v';
3720 case BuiltinType::Bool: return 'B';
3721 case BuiltinType::Char_U:
3722 case BuiltinType::UChar: return 'C';
3723 case BuiltinType::UShort: return 'S';
3724 case BuiltinType::UInt: return 'I';
3725 case BuiltinType::ULong:
3726 return
3727 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3728 case BuiltinType::UInt128: return 'T';
3729 case BuiltinType::ULongLong: return 'Q';
3730 case BuiltinType::Char_S:
3731 case BuiltinType::SChar: return 'c';
3732 case BuiltinType::Short: return 's';
John McCall24da7092010-06-11 10:11:05 +00003733 case BuiltinType::WChar:
David Chisnall64fd7e82010-06-04 01:10:52 +00003734 case BuiltinType::Int: return 'i';
3735 case BuiltinType::Long:
3736 return
3737 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3738 case BuiltinType::LongLong: return 'q';
3739 case BuiltinType::Int128: return 't';
3740 case BuiltinType::Float: return 'f';
3741 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00003742 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00003743 }
3744}
3745
Mike Stump1eb44332009-09-09 15:08:12 +00003746static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00003747 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003748 const Expr *E = FD->getBitWidth();
3749 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3750 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003751 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00003752 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3753 // The GNU runtime requires more information; bitfields are encoded as b,
3754 // then the offset (in bits) of the first element, then the type of the
3755 // bitfield, then the size in bits. For example, in this structure:
3756 //
3757 // struct
3758 // {
3759 // int integer;
3760 // int flags:2;
3761 // };
3762 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3763 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3764 // information is not especially sensible, but we're stuck with it for
3765 // compatibility with GCC, although providing it breaks anything that
3766 // actually uses runtime introspection and wants to work on both runtimes...
3767 if (!Ctx->getLangOptions().NeXTRuntime) {
3768 const RecordDecl *RD = FD->getParent();
3769 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3770 // FIXME: This same linear search is also used in ExprConstant - it might
3771 // be better if the FieldDecl stored its offset. We'd be increasing the
3772 // size of the object slightly, but saving some time every time it is used.
3773 unsigned i = 0;
3774 for (RecordDecl::field_iterator Field = RD->field_begin(),
3775 FieldEnd = RD->field_end();
3776 Field != FieldEnd; (void)++Field, ++i) {
3777 if (*Field == FD)
3778 break;
3779 }
3780 S += llvm::utostr(RL.getFieldOffset(i));
3781 S += ObjCEncodingForPrimitiveKind(Context, T);
3782 }
3783 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003784 S += llvm::utostr(N);
3785}
3786
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003787// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003788void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3789 bool ExpandPointedToStructures,
3790 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003791 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003792 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003793 bool EncodingProperty) {
David Chisnall64fd7e82010-06-04 01:10:52 +00003794 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003795 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003796 return EncodeBitField(this, S, T, FD);
3797 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003798 return;
3799 }
Mike Stump1eb44332009-09-09 15:08:12 +00003800
John McCall183700f2009-09-21 23:43:11 +00003801 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003802 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003803 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003804 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003805 return;
3806 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003807
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003808 // encoding for pointer or r3eference types.
3809 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003810 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003811 if (PT->isObjCSelType()) {
3812 S += ':';
3813 return;
3814 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003815 PointeeTy = PT->getPointeeType();
3816 }
3817 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3818 PointeeTy = RT->getPointeeType();
3819 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003820 bool isReadOnly = false;
3821 // For historical/compatibility reasons, the read-only qualifier of the
3822 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3823 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003824 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003825 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003826 if (OutermostType && T.isConstQualified()) {
3827 isReadOnly = true;
3828 S += 'r';
3829 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003830 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003831 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003832 while (P->getAs<PointerType>())
3833 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003834 if (P.isConstQualified()) {
3835 isReadOnly = true;
3836 S += 'r';
3837 }
3838 }
3839 if (isReadOnly) {
3840 // Another legacy compatibility encoding. Some ObjC qualifier and type
3841 // combinations need to be rearranged.
3842 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00003843 if (llvm::StringRef(S).endswith("nr"))
3844 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003845 }
Mike Stump1eb44332009-09-09 15:08:12 +00003846
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003847 if (PointeeTy->isCharType()) {
3848 // char pointer types should be encoded as '*' unless it is a
3849 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003850 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003851 S += '*';
3852 return;
3853 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003854 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003855 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3856 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3857 S += '#';
3858 return;
3859 }
3860 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3861 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3862 S += '@';
3863 return;
3864 }
3865 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003866 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003867 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003868 getLegacyIntegralTypeEncoding(PointeeTy);
3869
Mike Stump1eb44332009-09-09 15:08:12 +00003870 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003871 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003872 return;
3873 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00003874
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003875 if (const ArrayType *AT =
3876 // Ignore type qualifiers etc.
3877 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003878 if (isa<IncompleteArrayType>(AT)) {
3879 // Incomplete arrays are encoded as a pointer to the array element.
3880 S += '^';
3881
Mike Stump1eb44332009-09-09 15:08:12 +00003882 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003883 false, ExpandStructures, FD);
3884 } else {
3885 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003886
Anders Carlsson559a8332009-02-22 01:38:57 +00003887 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3888 S += llvm::utostr(CAT->getSize().getZExtValue());
3889 else {
3890 //Variable length arrays are encoded as a regular array with 0 elements.
3891 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3892 S += '0';
3893 }
Mike Stump1eb44332009-09-09 15:08:12 +00003894
3895 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003896 false, ExpandStructures, FD);
3897 S += ']';
3898 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003899 return;
3900 }
Mike Stump1eb44332009-09-09 15:08:12 +00003901
John McCall183700f2009-09-21 23:43:11 +00003902 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003903 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003904 return;
3905 }
Mike Stump1eb44332009-09-09 15:08:12 +00003906
Ted Kremenek6217b802009-07-29 21:53:49 +00003907 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003908 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003909 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003910 // Anonymous structures print as '?'
3911 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3912 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003913 if (ClassTemplateSpecializationDecl *Spec
3914 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3915 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3916 std::string TemplateArgsStr
3917 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00003918 TemplateArgs.data(),
3919 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00003920 (*this).PrintingPolicy);
3921
3922 S += TemplateArgsStr;
3923 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003924 } else {
3925 S += '?';
3926 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003927 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003928 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003929 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3930 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003931 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003932 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003933 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003934 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003935 S += '"';
3936 }
Mike Stump1eb44332009-09-09 15:08:12 +00003937
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003938 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003939 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003940 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003941 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003942 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003943 QualType qt = Field->getType();
3944 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003945 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003946 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003947 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003948 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003949 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003950 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003951 return;
3952 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00003953
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003954 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003955 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00003956 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003957 else
3958 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003959 return;
3960 }
Mike Stump1eb44332009-09-09 15:08:12 +00003961
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003962 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003963 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003964 return;
3965 }
Mike Stump1eb44332009-09-09 15:08:12 +00003966
John McCallc12c5bb2010-05-15 11:32:37 +00003967 // Ignore protocol qualifiers when mangling at this level.
3968 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3969 T = OT->getBaseType();
3970
John McCall0953e762009-09-24 19:53:00 +00003971 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003972 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003973 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003974 S += '{';
3975 const IdentifierInfo *II = OI->getIdentifier();
3976 S += II->getName();
3977 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003978 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
3979 DeepCollectObjCIvars(OI, true, Ivars);
3980 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
3981 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
3982 if (Field->isBitField())
3983 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003984 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003985 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003986 }
3987 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003988 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003989 }
Mike Stump1eb44332009-09-09 15:08:12 +00003990
John McCall183700f2009-09-21 23:43:11 +00003991 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003992 if (OPT->isObjCIdType()) {
3993 S += '@';
3994 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003995 }
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Steve Naroff27d20a22009-10-28 22:03:49 +00003997 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3998 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3999 // Since this is a binary compatibility issue, need to consult with runtime
4000 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004001 S += '#';
4002 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004003 }
Mike Stump1eb44332009-09-09 15:08:12 +00004004
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004005 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004006 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004007 ExpandPointedToStructures,
4008 ExpandStructures, FD);
4009 if (FD || EncodingProperty) {
4010 // Note that we do extended encoding of protocol qualifer list
4011 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004012 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004013 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4014 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004015 S += '<';
4016 S += (*I)->getNameAsString();
4017 S += '>';
4018 }
4019 S += '"';
4020 }
4021 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004022 }
Mike Stump1eb44332009-09-09 15:08:12 +00004023
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004024 QualType PointeeTy = OPT->getPointeeType();
4025 if (!EncodingProperty &&
4026 isa<TypedefType>(PointeeTy.getTypePtr())) {
4027 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004028 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004029 // {...};
4030 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004031 getObjCEncodingForTypeImpl(PointeeTy, S,
4032 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004033 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004034 return;
4035 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004036
4037 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004038 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004039 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004040 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004041 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4042 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004043 S += '<';
4044 S += (*I)->getNameAsString();
4045 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004046 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004047 S += '"';
4048 }
4049 return;
4050 }
Mike Stump1eb44332009-09-09 15:08:12 +00004051
John McCall532ec7b2010-05-17 23:56:34 +00004052 // gcc just blithely ignores member pointers.
4053 // TODO: maybe there should be a mangling for these
4054 if (T->getAs<MemberPointerType>())
4055 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004056
4057 if (T->isVectorType()) {
4058 // This matches gcc's encoding, even though technically it is
4059 // insufficient.
4060 // FIXME. We should do a better job than gcc.
4061 return;
4062 }
4063
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004064 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004065}
4066
Mike Stump1eb44332009-09-09 15:08:12 +00004067void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004068 std::string& S) const {
4069 if (QT & Decl::OBJC_TQ_In)
4070 S += 'n';
4071 if (QT & Decl::OBJC_TQ_Inout)
4072 S += 'N';
4073 if (QT & Decl::OBJC_TQ_Out)
4074 S += 'o';
4075 if (QT & Decl::OBJC_TQ_Bycopy)
4076 S += 'O';
4077 if (QT & Decl::OBJC_TQ_Byref)
4078 S += 'R';
4079 if (QT & Decl::OBJC_TQ_Oneway)
4080 S += 'V';
4081}
4082
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004083void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004084 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004085
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004086 BuiltinVaListType = T;
4087}
4088
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004089void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004090 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00004091}
4092
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004093void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004094 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004095}
4096
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004097void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004098 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004099}
4100
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004101void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004102 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004103}
4104
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004105void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004106 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004107 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004108
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004109 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004110}
4111
John McCall0bd6feb2009-12-02 08:04:21 +00004112/// \brief Retrieve the template name that corresponds to a non-empty
4113/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00004114TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4115 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00004116 unsigned size = End - Begin;
4117 assert(size > 1 && "set is not overloaded!");
4118
4119 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4120 size * sizeof(FunctionTemplateDecl*));
4121 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4122
4123 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004124 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004125 NamedDecl *D = *I;
4126 assert(isa<FunctionTemplateDecl>(D) ||
4127 (isa<UsingShadowDecl>(D) &&
4128 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4129 *Storage++ = D;
4130 }
4131
4132 return TemplateName(OT);
4133}
4134
Douglas Gregor7532dc62009-03-30 22:58:21 +00004135/// \brief Retrieve the template name that represents a qualified
4136/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00004137TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004138 bool TemplateKeyword,
4139 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004140 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004141 llvm::FoldingSetNodeID ID;
4142 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4143
4144 void *InsertPos = 0;
4145 QualifiedTemplateName *QTN =
4146 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4147 if (!QTN) {
4148 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4149 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4150 }
4151
4152 return TemplateName(QTN);
4153}
4154
4155/// \brief Retrieve the template name that represents a dependent
4156/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00004157TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004158 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004159 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004160 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004161
4162 llvm::FoldingSetNodeID ID;
4163 DependentTemplateName::Profile(ID, NNS, Name);
4164
4165 void *InsertPos = 0;
4166 DependentTemplateName *QTN =
4167 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4168
4169 if (QTN)
4170 return TemplateName(QTN);
4171
4172 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4173 if (CanonNNS == NNS) {
4174 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4175 } else {
4176 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4177 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004178 DependentTemplateName *CheckQTN =
4179 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4180 assert(!CheckQTN && "Dependent type name canonicalization broken");
4181 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004182 }
4183
4184 DependentTemplateNames.InsertNode(QTN, InsertPos);
4185 return TemplateName(QTN);
4186}
4187
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004188/// \brief Retrieve the template name that represents a dependent
4189/// template name such as \c MetaFun::template operator+.
4190TemplateName
4191ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4192 OverloadedOperatorKind Operator) {
4193 assert((!NNS || NNS->isDependent()) &&
4194 "Nested name specifier must be dependent");
4195
4196 llvm::FoldingSetNodeID ID;
4197 DependentTemplateName::Profile(ID, NNS, Operator);
4198
4199 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004200 DependentTemplateName *QTN
4201 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004202
4203 if (QTN)
4204 return TemplateName(QTN);
4205
4206 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4207 if (CanonNNS == NNS) {
4208 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4209 } else {
4210 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4211 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004212
4213 DependentTemplateName *CheckQTN
4214 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4215 assert(!CheckQTN && "Dependent template name canonicalization broken");
4216 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004217 }
4218
4219 DependentTemplateNames.InsertNode(QTN, InsertPos);
4220 return TemplateName(QTN);
4221}
4222
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004223/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004224/// TargetInfo, produce the corresponding type. The unsigned @p Type
4225/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004226CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004227 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004228 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004229 case TargetInfo::SignedShort: return ShortTy;
4230 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4231 case TargetInfo::SignedInt: return IntTy;
4232 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4233 case TargetInfo::SignedLong: return LongTy;
4234 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4235 case TargetInfo::SignedLongLong: return LongLongTy;
4236 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4237 }
4238
4239 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004240 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004241}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004242
4243//===----------------------------------------------------------------------===//
4244// Type Predicates.
4245//===----------------------------------------------------------------------===//
4246
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004247/// isObjCNSObjectType - Return true if this is an NSObject object using
4248/// NSObject attribute on a c-style pointer type.
4249/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004250/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004251///
4252bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4253 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4254 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004255 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004256 return true;
4257 }
Mike Stump1eb44332009-09-09 15:08:12 +00004258 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004259}
4260
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004261/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4262/// garbage collection attribute.
4263///
John McCall0953e762009-09-24 19:53:00 +00004264Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4265 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004266 if (getLangOptions().ObjC1 &&
4267 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004268 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004269 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004270 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004271 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004272 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004273 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004274 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004275 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004276 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004277 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004278 // Non-pointers have none gc'able attribute regardless of the attribute
4279 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004280 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004281 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004282 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004283 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004284}
4285
Chris Lattner6ac46a42008-04-07 06:51:04 +00004286//===----------------------------------------------------------------------===//
4287// Type Compatibility Testing
4288//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004289
Mike Stump1eb44332009-09-09 15:08:12 +00004290/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004291/// compatible.
4292static bool areCompatVectorTypes(const VectorType *LHS,
4293 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004294 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004295 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004296 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004297}
4298
Douglas Gregor255210e2010-08-06 10:14:59 +00004299bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4300 QualType SecondVec) {
4301 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4302 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4303
4304 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4305 return true;
4306
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004307 // Treat Neon vector types and most AltiVec vector types as if they are the
4308 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004309 const VectorType *First = FirstVec->getAs<VectorType>();
4310 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004311 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004312 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004313 First->getVectorKind() != VectorType::AltiVecPixel &&
4314 First->getVectorKind() != VectorType::AltiVecBool &&
4315 Second->getVectorKind() != VectorType::AltiVecPixel &&
4316 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004317 return true;
4318
4319 return false;
4320}
4321
Steve Naroff4084c302009-07-23 01:01:38 +00004322//===----------------------------------------------------------------------===//
4323// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4324//===----------------------------------------------------------------------===//
4325
4326/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4327/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004328bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4329 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004330 if (lProto == rProto)
4331 return true;
4332 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4333 E = rProto->protocol_end(); PI != E; ++PI)
4334 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4335 return true;
4336 return false;
4337}
4338
Steve Naroff4084c302009-07-23 01:01:38 +00004339/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4340/// return true if lhs's protocols conform to rhs's protocol; false
4341/// otherwise.
4342bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4343 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4344 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4345 return false;
4346}
4347
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004348/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4349/// Class<p1, ...>.
4350bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4351 QualType rhs) {
4352 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4353 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4354 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4355
4356 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4357 E = lhsQID->qual_end(); I != E; ++I) {
4358 bool match = false;
4359 ObjCProtocolDecl *lhsProto = *I;
4360 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4361 E = rhsOPT->qual_end(); J != E; ++J) {
4362 ObjCProtocolDecl *rhsProto = *J;
4363 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4364 match = true;
4365 break;
4366 }
4367 }
4368 if (!match)
4369 return false;
4370 }
4371 return true;
4372}
4373
Steve Naroff4084c302009-07-23 01:01:38 +00004374/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4375/// ObjCQualifiedIDType.
4376bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4377 bool compare) {
4378 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004379 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004380 lhs->isObjCIdType() || lhs->isObjCClassType())
4381 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004382 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004383 rhs->isObjCIdType() || rhs->isObjCClassType())
4384 return true;
4385
4386 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004387 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004388
Steve Naroff4084c302009-07-23 01:01:38 +00004389 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004390
Steve Naroff4084c302009-07-23 01:01:38 +00004391 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004392 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004393 // make sure we check the class hierarchy.
4394 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4395 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4396 E = lhsQID->qual_end(); I != E; ++I) {
4397 // when comparing an id<P> on lhs with a static type on rhs,
4398 // see if static class implements all of id's protocols, directly or
4399 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004400 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004401 return false;
4402 }
4403 }
4404 // If there are no qualifiers and no interface, we have an 'id'.
4405 return true;
4406 }
Mike Stump1eb44332009-09-09 15:08:12 +00004407 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004408 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4409 E = lhsQID->qual_end(); I != E; ++I) {
4410 ObjCProtocolDecl *lhsProto = *I;
4411 bool match = false;
4412
4413 // when comparing an id<P> on lhs with a static type on rhs,
4414 // see if static class implements all of id's protocols, directly or
4415 // through its super class and categories.
4416 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4417 E = rhsOPT->qual_end(); J != E; ++J) {
4418 ObjCProtocolDecl *rhsProto = *J;
4419 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4420 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4421 match = true;
4422 break;
4423 }
4424 }
Mike Stump1eb44332009-09-09 15:08:12 +00004425 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004426 // make sure we check the class hierarchy.
4427 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4428 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4429 E = lhsQID->qual_end(); I != E; ++I) {
4430 // when comparing an id<P> on lhs with a static type on rhs,
4431 // see if static class implements all of id's protocols, directly or
4432 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004433 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004434 match = true;
4435 break;
4436 }
4437 }
4438 }
4439 if (!match)
4440 return false;
4441 }
Mike Stump1eb44332009-09-09 15:08:12 +00004442
Steve Naroff4084c302009-07-23 01:01:38 +00004443 return true;
4444 }
Mike Stump1eb44332009-09-09 15:08:12 +00004445
Steve Naroff4084c302009-07-23 01:01:38 +00004446 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4447 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4448
Mike Stump1eb44332009-09-09 15:08:12 +00004449 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004450 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004451 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004452 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4453 E = lhsOPT->qual_end(); I != E; ++I) {
4454 ObjCProtocolDecl *lhsProto = *I;
4455 bool match = false;
4456
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004457 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00004458 // see if static class implements all of id's protocols, directly or
4459 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004460 // First, lhs protocols in the qualifier list must be found, direct
4461 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00004462 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4463 E = rhsQID->qual_end(); J != E; ++J) {
4464 ObjCProtocolDecl *rhsProto = *J;
4465 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4466 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4467 match = true;
4468 break;
4469 }
4470 }
4471 if (!match)
4472 return false;
4473 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004474
4475 // Static class's protocols, or its super class or category protocols
4476 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4477 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4478 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4479 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4480 // This is rather dubious but matches gcc's behavior. If lhs has
4481 // no type qualifier and its class has no static protocol(s)
4482 // assume that it is mismatch.
4483 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4484 return false;
4485 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4486 LHSInheritedProtocols.begin(),
4487 E = LHSInheritedProtocols.end(); I != E; ++I) {
4488 bool match = false;
4489 ObjCProtocolDecl *lhsProto = (*I);
4490 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4491 E = rhsQID->qual_end(); J != E; ++J) {
4492 ObjCProtocolDecl *rhsProto = *J;
4493 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4494 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4495 match = true;
4496 break;
4497 }
4498 }
4499 if (!match)
4500 return false;
4501 }
4502 }
Steve Naroff4084c302009-07-23 01:01:38 +00004503 return true;
4504 }
4505 return false;
4506}
4507
Eli Friedman3d815e72008-08-22 00:56:42 +00004508/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004509/// compatible for assignment from RHS to LHS. This handles validation of any
4510/// protocol qualifiers on the LHS or RHS.
4511///
Steve Naroff14108da2009-07-10 23:34:53 +00004512bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4513 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004514 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4515 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4516
Steve Naroffde2e22d2009-07-15 18:40:39 +00004517 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004518 if (LHS->isObjCUnqualifiedIdOrClass() ||
4519 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004520 return true;
4521
John McCallc12c5bb2010-05-15 11:32:37 +00004522 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004523 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4524 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004525 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004526
4527 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4528 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4529 QualType(RHSOPT,0));
4530
John McCallc12c5bb2010-05-15 11:32:37 +00004531 // If we have 2 user-defined types, fall into that path.
4532 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004533 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004534
Steve Naroff4084c302009-07-23 01:01:38 +00004535 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004536}
4537
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004538/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4539/// for providing type-safty for objective-c pointers used to pass/return
4540/// arguments in block literals. When passed as arguments, passing 'A*' where
4541/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4542/// not OK. For the return type, the opposite is not OK.
4543bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4544 const ObjCObjectPointerType *LHSOPT,
4545 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004546 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004547 return true;
4548
4549 if (LHSOPT->isObjCBuiltinType()) {
4550 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4551 }
4552
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004553 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004554 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4555 QualType(RHSOPT,0),
4556 false);
4557
4558 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4559 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4560 if (LHS && RHS) { // We have 2 user-defined types.
4561 if (LHS != RHS) {
4562 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4563 return false;
4564 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4565 return true;
4566 }
4567 else
4568 return true;
4569 }
4570 return false;
4571}
4572
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004573/// getIntersectionOfProtocols - This routine finds the intersection of set
4574/// of protocols inherited from two distinct objective-c pointer objects.
4575/// It is used to build composite qualifier list of the composite type of
4576/// the conditional expression involving two objective-c pointer objects.
4577static
4578void getIntersectionOfProtocols(ASTContext &Context,
4579 const ObjCObjectPointerType *LHSOPT,
4580 const ObjCObjectPointerType *RHSOPT,
4581 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4582
John McCallc12c5bb2010-05-15 11:32:37 +00004583 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4584 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4585 assert(LHS->getInterface() && "LHS must have an interface base");
4586 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004587
4588 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4589 unsigned LHSNumProtocols = LHS->getNumProtocols();
4590 if (LHSNumProtocols > 0)
4591 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4592 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004593 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004594 Context.CollectInheritedProtocols(LHS->getInterface(),
4595 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004596 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4597 LHSInheritedProtocols.end());
4598 }
4599
4600 unsigned RHSNumProtocols = RHS->getNumProtocols();
4601 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004602 ObjCProtocolDecl **RHSProtocols =
4603 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004604 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4605 if (InheritedProtocolSet.count(RHSProtocols[i]))
4606 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4607 }
4608 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004609 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004610 Context.CollectInheritedProtocols(RHS->getInterface(),
4611 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004612 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4613 RHSInheritedProtocols.begin(),
4614 E = RHSInheritedProtocols.end(); I != E; ++I)
4615 if (InheritedProtocolSet.count((*I)))
4616 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004617 }
4618}
4619
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004620/// areCommonBaseCompatible - Returns common base class of the two classes if
4621/// one found. Note that this is O'2 algorithm. But it will be called as the
4622/// last type comparison in a ?-exp of ObjC pointer types before a
4623/// warning is issued. So, its invokation is extremely rare.
4624QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004625 const ObjCObjectPointerType *Lptr,
4626 const ObjCObjectPointerType *Rptr) {
4627 const ObjCObjectType *LHS = Lptr->getObjectType();
4628 const ObjCObjectType *RHS = Rptr->getObjectType();
4629 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4630 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4631 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004632 return QualType();
4633
John McCallc12c5bb2010-05-15 11:32:37 +00004634 while ((LDecl = LDecl->getSuperClass())) {
4635 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004636 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004637 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4638 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4639
4640 QualType Result = QualType(LHS, 0);
4641 if (!Protocols.empty())
4642 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4643 Result = getObjCObjectPointerType(Result);
4644 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004645 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004646 }
4647
4648 return QualType();
4649}
4650
John McCallc12c5bb2010-05-15 11:32:37 +00004651bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4652 const ObjCObjectType *RHS) {
4653 assert(LHS->getInterface() && "LHS is not an interface type");
4654 assert(RHS->getInterface() && "RHS is not an interface type");
4655
Chris Lattner6ac46a42008-04-07 06:51:04 +00004656 // Verify that the base decls are compatible: the RHS must be a subclass of
4657 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004658 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004659 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004660
Chris Lattner6ac46a42008-04-07 06:51:04 +00004661 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4662 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004663 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004664 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Chris Lattner6ac46a42008-04-07 06:51:04 +00004666 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4667 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004668 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004669 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004670
John McCallc12c5bb2010-05-15 11:32:37 +00004671 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4672 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004673 LHSPI != LHSPE; LHSPI++) {
4674 bool RHSImplementsProtocol = false;
4675
4676 // If the RHS doesn't implement the protocol on the left, the types
4677 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004678 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4679 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004680 RHSPI != RHSPE; RHSPI++) {
4681 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004682 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004683 break;
4684 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004685 }
4686 // FIXME: For better diagnostics, consider passing back the protocol name.
4687 if (!RHSImplementsProtocol)
4688 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004689 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004690 // The RHS implements all protocols listed on the LHS.
4691 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004692}
4693
Steve Naroff389bf462009-02-12 17:52:19 +00004694bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4695 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004696 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4697 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004698
Steve Naroff14108da2009-07-10 23:34:53 +00004699 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004700 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004701
4702 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4703 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004704}
4705
Douglas Gregor569c3162010-08-07 11:51:51 +00004706bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4707 return canAssignObjCInterfaces(
4708 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4709 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4710}
4711
Mike Stump1eb44332009-09-09 15:08:12 +00004712/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004713/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004714/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004715/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00004716bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4717 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004718 if (getLangOptions().CPlusPlus)
4719 return hasSameType(LHS, RHS);
4720
Douglas Gregor447234d2010-07-29 15:18:02 +00004721 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00004722}
4723
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004724bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4725 return !mergeTypes(LHS, RHS, true).isNull();
4726}
4727
Peter Collingbourne48466752010-10-24 18:30:18 +00004728/// mergeTransparentUnionType - if T is a transparent union type and a member
4729/// of T is compatible with SubType, return the merged type, else return
4730/// QualType()
4731QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
4732 bool OfBlockPointer,
4733 bool Unqualified) {
4734 if (const RecordType *UT = T->getAsUnionType()) {
4735 RecordDecl *UD = UT->getDecl();
4736 if (UD->hasAttr<TransparentUnionAttr>()) {
4737 for (RecordDecl::field_iterator it = UD->field_begin(),
4738 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00004739 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00004740 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
4741 if (!MT.isNull())
4742 return MT;
4743 }
4744 }
4745 }
4746
4747 return QualType();
4748}
4749
4750/// mergeFunctionArgumentTypes - merge two types which appear as function
4751/// argument types
4752QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
4753 bool OfBlockPointer,
4754 bool Unqualified) {
4755 // GNU extension: two types are compatible if they appear as a function
4756 // argument, one of the types is a transparent union type and the other
4757 // type is compatible with a union member
4758 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
4759 Unqualified);
4760 if (!lmerge.isNull())
4761 return lmerge;
4762
4763 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
4764 Unqualified);
4765 if (!rmerge.isNull())
4766 return rmerge;
4767
4768 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
4769}
4770
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004771QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00004772 bool OfBlockPointer,
4773 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00004774 const FunctionType *lbase = lhs->getAs<FunctionType>();
4775 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004776 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4777 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004778 bool allLTypes = true;
4779 bool allRTypes = true;
4780
4781 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004782 QualType retType;
4783 if (OfBlockPointer)
Douglas Gregor447234d2010-07-29 15:18:02 +00004784 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4785 Unqualified);
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004786 else
John McCall8cc246c2010-12-15 01:06:38 +00004787 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
4788 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004789 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004790
4791 if (Unqualified)
4792 retType = retType.getUnqualifiedType();
4793
4794 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4795 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4796 if (Unqualified) {
4797 LRetType = LRetType.getUnqualifiedType();
4798 RRetType = RRetType.getUnqualifiedType();
4799 }
4800
4801 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004802 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00004803 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00004804 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00004805
Daniel Dunbar6a15c852010-04-28 16:20:58 +00004806 // FIXME: double check this
4807 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4808 // rbase->getRegParmAttr() != 0 &&
4809 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00004810 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4811 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00004812
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004813 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00004814 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004815 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004816
John McCall8cc246c2010-12-15 01:06:38 +00004817 // Regparm is part of the calling convention.
4818 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
4819 return QualType();
4820
4821 // It's noreturn if either type is.
4822 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
4823 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4824 if (NoReturn != lbaseInfo.getNoReturn())
4825 allLTypes = false;
4826 if (NoReturn != rbaseInfo.getNoReturn())
4827 allRTypes = false;
4828
4829 FunctionType::ExtInfo einfo(NoReturn,
4830 lbaseInfo.getRegParm(),
4831 lbaseInfo.getCC());
John McCalle23cf432010-12-14 08:05:40 +00004832
Eli Friedman3d815e72008-08-22 00:56:42 +00004833 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004834 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4835 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004836 unsigned lproto_nargs = lproto->getNumArgs();
4837 unsigned rproto_nargs = rproto->getNumArgs();
4838
4839 // Compatible functions must have the same number of arguments
4840 if (lproto_nargs != rproto_nargs)
4841 return QualType();
4842
4843 // Variadic and non-variadic functions aren't compatible
4844 if (lproto->isVariadic() != rproto->isVariadic())
4845 return QualType();
4846
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004847 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4848 return QualType();
4849
Eli Friedman3d815e72008-08-22 00:56:42 +00004850 // Check argument compatibility
4851 llvm::SmallVector<QualType, 10> types;
4852 for (unsigned i = 0; i < lproto_nargs; i++) {
4853 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4854 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00004855 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
4856 OfBlockPointer,
4857 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00004858 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00004859
4860 if (Unqualified)
4861 argtype = argtype.getUnqualifiedType();
4862
Eli Friedman3d815e72008-08-22 00:56:42 +00004863 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00004864 if (Unqualified) {
4865 largtype = largtype.getUnqualifiedType();
4866 rargtype = rargtype.getUnqualifiedType();
4867 }
4868
Chris Lattner61710852008-10-05 17:34:18 +00004869 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4870 allLTypes = false;
4871 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4872 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004873 }
4874 if (allLTypes) return lhs;
4875 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00004876
4877 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
4878 EPI.ExtInfo = einfo;
4879 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00004880 }
4881
4882 if (lproto) allRTypes = false;
4883 if (rproto) allLTypes = false;
4884
Douglas Gregor72564e72009-02-26 23:50:07 +00004885 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004886 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004887 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004888 if (proto->isVariadic()) return QualType();
4889 // Check that the types are compatible with the types that
4890 // would result from default argument promotions (C99 6.7.5.3p15).
4891 // The only types actually affected are promotable integer
4892 // types and floats, which would be passed as a different
4893 // type depending on whether the prototype is visible.
4894 unsigned proto_nargs = proto->getNumArgs();
4895 for (unsigned i = 0; i < proto_nargs; ++i) {
4896 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004897
4898 // Look at the promotion type of enum types, since that is the type used
4899 // to pass enum values.
4900 if (const EnumType *Enum = argTy->getAs<EnumType>())
4901 argTy = Enum->getDecl()->getPromotionType();
4902
Eli Friedman3d815e72008-08-22 00:56:42 +00004903 if (argTy->isPromotableIntegerType() ||
4904 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4905 return QualType();
4906 }
4907
4908 if (allLTypes) return lhs;
4909 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00004910
4911 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
4912 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00004913 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004914 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00004915 }
4916
4917 if (allLTypes) return lhs;
4918 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00004919 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00004920}
4921
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004922QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00004923 bool OfBlockPointer,
4924 bool Unqualified) {
Bill Wendling43d69752007-12-03 07:33:35 +00004925 // C++ [expr]: If an expression initially has the type "reference to T", the
4926 // type is adjusted to "T" prior to any further analysis, the expression
4927 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004928 // expression is an lvalue unless the reference is an rvalue reference and
4929 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004930 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4931 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00004932
4933 if (Unqualified) {
4934 LHS = LHS.getUnqualifiedType();
4935 RHS = RHS.getUnqualifiedType();
4936 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004937
Eli Friedman3d815e72008-08-22 00:56:42 +00004938 QualType LHSCan = getCanonicalType(LHS),
4939 RHSCan = getCanonicalType(RHS);
4940
4941 // If two types are identical, they are compatible.
4942 if (LHSCan == RHSCan)
4943 return LHS;
4944
John McCall0953e762009-09-24 19:53:00 +00004945 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004946 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4947 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004948 if (LQuals != RQuals) {
4949 // If any of these qualifiers are different, we have a type
4950 // mismatch.
4951 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4952 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4953 return QualType();
4954
4955 // Exactly one GC qualifier difference is allowed: __strong is
4956 // okay if the other type has no GC qualifier but is an Objective
4957 // C object pointer (i.e. implicitly strong by default). We fix
4958 // this by pretending that the unqualified type was actually
4959 // qualified __strong.
4960 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4961 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4962 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4963
4964 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4965 return QualType();
4966
4967 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4968 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4969 }
4970 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4971 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4972 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004973 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004974 }
4975
4976 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004977
Eli Friedman852d63b2009-06-01 01:22:52 +00004978 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4979 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004980
Chris Lattner1adb8832008-01-14 05:45:46 +00004981 // We want to consider the two function types to be the same for these
4982 // comparisons, just force one to the other.
4983 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4984 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004985
4986 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004987 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4988 LHSClass = Type::ConstantArray;
4989 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4990 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004991
John McCallc12c5bb2010-05-15 11:32:37 +00004992 // ObjCInterfaces are just specialized ObjCObjects.
4993 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4994 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4995
Nate Begeman213541a2008-04-18 23:10:10 +00004996 // Canonicalize ExtVector -> Vector.
4997 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4998 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004999
Chris Lattnera36a61f2008-04-07 05:43:21 +00005000 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005001 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005002 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005003 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005004 // Compatibility is based on the underlying type, not the promotion
5005 // type.
John McCall183700f2009-09-21 23:43:11 +00005006 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005007 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5008 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005009 }
John McCall183700f2009-09-21 23:43:11 +00005010 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005011 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5012 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005013 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005014
Eli Friedman3d815e72008-08-22 00:56:42 +00005015 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005016 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005017
Steve Naroff4a746782008-01-09 22:43:08 +00005018 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005019 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005020#define TYPE(Class, Base)
5021#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005022#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005023#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5024#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5025#include "clang/AST/TypeNodes.def"
5026 assert(false && "Non-canonical and dependent types shouldn't get here");
5027 return QualType();
5028
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005029 case Type::LValueReference:
5030 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005031 case Type::MemberPointer:
5032 assert(false && "C++ should never be in mergeTypes");
5033 return QualType();
5034
John McCallc12c5bb2010-05-15 11:32:37 +00005035 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005036 case Type::IncompleteArray:
5037 case Type::VariableArray:
5038 case Type::FunctionProto:
5039 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005040 assert(false && "Types are eliminated above");
5041 return QualType();
5042
Chris Lattner1adb8832008-01-14 05:45:46 +00005043 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005044 {
5045 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005046 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5047 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005048 if (Unqualified) {
5049 LHSPointee = LHSPointee.getUnqualifiedType();
5050 RHSPointee = RHSPointee.getUnqualifiedType();
5051 }
5052 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5053 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005054 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005055 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005056 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005057 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005058 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005059 return getPointerType(ResultType);
5060 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005061 case Type::BlockPointer:
5062 {
5063 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005064 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5065 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005066 if (Unqualified) {
5067 LHSPointee = LHSPointee.getUnqualifiedType();
5068 RHSPointee = RHSPointee.getUnqualifiedType();
5069 }
5070 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5071 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005072 if (ResultType.isNull()) return QualType();
5073 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5074 return LHS;
5075 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5076 return RHS;
5077 return getBlockPointerType(ResultType);
5078 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005079 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005080 {
5081 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5082 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5083 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5084 return QualType();
5085
5086 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5087 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005088 if (Unqualified) {
5089 LHSElem = LHSElem.getUnqualifiedType();
5090 RHSElem = RHSElem.getUnqualifiedType();
5091 }
5092
5093 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005094 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005095 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5096 return LHS;
5097 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5098 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005099 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5100 ArrayType::ArraySizeModifier(), 0);
5101 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5102 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005103 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5104 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005105 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5106 return LHS;
5107 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5108 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005109 if (LVAT) {
5110 // FIXME: This isn't correct! But tricky to implement because
5111 // the array's size has to be the size of LHS, but the type
5112 // has to be different.
5113 return LHS;
5114 }
5115 if (RVAT) {
5116 // FIXME: This isn't correct! But tricky to implement because
5117 // the array's size has to be the size of RHS, but the type
5118 // has to be different.
5119 return RHS;
5120 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005121 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5122 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005123 return getIncompleteArrayType(ResultType,
5124 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005125 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005126 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005127 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005128 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005129 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005130 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005131 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005132 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005133 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005134 case Type::Complex:
5135 // Distinct complex types are incompatible.
5136 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005137 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005138 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005139 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5140 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005141 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005142 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005143 case Type::ObjCObject: {
5144 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005145 // FIXME: This should be type compatibility, e.g. whether
5146 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005147 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5148 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5149 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005150 return LHS;
5151
Eli Friedman3d815e72008-08-22 00:56:42 +00005152 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005153 }
Steve Naroff14108da2009-07-10 23:34:53 +00005154 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005155 if (OfBlockPointer) {
5156 if (canAssignObjCInterfacesInBlockPointer(
5157 LHS->getAs<ObjCObjectPointerType>(),
5158 RHS->getAs<ObjCObjectPointerType>()))
5159 return LHS;
5160 return QualType();
5161 }
John McCall183700f2009-09-21 23:43:11 +00005162 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5163 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005164 return LHS;
5165
Steve Naroffbc76dd02008-12-10 22:14:21 +00005166 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005167 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005168 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005169
5170 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005171}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005172
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005173/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5174/// 'RHS' attributes and returns the merged version; including for function
5175/// return types.
5176QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5177 QualType LHSCan = getCanonicalType(LHS),
5178 RHSCan = getCanonicalType(RHS);
5179 // If two types are identical, they are compatible.
5180 if (LHSCan == RHSCan)
5181 return LHS;
5182 if (RHSCan->isFunctionType()) {
5183 if (!LHSCan->isFunctionType())
5184 return QualType();
5185 QualType OldReturnType =
5186 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5187 QualType NewReturnType =
5188 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5189 QualType ResReturnType =
5190 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5191 if (ResReturnType.isNull())
5192 return QualType();
5193 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5194 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5195 // In either case, use OldReturnType to build the new function type.
5196 const FunctionType *F = LHS->getAs<FunctionType>();
5197 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005198 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5199 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005200 QualType ResultType
5201 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005202 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005203 return ResultType;
5204 }
5205 }
5206 return QualType();
5207 }
5208
5209 // If the qualifiers are different, the types can still be merged.
5210 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5211 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5212 if (LQuals != RQuals) {
5213 // If any of these qualifiers are different, we have a type mismatch.
5214 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5215 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5216 return QualType();
5217
5218 // Exactly one GC qualifier difference is allowed: __strong is
5219 // okay if the other type has no GC qualifier but is an Objective
5220 // C object pointer (i.e. implicitly strong by default). We fix
5221 // this by pretending that the unqualified type was actually
5222 // qualified __strong.
5223 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5224 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5225 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5226
5227 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5228 return QualType();
5229
5230 if (GC_L == Qualifiers::Strong)
5231 return LHS;
5232 if (GC_R == Qualifiers::Strong)
5233 return RHS;
5234 return QualType();
5235 }
5236
5237 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5238 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5239 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5240 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5241 if (ResQT == LHSBaseQT)
5242 return LHS;
5243 if (ResQT == RHSBaseQT)
5244 return RHS;
5245 }
5246 return QualType();
5247}
5248
Chris Lattner5426bf62008-04-07 07:01:58 +00005249//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005250// Integer Predicates
5251//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005252
Eli Friedmanad74a752008-06-28 06:23:08 +00005253unsigned ASTContext::getIntWidth(QualType T) {
John McCall842aef82009-12-09 09:09:27 +00005254 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005255 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005256 if (T->isBooleanType())
5257 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005258 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005259 return (unsigned)getTypeSize(T);
5260}
5261
5262QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005263 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005264
5265 // Turn <4 x signed int> -> <4 x unsigned int>
5266 if (const VectorType *VTy = T->getAs<VectorType>())
5267 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005268 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005269
5270 // For enums, we return the unsigned version of the base type.
5271 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005272 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005273
5274 const BuiltinType *BTy = T->getAs<BuiltinType>();
5275 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005276 switch (BTy->getKind()) {
5277 case BuiltinType::Char_S:
5278 case BuiltinType::SChar:
5279 return UnsignedCharTy;
5280 case BuiltinType::Short:
5281 return UnsignedShortTy;
5282 case BuiltinType::Int:
5283 return UnsignedIntTy;
5284 case BuiltinType::Long:
5285 return UnsignedLongTy;
5286 case BuiltinType::LongLong:
5287 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005288 case BuiltinType::Int128:
5289 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005290 default:
5291 assert(0 && "Unexpected signed integer type");
5292 return QualType();
5293 }
5294}
5295
Douglas Gregor2cf26342009-04-09 22:27:44 +00005296ExternalASTSource::~ExternalASTSource() { }
5297
5298void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005299
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005300ASTMutationListener::~ASTMutationListener() { }
5301
Chris Lattner86df27b2009-06-14 00:45:47 +00005302
5303//===----------------------------------------------------------------------===//
5304// Builtin Type Computation
5305//===----------------------------------------------------------------------===//
5306
5307/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00005308/// pointer over the consumed characters. This returns the resultant type. If
5309/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5310/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5311/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00005312///
5313/// RequiresICE is filled in on return to indicate whether the value is required
5314/// to be an Integer Constant Expression.
Mike Stump1eb44332009-09-09 15:08:12 +00005315static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005316 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00005317 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00005318 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005319 // Modifiers.
5320 int HowLong = 0;
5321 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00005322 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005323
Chris Lattner33daae62010-10-01 22:42:38 +00005324 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00005325 bool Done = false;
5326 while (!Done) {
5327 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005328 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005329 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00005330 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005331 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005332 case 'S':
5333 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5334 assert(!Signed && "Can't use 'S' modifier multiple times!");
5335 Signed = true;
5336 break;
5337 case 'U':
5338 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5339 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5340 Unsigned = true;
5341 break;
5342 case 'L':
5343 assert(HowLong <= 2 && "Can't have LLLL modifier");
5344 ++HowLong;
5345 break;
5346 }
5347 }
5348
5349 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005350
Chris Lattner86df27b2009-06-14 00:45:47 +00005351 // Read the base type.
5352 switch (*Str++) {
5353 default: assert(0 && "Unknown builtin type letter!");
5354 case 'v':
5355 assert(HowLong == 0 && !Signed && !Unsigned &&
5356 "Bad modifiers used with 'v'!");
5357 Type = Context.VoidTy;
5358 break;
5359 case 'f':
5360 assert(HowLong == 0 && !Signed && !Unsigned &&
5361 "Bad modifiers used with 'f'!");
5362 Type = Context.FloatTy;
5363 break;
5364 case 'd':
5365 assert(HowLong < 2 && !Signed && !Unsigned &&
5366 "Bad modifiers used with 'd'!");
5367 if (HowLong)
5368 Type = Context.LongDoubleTy;
5369 else
5370 Type = Context.DoubleTy;
5371 break;
5372 case 's':
5373 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5374 if (Unsigned)
5375 Type = Context.UnsignedShortTy;
5376 else
5377 Type = Context.ShortTy;
5378 break;
5379 case 'i':
5380 if (HowLong == 3)
5381 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5382 else if (HowLong == 2)
5383 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5384 else if (HowLong == 1)
5385 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5386 else
5387 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5388 break;
5389 case 'c':
5390 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5391 if (Signed)
5392 Type = Context.SignedCharTy;
5393 else if (Unsigned)
5394 Type = Context.UnsignedCharTy;
5395 else
5396 Type = Context.CharTy;
5397 break;
5398 case 'b': // boolean
5399 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5400 Type = Context.BoolTy;
5401 break;
5402 case 'z': // size_t.
5403 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5404 Type = Context.getSizeType();
5405 break;
5406 case 'F':
5407 Type = Context.getCFConstantStringType();
5408 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00005409 case 'G':
5410 Type = Context.getObjCIdType();
5411 break;
5412 case 'H':
5413 Type = Context.getObjCSelType();
5414 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005415 case 'a':
5416 Type = Context.getBuiltinVaListType();
5417 assert(!Type.isNull() && "builtin va list type not initialized!");
5418 break;
5419 case 'A':
5420 // This is a "reference" to a va_list; however, what exactly
5421 // this means depends on how va_list is defined. There are two
5422 // different kinds of va_list: ones passed by value, and ones
5423 // passed by reference. An example of a by-value va_list is
5424 // x86, where va_list is a char*. An example of by-ref va_list
5425 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5426 // we want this argument to be a char*&; for x86-64, we want
5427 // it to be a __va_list_tag*.
5428 Type = Context.getBuiltinVaListType();
5429 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00005430 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00005431 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00005432 else
Chris Lattner86df27b2009-06-14 00:45:47 +00005433 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005434 break;
5435 case 'V': {
5436 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005437 unsigned NumElements = strtoul(Str, &End, 10);
5438 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00005439 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005440
Chris Lattner14e0e742010-10-01 22:53:11 +00005441 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5442 RequiresICE, false);
5443 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00005444
5445 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005446 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00005447 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00005448 break;
5449 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005450 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00005451 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5452 false);
5453 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00005454 Type = Context.getComplexType(ElementType);
5455 break;
5456 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005457 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005458 Type = Context.getFILEType();
5459 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005460 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005461 return QualType();
5462 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005463 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005464 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005465 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005466 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005467 else
5468 Type = Context.getjmp_bufType();
5469
Mike Stumpfd612db2009-07-28 23:47:15 +00005470 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005471 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005472 return QualType();
5473 }
5474 break;
Mike Stump782fa302009-07-28 02:25:19 +00005475 }
Mike Stump1eb44332009-09-09 15:08:12 +00005476
Chris Lattner33daae62010-10-01 22:42:38 +00005477 // If there are modifiers and if we're allowed to parse them, go for it.
5478 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00005479 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005480 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00005481 default: Done = true; --Str; break;
5482 case '*':
5483 case '&': {
5484 // Both pointers and references can have their pointee types
5485 // qualified with an address space.
5486 char *End;
5487 unsigned AddrSpace = strtoul(Str, &End, 10);
5488 if (End != Str && AddrSpace != 0) {
5489 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5490 Str = End;
5491 }
5492 if (c == '*')
5493 Type = Context.getPointerType(Type);
5494 else
5495 Type = Context.getLValueReferenceType(Type);
5496 break;
5497 }
5498 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5499 case 'C':
5500 Type = Type.withConst();
5501 break;
5502 case 'D':
5503 Type = Context.getVolatileType(Type);
5504 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005505 }
5506 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00005507
Chris Lattner14e0e742010-10-01 22:53:11 +00005508 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00005509 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00005510
Chris Lattner86df27b2009-06-14 00:45:47 +00005511 return Type;
5512}
5513
5514/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00005515QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00005516 GetBuiltinTypeError &Error,
5517 unsigned *IntegerConstantArgs) {
Chris Lattner33daae62010-10-01 22:42:38 +00005518 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00005519
Chris Lattner86df27b2009-06-14 00:45:47 +00005520 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005521
Chris Lattner14e0e742010-10-01 22:53:11 +00005522 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00005523 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00005524 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5525 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005526 if (Error != GE_None)
5527 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00005528
5529 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5530
Chris Lattner86df27b2009-06-14 00:45:47 +00005531 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00005532 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005533 if (Error != GE_None)
5534 return QualType();
5535
Chris Lattner14e0e742010-10-01 22:53:11 +00005536 // If this argument is required to be an IntegerConstantExpression and the
5537 // caller cares, fill in the bitmask we return.
5538 if (RequiresICE && IntegerConstantArgs)
5539 *IntegerConstantArgs |= 1 << ArgTypes.size();
5540
Chris Lattner86df27b2009-06-14 00:45:47 +00005541 // Do array -> pointer decay. The builtin should use the decayed type.
5542 if (Ty->isArrayType())
5543 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005544
Chris Lattner86df27b2009-06-14 00:45:47 +00005545 ArgTypes.push_back(Ty);
5546 }
5547
5548 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5549 "'.' should only occur at end of builtin type list!");
5550
John McCall00ccbef2010-12-21 00:44:39 +00005551 FunctionType::ExtInfo EI;
5552 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5553
5554 bool Variadic = (TypeStr[0] == '.');
5555
5556 // We really shouldn't be making a no-proto type here, especially in C++.
5557 if (ArgTypes.empty() && Variadic)
5558 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005559
John McCalle23cf432010-12-14 08:05:40 +00005560 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00005561 EPI.ExtInfo = EI;
5562 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00005563
5564 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00005565}
Eli Friedmana95d7572009-08-19 07:44:53 +00005566
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005567GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5568 GVALinkage External = GVA_StrongExternal;
5569
5570 Linkage L = FD->getLinkage();
5571 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5572 FD->getType()->getLinkage() == UniqueExternalLinkage)
5573 L = UniqueExternalLinkage;
5574
5575 switch (L) {
5576 case NoLinkage:
5577 case InternalLinkage:
5578 case UniqueExternalLinkage:
5579 return GVA_Internal;
5580
5581 case ExternalLinkage:
5582 switch (FD->getTemplateSpecializationKind()) {
5583 case TSK_Undeclared:
5584 case TSK_ExplicitSpecialization:
5585 External = GVA_StrongExternal;
5586 break;
5587
5588 case TSK_ExplicitInstantiationDefinition:
5589 return GVA_ExplicitTemplateInstantiation;
5590
5591 case TSK_ExplicitInstantiationDeclaration:
5592 case TSK_ImplicitInstantiation:
5593 External = GVA_TemplateInstantiation;
5594 break;
5595 }
5596 }
5597
5598 if (!FD->isInlined())
5599 return External;
5600
5601 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5602 // GNU or C99 inline semantics. Determine whether this symbol should be
5603 // externally visible.
5604 if (FD->isInlineDefinitionExternallyVisible())
5605 return External;
5606
5607 // C99 inline semantics, where the symbol is not externally visible.
5608 return GVA_C99Inline;
5609 }
5610
5611 // C++0x [temp.explicit]p9:
5612 // [ Note: The intent is that an inline function that is the subject of
5613 // an explicit instantiation declaration will still be implicitly
5614 // instantiated when used so that the body can be considered for
5615 // inlining, but that no out-of-line copy of the inline function would be
5616 // generated in the translation unit. -- end note ]
5617 if (FD->getTemplateSpecializationKind()
5618 == TSK_ExplicitInstantiationDeclaration)
5619 return GVA_C99Inline;
5620
5621 return GVA_CXXInline;
5622}
5623
5624GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5625 // If this is a static data member, compute the kind of template
5626 // specialization. Otherwise, this variable is not part of a
5627 // template.
5628 TemplateSpecializationKind TSK = TSK_Undeclared;
5629 if (VD->isStaticDataMember())
5630 TSK = VD->getTemplateSpecializationKind();
5631
5632 Linkage L = VD->getLinkage();
5633 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5634 VD->getType()->getLinkage() == UniqueExternalLinkage)
5635 L = UniqueExternalLinkage;
5636
5637 switch (L) {
5638 case NoLinkage:
5639 case InternalLinkage:
5640 case UniqueExternalLinkage:
5641 return GVA_Internal;
5642
5643 case ExternalLinkage:
5644 switch (TSK) {
5645 case TSK_Undeclared:
5646 case TSK_ExplicitSpecialization:
5647 return GVA_StrongExternal;
5648
5649 case TSK_ExplicitInstantiationDeclaration:
5650 llvm_unreachable("Variable should not be instantiated");
5651 // Fall through to treat this like any other instantiation.
5652
5653 case TSK_ExplicitInstantiationDefinition:
5654 return GVA_ExplicitTemplateInstantiation;
5655
5656 case TSK_ImplicitInstantiation:
5657 return GVA_TemplateInstantiation;
5658 }
5659 }
5660
5661 return GVA_StrongExternal;
5662}
5663
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00005664bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005665 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5666 if (!VD->isFileVarDecl())
5667 return false;
5668 } else if (!isa<FunctionDecl>(D))
5669 return false;
5670
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005671 // Weak references don't produce any output by themselves.
5672 if (D->hasAttr<WeakRefAttr>())
5673 return false;
5674
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005675 // Aliases and used decls are required.
5676 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5677 return true;
5678
5679 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5680 // Forward declarations aren't required.
5681 if (!FD->isThisDeclarationADefinition())
5682 return false;
5683
5684 // Constructors and destructors are required.
5685 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5686 return true;
5687
5688 // The key function for a class is required.
5689 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5690 const CXXRecordDecl *RD = MD->getParent();
5691 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5692 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5693 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5694 return true;
5695 }
5696 }
5697
5698 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5699
5700 // static, static inline, always_inline, and extern inline functions can
5701 // always be deferred. Normal inline functions can be deferred in C99/C++.
5702 // Implicit template instantiations can also be deferred in C++.
5703 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5704 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5705 return false;
5706 return true;
5707 }
5708
5709 const VarDecl *VD = cast<VarDecl>(D);
5710 assert(VD->isFileVarDecl() && "Expected file scoped var");
5711
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005712 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5713 return false;
5714
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005715 // Structs that have non-trivial constructors or destructors are required.
5716
5717 // FIXME: Handle references.
5718 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5719 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00005720 if (RD->hasDefinition() &&
5721 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005722 return true;
5723 }
5724 }
5725
5726 GVALinkage L = GetGVALinkageForVariable(VD);
5727 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5728 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5729 return false;
5730 }
5731
5732 return true;
5733}
Charles Davis071cc7d2010-08-16 03:33:14 +00005734
Charles Davisee743f92010-11-09 18:04:24 +00005735CallingConv ASTContext::getDefaultMethodCallConv() {
5736 // Pass through to the C++ ABI object
5737 return ABI->getDefaultMethodCallConv();
5738}
5739
Anders Carlssondae0cb52010-11-25 01:51:53 +00005740bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) {
5741 // Pass through to the C++ ABI object
5742 return ABI->isNearlyEmpty(RD);
5743}
5744
Charles Davis071cc7d2010-08-16 03:33:14 +00005745CXXABI::~CXXABI() {}