blob: 3abfe22caa89c47927eb4e9bb084a7f11d89eedb [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Charles Davis53c59df2010-08-16 03:33:14 +000033#include "CXXABI.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000034
Chris Lattnerddc135e2006-11-10 06:34:16 +000035using namespace clang;
36
Douglas Gregor9672f922010-07-03 00:47:00 +000037unsigned ASTContext::NumImplicitDefaultConstructors;
38unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000039unsigned ASTContext::NumImplicitCopyConstructors;
40unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000041unsigned ASTContext::NumImplicitCopyAssignmentOperators;
42unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000043unsigned ASTContext::NumImplicitDestructors;
44unsigned ASTContext::NumImplicitDestructorsDeclared;
45
Steve Naroff0af91202007-04-27 21:51:21 +000046enum FloatingRank {
47 FloatRank, DoubleRank, LongDoubleRank
48};
49
Douglas Gregor7dbfb462010-06-16 21:09:37 +000050void
51ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
52 TemplateTemplateParmDecl *Parm) {
53 ID.AddInteger(Parm->getDepth());
54 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000055 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000056
57 TemplateParameterList *Params = Parm->getTemplateParameters();
58 ID.AddInteger(Params->size());
59 for (TemplateParameterList::const_iterator P = Params->begin(),
60 PEnd = Params->end();
61 P != PEnd; ++P) {
62 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
63 ID.AddInteger(0);
64 ID.AddBoolean(TTP->isParameterPack());
65 continue;
66 }
67
68 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
69 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000070 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000071 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
72 continue;
73 }
74
75 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
76 ID.AddInteger(2);
77 Profile(ID, TTP);
78 }
79}
80
81TemplateTemplateParmDecl *
82ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000083 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000084 // Check if we already have a canonical template template parameter.
85 llvm::FoldingSetNodeID ID;
86 CanonicalTemplateTemplateParm::Profile(ID, TTP);
87 void *InsertPos = 0;
88 CanonicalTemplateTemplateParm *Canonical
89 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
90 if (Canonical)
91 return Canonical->getParam();
92
93 // Build a canonical template parameter list.
94 TemplateParameterList *Params = TTP->getTemplateParameters();
95 llvm::SmallVector<NamedDecl *, 4> CanonParams;
96 CanonParams.reserve(Params->size());
97 for (TemplateParameterList::const_iterator P = Params->begin(),
98 PEnd = Params->end();
99 P != PEnd; ++P) {
100 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
101 CanonParams.push_back(
102 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
103 SourceLocation(), TTP->getDepth(),
104 TTP->getIndex(), 0, false,
105 TTP->isParameterPack()));
106 else if (NonTypeTemplateParmDecl *NTTP
107 = dyn_cast<NonTypeTemplateParmDecl>(*P))
108 CanonParams.push_back(
109 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
110 SourceLocation(), NTTP->getDepth(),
111 NTTP->getPosition(), 0,
112 getCanonicalType(NTTP->getType()),
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000113 NTTP->isParameterPack(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000114 0));
115 else
116 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
117 cast<TemplateTemplateParmDecl>(*P)));
118 }
119
120 TemplateTemplateParmDecl *CanonTTP
121 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
122 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000123 TTP->getPosition(),
124 TTP->isParameterPack(),
125 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000126 TemplateParameterList::Create(*this, SourceLocation(),
127 SourceLocation(),
128 CanonParams.data(),
129 CanonParams.size(),
130 SourceLocation()));
131
132 // Get the new insert position for the node we care about.
133 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
134 assert(Canonical == 0 && "Shouldn't be in the map!");
135 (void)Canonical;
136
137 // Create the canonical template template parameter entry.
138 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
139 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
140 return CanonTTP;
141}
142
Charles Davis53c59df2010-08-16 03:33:14 +0000143CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000144 if (!LangOpts.CPlusPlus) return 0;
145
Charles Davis6bcb07a2010-08-19 02:18:14 +0000146 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000147 case CXXABI_ARM:
148 return CreateARMCXXABI(*this);
149 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000150 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000151 case CXXABI_Microsoft:
152 return CreateMicrosoftCXXABI(*this);
153 }
John McCall86353412010-08-21 22:46:04 +0000154 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000155}
156
Chris Lattner465fa322008-10-05 17:34:18 +0000157ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000158 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000159 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000160 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000161 unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000162 TemplateSpecializationTypes(this_()),
163 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000164 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
165 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000166 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000167 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000168 NullTypeSourceInfo(QualType()),
Charles Davis53c59df2010-08-16 03:33:14 +0000169 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000170 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000171 BuiltinInfo(builtins),
172 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000173 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000174 LastSDM(0, 0),
175 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000176 ObjCIdRedefinitionType = QualType();
177 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000178 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000179 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000180 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000181 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000182}
183
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000184ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000185 // Release the DenseMaps associated with DeclContext objects.
186 // FIXME: Is this the ideal solution?
187 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000188
Douglas Gregor5b11d492010-07-25 17:53:33 +0000189 // Call all of the deallocation functions.
190 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
191 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000192
Douglas Gregor832940b2010-03-02 23:58:15 +0000193 // Release all of the memory associated with overridden C++ methods.
194 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
195 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
196 OM != OMEnd; ++OM)
197 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000198
Ted Kremenek076baeb2010-06-08 23:00:58 +0000199 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000200 // because they can contain DenseMaps.
201 for (llvm::DenseMap<const ObjCContainerDecl*,
202 const ASTRecordLayout*>::iterator
203 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
204 // Increment in loop to prevent using deallocated memory.
205 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
206 R->Destroy(*this);
207
Ted Kremenek076baeb2010-06-08 23:00:58 +0000208 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
209 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
210 // Increment in loop to prevent using deallocated memory.
211 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
212 R->Destroy(*this);
213 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000214
215 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
216 AEnd = DeclAttrs.end();
217 A != AEnd; ++A)
218 A->second->~AttrVec();
219}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000220
Douglas Gregor1a809332010-05-23 18:26:36 +0000221void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
222 Deallocations.push_back(std::make_pair(Callback, Data));
223}
224
Mike Stump11289f42009-09-09 15:08:12 +0000225void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000226ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
227 ExternalSource.reset(Source.take());
228}
229
Chris Lattner4eb445d2007-01-26 01:27:23 +0000230void ASTContext::PrintStats() const {
231 fprintf(stderr, "*** AST Context Stats:\n");
232 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000233
Douglas Gregora30d0462009-05-26 14:40:08 +0000234 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000235#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000236#define ABSTRACT_TYPE(Name, Parent)
237#include "clang/AST/TypeNodes.def"
238 0 // Extra
239 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000240
Chris Lattner4eb445d2007-01-26 01:27:23 +0000241 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
242 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000243 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000244 }
245
Douglas Gregora30d0462009-05-26 14:40:08 +0000246 unsigned Idx = 0;
247 unsigned TotalBytes = 0;
248#define TYPE(Name, Parent) \
249 if (counts[Idx]) \
250 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
251 TotalBytes += counts[Idx] * sizeof(Name##Type); \
252 ++Idx;
253#define ABSTRACT_TYPE(Name, Parent)
254#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000255
Douglas Gregora30d0462009-05-26 14:40:08 +0000256 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000257
Douglas Gregor7454c562010-07-02 20:37:36 +0000258 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000259 fprintf(stderr, " %u/%u implicit default constructors created\n",
260 NumImplicitDefaultConstructorsDeclared,
261 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000262 fprintf(stderr, " %u/%u implicit copy constructors created\n",
263 NumImplicitCopyConstructorsDeclared,
264 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000265 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
266 NumImplicitCopyAssignmentOperatorsDeclared,
267 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000268 fprintf(stderr, " %u/%u implicit destructors created\n",
269 NumImplicitDestructorsDeclared, NumImplicitDestructors);
270
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000271 if (ExternalSource.get()) {
272 fprintf(stderr, "\n");
273 ExternalSource->PrintStats();
274 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000275
Douglas Gregor5b11d492010-07-25 17:53:33 +0000276 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000277}
278
279
John McCall48f2d582009-10-23 23:03:21 +0000280void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000281 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000282 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000283 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000284}
285
Chris Lattner970e54e2006-11-12 00:37:36 +0000286void ASTContext::InitBuiltinTypes() {
287 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000288
Chris Lattner970e54e2006-11-12 00:37:36 +0000289 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000290 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000291
Chris Lattner970e54e2006-11-12 00:37:36 +0000292 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000293 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000294 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000295 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000296 InitBuiltinType(CharTy, BuiltinType::Char_S);
297 else
298 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000299 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000300 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
301 InitBuiltinType(ShortTy, BuiltinType::Short);
302 InitBuiltinType(IntTy, BuiltinType::Int);
303 InitBuiltinType(LongTy, BuiltinType::Long);
304 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattner970e54e2006-11-12 00:37:36 +0000306 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000307 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
308 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
309 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
310 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
311 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000312
Chris Lattner970e54e2006-11-12 00:37:36 +0000313 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000314 InitBuiltinType(FloatTy, BuiltinType::Float);
315 InitBuiltinType(DoubleTy, BuiltinType::Double);
316 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000317
Chris Lattnerf122cef2009-04-30 02:43:43 +0000318 // GNU extension, 128-bit integers.
319 InitBuiltinType(Int128Ty, BuiltinType::Int128);
320 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
321
Chris Lattnerad3467e2010-12-25 23:25:43 +0000322 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
323 if (!LangOpts.ShortWChar)
324 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
325 else // -fshort-wchar makes wchar_t be unsigned.
326 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
327 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000328 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000329
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000330 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
331 InitBuiltinType(Char16Ty, BuiltinType::Char16);
332 else // C99
333 Char16Ty = getFromTargetType(Target.getChar16Type());
334
335 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
336 InitBuiltinType(Char32Ty, BuiltinType::Char32);
337 else // C99
338 Char32Ty = getFromTargetType(Target.getChar32Type());
339
Douglas Gregor4619e432008-12-05 23:32:09 +0000340 // Placeholder type for type-dependent expressions whose type is
341 // completely unknown. No code should ever check a type against
342 // DependentTy and users should never see it; however, it is here to
343 // help diagnose failures to properly check for type-dependent
344 // expressions.
345 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000346
John McCall36e7fe32010-10-12 00:20:44 +0000347 // Placeholder type for functions.
348 InitBuiltinType(OverloadTy, BuiltinType::Overload);
349
Mike Stump11289f42009-09-09 15:08:12 +0000350 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000351 // not yet been deduced.
John McCall36e7fe32010-10-12 00:20:44 +0000352 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000353
Chris Lattner970e54e2006-11-12 00:37:36 +0000354 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000355 FloatComplexTy = getComplexType(FloatTy);
356 DoubleComplexTy = getComplexType(DoubleTy);
357 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000358
Steve Naroff66e9f332007-10-15 14:41:52 +0000359 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000360
Steve Naroff1329fa02009-07-15 18:40:39 +0000361 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
362 ObjCIdTypedefType = QualType();
363 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000364 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000365
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000366 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000367 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
368 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000369 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000370
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000371 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000372
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000373 // void * type
374 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000375
376 // nullptr type (C++0x 2.14.7)
377 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000378}
379
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000380Diagnostic &ASTContext::getDiagnostics() const {
381 return SourceMgr.getDiagnostics();
382}
383
Douglas Gregor561eceb2010-08-30 16:49:28 +0000384AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
385 AttrVec *&Result = DeclAttrs[D];
386 if (!Result) {
387 void *Mem = Allocate(sizeof(AttrVec));
388 Result = new (Mem) AttrVec;
389 }
390
391 return *Result;
392}
393
394/// \brief Erase the attributes corresponding to the given declaration.
395void ASTContext::eraseDeclAttrs(const Decl *D) {
396 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
397 if (Pos != DeclAttrs.end()) {
398 Pos->second->~AttrVec();
399 DeclAttrs.erase(Pos);
400 }
401}
402
403
Douglas Gregor86d142a2009-10-08 07:24:58 +0000404MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000405ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000406 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000407 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000408 = InstantiatedFromStaticDataMember.find(Var);
409 if (Pos == InstantiatedFromStaticDataMember.end())
410 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000411
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000412 return Pos->second;
413}
414
Mike Stump11289f42009-09-09 15:08:12 +0000415void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000416ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000417 TemplateSpecializationKind TSK,
418 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000419 assert(Inst->isStaticDataMember() && "Not a static data member");
420 assert(Tmpl->isStaticDataMember() && "Not a static data member");
421 assert(!InstantiatedFromStaticDataMember[Inst] &&
422 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000423 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000424 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000425}
426
John McCalle61f2ba2009-11-18 02:36:19 +0000427NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000428ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000429 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000430 = InstantiatedFromUsingDecl.find(UUD);
431 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000432 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000433
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000434 return Pos->second;
435}
436
437void
John McCallb96ec562009-12-04 22:46:56 +0000438ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
439 assert((isa<UsingDecl>(Pattern) ||
440 isa<UnresolvedUsingValueDecl>(Pattern) ||
441 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
442 "pattern decl is not a using decl");
443 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
444 InstantiatedFromUsingDecl[Inst] = Pattern;
445}
446
447UsingShadowDecl *
448ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
449 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
450 = InstantiatedFromUsingShadowDecl.find(Inst);
451 if (Pos == InstantiatedFromUsingShadowDecl.end())
452 return 0;
453
454 return Pos->second;
455}
456
457void
458ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
459 UsingShadowDecl *Pattern) {
460 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
461 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000462}
463
Anders Carlsson5da84842009-09-01 04:26:58 +0000464FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
465 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
466 = InstantiatedFromUnnamedFieldDecl.find(Field);
467 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
468 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000469
Anders Carlsson5da84842009-09-01 04:26:58 +0000470 return Pos->second;
471}
472
473void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
474 FieldDecl *Tmpl) {
475 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
476 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
477 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
478 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000479
Anders Carlsson5da84842009-09-01 04:26:58 +0000480 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
481}
482
Douglas Gregor832940b2010-03-02 23:58:15 +0000483ASTContext::overridden_cxx_method_iterator
484ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
485 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
486 = OverriddenMethods.find(Method);
487 if (Pos == OverriddenMethods.end())
488 return 0;
489
490 return Pos->second.begin();
491}
492
493ASTContext::overridden_cxx_method_iterator
494ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
495 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
496 = OverriddenMethods.find(Method);
497 if (Pos == OverriddenMethods.end())
498 return 0;
499
500 return Pos->second.end();
501}
502
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000503unsigned
504ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
505 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
506 = OverriddenMethods.find(Method);
507 if (Pos == OverriddenMethods.end())
508 return 0;
509
510 return Pos->second.size();
511}
512
Douglas Gregor832940b2010-03-02 23:58:15 +0000513void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
514 const CXXMethodDecl *Overridden) {
515 OverriddenMethods[Method].push_back(Overridden);
516}
517
Chris Lattner53cfe802007-07-18 17:52:12 +0000518//===----------------------------------------------------------------------===//
519// Type Sizing and Analysis
520//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000521
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000522/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
523/// scalar floating point type.
524const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000525 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000526 assert(BT && "Not a floating point type!");
527 switch (BT->getKind()) {
528 default: assert(0 && "Not a floating point type!");
529 case BuiltinType::Float: return Target.getFloatFormat();
530 case BuiltinType::Double: return Target.getDoubleFormat();
531 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
532 }
533}
534
Ken Dyck160146e2010-01-27 17:10:57 +0000535/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000536/// specified decl. Note that bitfields do not have a valid alignment, so
537/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000538/// If @p RefAsPointee, references are treated like their underlying type
539/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000540CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000541 unsigned Align = Target.getCharWidth();
542
John McCall94268702010-10-08 18:24:19 +0000543 bool UseAlignAttrOnly = false;
544 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
545 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000546
John McCall94268702010-10-08 18:24:19 +0000547 // __attribute__((aligned)) can increase or decrease alignment
548 // *except* on a struct or struct member, where it only increases
549 // alignment unless 'packed' is also specified.
550 //
551 // It is an error for [[align]] to decrease alignment, so we can
552 // ignore that possibility; Sema should diagnose it.
553 if (isa<FieldDecl>(D)) {
554 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
555 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
556 } else {
557 UseAlignAttrOnly = true;
558 }
559 }
560
561 if (UseAlignAttrOnly) {
562 // ignore type of value
563 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000564 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000565 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000566 if (RefAsPointee)
567 T = RT->getPointeeType();
568 else
569 T = getPointerType(RT->getPointeeType());
570 }
571 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000572 unsigned MinWidth = Target.getLargeArrayMinWidth();
573 unsigned ArrayAlign = Target.getLargeArrayAlign();
574 if (isa<VariableArrayType>(T) && MinWidth != 0)
575 Align = std::max(Align, ArrayAlign);
576 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
577 unsigned Size = getTypeSize(CT);
578 if (MinWidth != 0 && MinWidth <= Size)
579 Align = std::max(Align, ArrayAlign);
580 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000581 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000582 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
583 T = cast<ArrayType>(T)->getElementType();
584
585 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
586 }
Charles Davis3fc51072010-02-23 04:52:00 +0000587 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
588 // In the case of a field in a packed struct, we want the minimum
589 // of the alignment of the field and the alignment of the struct.
590 Align = std::min(Align,
591 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
592 }
Chris Lattner68061312009-01-24 21:53:27 +0000593 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000594
Ken Dyck160146e2010-01-27 17:10:57 +0000595 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000596}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000597
John McCall87fe5d52010-05-20 01:18:31 +0000598std::pair<CharUnits, CharUnits>
599ASTContext::getTypeInfoInChars(const Type *T) {
600 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
601 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
602 CharUnits::fromQuantity(Info.second / getCharWidth()));
603}
604
605std::pair<CharUnits, CharUnits>
606ASTContext::getTypeInfoInChars(QualType T) {
607 return getTypeInfoInChars(T.getTypePtr());
608}
609
Chris Lattner983a8bb2007-07-13 22:13:22 +0000610/// getTypeSize - Return the size of the specified type, in bits. This method
611/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000612///
613/// FIXME: Pointers into different addr spaces could have different sizes and
614/// alignment requirements: getPointerInfo should take an AddrSpace, this
615/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000616std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000617ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000618 uint64_t Width=0;
619 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000620 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000621#define TYPE(Class, Base)
622#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000623#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000624#define DEPENDENT_TYPE(Class, Base) case Type::Class:
625#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000626 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000627 break;
628
Chris Lattner355332d2007-07-13 22:27:08 +0000629 case Type::FunctionNoProto:
630 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000631 // GCC extension: alignof(function) = 32 bits
632 Width = 0;
633 Align = 32;
634 break;
635
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000636 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000637 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000638 Width = 0;
639 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
640 break;
641
Steve Naroff5c131802007-08-30 01:06:46 +0000642 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000643 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000644
Chris Lattner37e05872008-03-05 18:54:05 +0000645 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000646 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000647 Align = EltInfo.second;
648 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000649 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000650 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000651 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000652 const VectorType *VT = cast<VectorType>(T);
653 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
654 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000655 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000656 // If the alignment is not a power of 2, round up to the next power of 2.
657 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000658 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000659 Align = llvm::NextPowerOf2(Align);
660 Width = llvm::RoundUpToAlignment(Width, Align);
661 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000662 break;
663 }
Chris Lattner647fb222007-07-18 18:26:58 +0000664
Chris Lattner7570e9c2008-03-08 08:52:55 +0000665 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000666 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000667 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000668 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000669 // GCC extension: alignof(void) = 8 bits.
670 Width = 0;
671 Align = 8;
672 break;
673
Chris Lattner6a4f7452007-12-19 19:23:28 +0000674 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000675 Width = Target.getBoolWidth();
676 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000677 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000678 case BuiltinType::Char_S:
679 case BuiltinType::Char_U:
680 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000681 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000682 Width = Target.getCharWidth();
683 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000684 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000685 case BuiltinType::WChar_S:
686 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000687 Width = Target.getWCharWidth();
688 Align = Target.getWCharAlign();
689 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000690 case BuiltinType::Char16:
691 Width = Target.getChar16Width();
692 Align = Target.getChar16Align();
693 break;
694 case BuiltinType::Char32:
695 Width = Target.getChar32Width();
696 Align = Target.getChar32Align();
697 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000698 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000699 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000700 Width = Target.getShortWidth();
701 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000702 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000703 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000704 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000705 Width = Target.getIntWidth();
706 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000707 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000708 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000709 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000710 Width = Target.getLongWidth();
711 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000712 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000713 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000714 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000715 Width = Target.getLongLongWidth();
716 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000717 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000718 case BuiltinType::Int128:
719 case BuiltinType::UInt128:
720 Width = 128;
721 Align = 128; // int128_t is 128-bit aligned on all targets.
722 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000723 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000724 Width = Target.getFloatWidth();
725 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000726 break;
727 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000728 Width = Target.getDoubleWidth();
729 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000730 break;
731 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000732 Width = Target.getLongDoubleWidth();
733 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000734 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000735 case BuiltinType::NullPtr:
736 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
737 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000738 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000739 case BuiltinType::ObjCId:
740 case BuiltinType::ObjCClass:
741 case BuiltinType::ObjCSel:
742 Width = Target.getPointerWidth(0);
743 Align = Target.getPointerAlign(0);
744 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000745 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000746 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000747 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000748 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000749 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000750 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000751 case Type::BlockPointer: {
752 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
753 Width = Target.getPointerWidth(AS);
754 Align = Target.getPointerAlign(AS);
755 break;
756 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000757 case Type::LValueReference:
758 case Type::RValueReference: {
759 // alignof and sizeof should never enter this code path here, so we go
760 // the pointer route.
761 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
762 Width = Target.getPointerWidth(AS);
763 Align = Target.getPointerAlign(AS);
764 break;
765 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000766 case Type::Pointer: {
767 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000768 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000769 Align = Target.getPointerAlign(AS);
770 break;
771 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000772 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000773 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000774 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000775 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000776 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000777 Align = PtrDiffInfo.second;
778 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000779 }
Chris Lattner647fb222007-07-18 18:26:58 +0000780 case Type::Complex: {
781 // Complex types have the same alignment as their elements, but twice the
782 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000783 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000784 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000785 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000786 Align = EltInfo.second;
787 break;
788 }
John McCall8b07ec22010-05-15 11:32:37 +0000789 case Type::ObjCObject:
790 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000791 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000792 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000793 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
794 Width = Layout.getSize();
795 Align = Layout.getAlignment();
796 break;
797 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000798 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000799 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000800 const TagType *TT = cast<TagType>(T);
801
802 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000803 Width = 1;
804 Align = 1;
805 break;
806 }
Mike Stump11289f42009-09-09 15:08:12 +0000807
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000808 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000809 return getTypeInfo(ET->getDecl()->getIntegerType());
810
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000811 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000812 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
813 Width = Layout.getSize();
814 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000815 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000816 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000817
Chris Lattner63d2b362009-10-22 05:17:15 +0000818 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000819 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
820 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000821
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000822 case Type::Paren:
823 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
824
Douglas Gregoref462e62009-04-30 17:32:17 +0000825 case Type::Typedef: {
826 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000827 std::pair<uint64_t, unsigned> Info
828 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
829 Align = std::max(Typedef->getMaxAlignment(), Info.second);
830 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000831 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000832 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000833
834 case Type::TypeOfExpr:
835 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
836 .getTypePtr());
837
838 case Type::TypeOf:
839 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
840
Anders Carlsson81df7b82009-06-24 19:06:50 +0000841 case Type::Decltype:
842 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
843 .getTypePtr());
844
Abramo Bagnara6150c882010-05-11 21:36:43 +0000845 case Type::Elaborated:
846 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000847
John McCall81904512011-01-06 01:58:22 +0000848 case Type::Attributed:
849 return getTypeInfo(
850 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
851
Douglas Gregoref462e62009-04-30 17:32:17 +0000852 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000853 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000854 "Cannot request the size of a dependent type");
855 // FIXME: this is likely to be wrong once we support template
856 // aliases, since a template alias could refer to a typedef that
857 // has an __aligned__ attribute on it.
858 return getTypeInfo(getCanonicalType(T));
859 }
Mike Stump11289f42009-09-09 15:08:12 +0000860
Chris Lattner53cfe802007-07-18 17:52:12 +0000861 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000862 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000863}
864
Ken Dyck8c89d592009-12-22 14:23:30 +0000865/// getTypeSizeInChars - Return the size of the specified type, in characters.
866/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000867CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyck40775002010-01-11 17:06:35 +0000868 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000869}
Jay Foad39c79802011-01-12 09:06:06 +0000870CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyck40775002010-01-11 17:06:35 +0000871 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000872}
873
Ken Dycka6046ab2010-01-26 17:25:18 +0000874/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000875/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000876CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyck24d28d62010-01-26 17:22:55 +0000877 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
878}
Jay Foad39c79802011-01-12 09:06:06 +0000879CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyck24d28d62010-01-26 17:22:55 +0000880 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
881}
882
Chris Lattnera3402cd2009-01-27 18:08:34 +0000883/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
884/// type for the current target in bits. This can be different than the ABI
885/// alignment in cases where it is beneficial for performance to overalign
886/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +0000887unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +0000888 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000889
890 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000891 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000892 T = CT->getElementType().getTypePtr();
893 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
894 T->isSpecificBuiltinType(BuiltinType::LongLong))
895 return std::max(ABIAlign, (unsigned)getTypeSize(T));
896
Chris Lattnera3402cd2009-01-27 18:08:34 +0000897 return ABIAlign;
898}
899
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000900/// ShallowCollectObjCIvars -
901/// Collect all ivars, including those synthesized, in the current class.
902///
903void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +0000904 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000905 // FIXME. This need be removed but there are two many places which
906 // assume const-ness of ObjCInterfaceDecl
907 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
908 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
909 Iv= Iv->getNextIvar())
910 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000911}
912
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000913/// DeepCollectObjCIvars -
914/// This routine first collects all declared, but not synthesized, ivars in
915/// super class and then collects all ivars, including those synthesized for
916/// current class. This routine is used for implementation of current class
917/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000918///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000919void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
920 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +0000921 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000922 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
923 DeepCollectObjCIvars(SuperClass, false, Ivars);
924 if (!leafClass) {
925 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
926 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000927 Ivars.push_back(*I);
928 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000929 else
930 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000931}
932
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000933/// CollectInheritedProtocols - Collect all protocols in current class and
934/// those inherited by it.
935void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000936 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000937 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000938 // We can use protocol_iterator here instead of
939 // all_referenced_protocol_iterator since we are walking all categories.
940 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
941 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000942 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000943 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000944 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000945 PE = Proto->protocol_end(); P != PE; ++P) {
946 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000947 CollectInheritedProtocols(*P, Protocols);
948 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000949 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000950
951 // Categories of this Interface.
952 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
953 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
954 CollectInheritedProtocols(CDeclChain, Protocols);
955 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
956 while (SD) {
957 CollectInheritedProtocols(SD, Protocols);
958 SD = SD->getSuperClass();
959 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000960 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000961 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000962 PE = OC->protocol_end(); P != PE; ++P) {
963 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000964 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000965 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
966 PE = Proto->protocol_end(); P != PE; ++P)
967 CollectInheritedProtocols(*P, Protocols);
968 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000969 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000970 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
971 PE = OP->protocol_end(); P != PE; ++P) {
972 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000973 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000974 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
975 PE = Proto->protocol_end(); P != PE; ++P)
976 CollectInheritedProtocols(*P, Protocols);
977 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000978 }
979}
980
Jay Foad39c79802011-01-12 09:06:06 +0000981unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000982 unsigned count = 0;
983 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000984 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
985 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000986 count += CDecl->ivar_size();
987
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000988 // Count ivar defined in this class's implementation. This
989 // includes synthesized ivars.
990 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000991 count += ImplDecl->ivar_size();
992
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000993 return count;
994}
995
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000996/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
997ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
998 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
999 I = ObjCImpls.find(D);
1000 if (I != ObjCImpls.end())
1001 return cast<ObjCImplementationDecl>(I->second);
1002 return 0;
1003}
1004/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1005ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1006 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1007 I = ObjCImpls.find(D);
1008 if (I != ObjCImpls.end())
1009 return cast<ObjCCategoryImplDecl>(I->second);
1010 return 0;
1011}
1012
1013/// \brief Set the implementation of ObjCInterfaceDecl.
1014void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1015 ObjCImplementationDecl *ImplD) {
1016 assert(IFaceD && ImplD && "Passed null params");
1017 ObjCImpls[IFaceD] = ImplD;
1018}
1019/// \brief Set the implementation of ObjCCategoryDecl.
1020void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1021 ObjCCategoryImplDecl *ImplD) {
1022 assert(CatD && ImplD && "Passed null params");
1023 ObjCImpls[CatD] = ImplD;
1024}
1025
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001026/// \brief Get the copy initialization expression of VarDecl,or NULL if
1027/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001028Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001029 assert(VD && "Passed null params");
1030 assert(VD->hasAttr<BlocksAttr>() &&
1031 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001032 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001033 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001034 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1035}
1036
1037/// \brief Set the copy inialization expression of a block var decl.
1038void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1039 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001040 assert(VD->hasAttr<BlocksAttr>() &&
1041 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001042 BlockVarCopyInits[VD] = Init;
1043}
1044
John McCallbcd03502009-12-07 02:54:59 +00001045/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001046///
John McCallbcd03502009-12-07 02:54:59 +00001047/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001048/// the TypeLoc wrappers.
1049///
1050/// \param T the type that will be the basis for type source info. This type
1051/// should refer to how the declarator was written in source code, not to
1052/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001053TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001054 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001055 if (!DataSize)
1056 DataSize = TypeLoc::getFullDataSizeForType(T);
1057 else
1058 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001059 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001060
John McCallbcd03502009-12-07 02:54:59 +00001061 TypeSourceInfo *TInfo =
1062 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1063 new (TInfo) TypeSourceInfo(T);
1064 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001065}
1066
John McCallbcd03502009-12-07 02:54:59 +00001067TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001068 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001069 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001070 DI->getTypeLoc().initialize(L);
1071 return DI;
1072}
1073
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001074const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001075ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001076 return getObjCLayout(D, 0);
1077}
1078
1079const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001080ASTContext::getASTObjCImplementationLayout(
1081 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001082 return getObjCLayout(D->getClassInterface(), D);
1083}
1084
Chris Lattner983a8bb2007-07-13 22:13:22 +00001085//===----------------------------------------------------------------------===//
1086// Type creation/memoization methods
1087//===----------------------------------------------------------------------===//
1088
Jay Foad39c79802011-01-12 09:06:06 +00001089QualType
1090ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) const {
John McCall8ccfcb52009-09-24 19:53:00 +00001091 unsigned Fast = Quals.getFastQualifiers();
1092 Quals.removeFastQualifiers();
1093
1094 // Check if we've already instantiated this type.
1095 llvm::FoldingSetNodeID ID;
1096 ExtQuals::Profile(ID, TypeNode, Quals);
1097 void *InsertPos = 0;
1098 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1099 assert(EQ->getQualifiers() == Quals);
1100 QualType T = QualType(EQ, Fast);
1101 return T;
1102 }
1103
John McCall717d9b02010-12-10 11:01:00 +00001104 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001105 ExtQualNodes.InsertNode(New, InsertPos);
1106 QualType T = QualType(New, Fast);
1107 return T;
1108}
1109
Jay Foad39c79802011-01-12 09:06:06 +00001110QualType
1111ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001112 QualType CanT = getCanonicalType(T);
1113 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001114 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001115
John McCall8ccfcb52009-09-24 19:53:00 +00001116 // If we are composing extended qualifiers together, merge together
1117 // into one ExtQuals node.
1118 QualifierCollector Quals;
1119 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001120
John McCall8ccfcb52009-09-24 19:53:00 +00001121 // If this type already has an address space specified, it cannot get
1122 // another one.
1123 assert(!Quals.hasAddressSpace() &&
1124 "Type cannot be in multiple addr spaces!");
1125 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001126
John McCall8ccfcb52009-09-24 19:53:00 +00001127 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001128}
1129
Chris Lattnerd60183d2009-02-18 22:53:11 +00001130QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001131 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001132 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001133 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001134 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001135
John McCall53fa7142010-12-24 02:08:15 +00001136 if (const PointerType *ptr = T->getAs<PointerType>()) {
1137 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001138 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001139 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1140 return getPointerType(ResultType);
1141 }
1142 }
Mike Stump11289f42009-09-09 15:08:12 +00001143
John McCall8ccfcb52009-09-24 19:53:00 +00001144 // If we are composing extended qualifiers together, merge together
1145 // into one ExtQuals node.
1146 QualifierCollector Quals;
1147 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001148
John McCall8ccfcb52009-09-24 19:53:00 +00001149 // If this type already has an ObjCGC specified, it cannot get
1150 // another one.
1151 assert(!Quals.hasObjCGCAttr() &&
1152 "Type cannot have multiple ObjCGCs!");
1153 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001154
John McCall8ccfcb52009-09-24 19:53:00 +00001155 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001156}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001157
John McCall4f5019e2010-12-19 02:44:49 +00001158const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1159 FunctionType::ExtInfo Info) {
1160 if (T->getExtInfo() == Info)
1161 return T;
1162
1163 QualType Result;
1164 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1165 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1166 } else {
1167 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1168 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1169 EPI.ExtInfo = Info;
1170 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1171 FPT->getNumArgs(), EPI);
1172 }
1173
1174 return cast<FunctionType>(Result.getTypePtr());
1175}
1176
Chris Lattnerc6395932007-06-22 20:56:16 +00001177/// getComplexType - Return the uniqued reference to the type for a complex
1178/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001179QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001180 // Unique pointers, to guarantee there is only one pointer of a particular
1181 // structure.
1182 llvm::FoldingSetNodeID ID;
1183 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001184
Chris Lattnerc6395932007-06-22 20:56:16 +00001185 void *InsertPos = 0;
1186 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1187 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001188
Chris Lattnerc6395932007-06-22 20:56:16 +00001189 // If the pointee type isn't canonical, this won't be a canonical type either,
1190 // so fill in the canonical type field.
1191 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001192 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001193 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001194
Chris Lattnerc6395932007-06-22 20:56:16 +00001195 // Get the new insert position for the node we care about.
1196 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001197 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001198 }
John McCall90d1c2d2009-09-24 23:30:46 +00001199 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001200 Types.push_back(New);
1201 ComplexTypes.InsertNode(New, InsertPos);
1202 return QualType(New, 0);
1203}
1204
Chris Lattner970e54e2006-11-12 00:37:36 +00001205/// getPointerType - Return the uniqued reference to the type for a pointer to
1206/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001207QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001208 // Unique pointers, to guarantee there is only one pointer of a particular
1209 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001210 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001211 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001212
Chris Lattner67521df2007-01-27 01:29:36 +00001213 void *InsertPos = 0;
1214 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001215 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001216
Chris Lattner7ccecb92006-11-12 08:50:50 +00001217 // If the pointee type isn't canonical, this won't be a canonical type either,
1218 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001219 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001220 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001221 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001222
Chris Lattner67521df2007-01-27 01:29:36 +00001223 // Get the new insert position for the node we care about.
1224 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001225 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001226 }
John McCall90d1c2d2009-09-24 23:30:46 +00001227 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001228 Types.push_back(New);
1229 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001230 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001231}
1232
Mike Stump11289f42009-09-09 15:08:12 +00001233/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001234/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001235QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001236 assert(T->isFunctionType() && "block of function types only");
1237 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001238 // structure.
1239 llvm::FoldingSetNodeID ID;
1240 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001241
Steve Naroffec33ed92008-08-27 16:04:49 +00001242 void *InsertPos = 0;
1243 if (BlockPointerType *PT =
1244 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1245 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001246
1247 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001248 // type either so fill in the canonical type field.
1249 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001250 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001251 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001252
Steve Naroffec33ed92008-08-27 16:04:49 +00001253 // Get the new insert position for the node we care about.
1254 BlockPointerType *NewIP =
1255 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001256 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001257 }
John McCall90d1c2d2009-09-24 23:30:46 +00001258 BlockPointerType *New
1259 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001260 Types.push_back(New);
1261 BlockPointerTypes.InsertNode(New, InsertPos);
1262 return QualType(New, 0);
1263}
1264
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001265/// getLValueReferenceType - Return the uniqued reference to the type for an
1266/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001267QualType
1268ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001269 // Unique pointers, to guarantee there is only one pointer of a particular
1270 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001271 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001272 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001273
1274 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001275 if (LValueReferenceType *RT =
1276 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001277 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001278
John McCallfc93cf92009-10-22 22:37:11 +00001279 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1280
Bill Wendling3708c182007-05-27 10:15:43 +00001281 // If the referencee type isn't canonical, this won't be a canonical type
1282 // either, so fill in the canonical type field.
1283 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001284 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1285 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1286 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001287
Bill Wendling3708c182007-05-27 10:15:43 +00001288 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001289 LValueReferenceType *NewIP =
1290 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001291 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001292 }
1293
John McCall90d1c2d2009-09-24 23:30:46 +00001294 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001295 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1296 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001297 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001298 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001299
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001300 return QualType(New, 0);
1301}
1302
1303/// getRValueReferenceType - Return the uniqued reference to the type for an
1304/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001305QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001306 // Unique pointers, to guarantee there is only one pointer of a particular
1307 // structure.
1308 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001309 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001310
1311 void *InsertPos = 0;
1312 if (RValueReferenceType *RT =
1313 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1314 return QualType(RT, 0);
1315
John McCallfc93cf92009-10-22 22:37:11 +00001316 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1317
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001318 // If the referencee type isn't canonical, this won't be a canonical type
1319 // either, so fill in the canonical type field.
1320 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001321 if (InnerRef || !T.isCanonical()) {
1322 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1323 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001324
1325 // Get the new insert position for the node we care about.
1326 RValueReferenceType *NewIP =
1327 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001328 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001329 }
1330
John McCall90d1c2d2009-09-24 23:30:46 +00001331 RValueReferenceType *New
1332 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001333 Types.push_back(New);
1334 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001335 return QualType(New, 0);
1336}
1337
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001338/// getMemberPointerType - Return the uniqued reference to the type for a
1339/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001340QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001341 // Unique pointers, to guarantee there is only one pointer of a particular
1342 // structure.
1343 llvm::FoldingSetNodeID ID;
1344 MemberPointerType::Profile(ID, T, Cls);
1345
1346 void *InsertPos = 0;
1347 if (MemberPointerType *PT =
1348 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1349 return QualType(PT, 0);
1350
1351 // If the pointee or class type isn't canonical, this won't be a canonical
1352 // type either, so fill in the canonical type field.
1353 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001354 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001355 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1356
1357 // Get the new insert position for the node we care about.
1358 MemberPointerType *NewIP =
1359 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001360 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001361 }
John McCall90d1c2d2009-09-24 23:30:46 +00001362 MemberPointerType *New
1363 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001364 Types.push_back(New);
1365 MemberPointerTypes.InsertNode(New, InsertPos);
1366 return QualType(New, 0);
1367}
1368
Mike Stump11289f42009-09-09 15:08:12 +00001369/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001370/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001371QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001372 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001373 ArrayType::ArraySizeModifier ASM,
Jay Foad39c79802011-01-12 09:06:06 +00001374 unsigned EltTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001375 assert((EltTy->isDependentType() ||
1376 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001377 "Constant array of VLAs is illegal!");
1378
Chris Lattnere2df3f92009-05-13 04:12:56 +00001379 // Convert the array size into a canonical width matching the pointer size for
1380 // the target.
1381 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001382 ArySize =
1383 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001384
Chris Lattner23b7eb62007-06-15 23:05:46 +00001385 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001386 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001387
Chris Lattner36f8e652007-01-27 08:31:04 +00001388 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001389 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001390 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001391 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001392
Chris Lattner7ccecb92006-11-12 08:50:50 +00001393 // If the element type isn't canonical, this won't be a canonical type either,
1394 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001395 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001396 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001397 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001398 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001399 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001400 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001401 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001402 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001403 }
Mike Stump11289f42009-09-09 15:08:12 +00001404
John McCall90d1c2d2009-09-24 23:30:46 +00001405 ConstantArrayType *New = new(*this,TypeAlignment)
1406 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001407 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001408 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001409 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001410}
1411
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001412/// getIncompleteArrayType - Returns a unique reference to the type for a
1413/// incomplete array of the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001414QualType ASTContext::getUnknownSizeVariableArrayType(QualType Ty) const {
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001415 QualType ElemTy = getBaseElementType(Ty);
1416 DeclarationName Name;
1417 llvm::SmallVector<QualType, 8> ATypes;
1418 QualType ATy = Ty;
1419 while (const ArrayType *AT = getAsArrayType(ATy)) {
1420 ATypes.push_back(ATy);
1421 ATy = AT->getElementType();
1422 }
1423 for (int i = ATypes.size() - 1; i >= 0; i--) {
1424 if (const VariableArrayType *VAT = getAsVariableArrayType(ATypes[i])) {
1425 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Star,
1426 0, VAT->getBracketsRange());
1427 }
1428 else if (const ConstantArrayType *CAT = getAsConstantArrayType(ATypes[i])) {
1429 llvm::APSInt ConstVal(CAT->getSize());
1430 ElemTy = getConstantArrayType(ElemTy, ConstVal, ArrayType::Normal, 0);
1431 }
1432 else if (getAsIncompleteArrayType(ATypes[i])) {
1433 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Normal,
1434 0, SourceRange());
1435 }
1436 else
1437 assert(false && "DependentArrayType is seen");
1438 }
1439 return ElemTy;
1440}
1441
1442/// getVariableArrayDecayedType - Returns a vla type where known sizes
1443/// are replaced with [*]
Jay Foad39c79802011-01-12 09:06:06 +00001444QualType ASTContext::getVariableArrayDecayedType(QualType Ty) const {
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001445 if (Ty->isPointerType()) {
1446 QualType BaseType = Ty->getAs<PointerType>()->getPointeeType();
1447 if (isa<VariableArrayType>(BaseType)) {
1448 ArrayType *AT = dyn_cast<ArrayType>(BaseType);
1449 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1450 if (VAT->getSizeExpr()) {
1451 Ty = getUnknownSizeVariableArrayType(BaseType);
1452 Ty = getPointerType(Ty);
1453 }
1454 }
1455 }
1456 return Ty;
1457}
1458
1459
Steve Naroffcadebd02007-08-30 18:14:25 +00001460/// getVariableArrayType - Returns a non-unique reference to the type for a
1461/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001462QualType ASTContext::getVariableArrayType(QualType EltTy,
1463 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001464 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001465 unsigned EltTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001466 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001467 // Since we don't unique expressions, it isn't possible to unique VLA's
1468 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001469 QualType CanonType;
1470
1471 if (!EltTy.isCanonical()) {
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001472 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1473 EltTypeQuals, Brackets);
1474 }
1475
John McCall90d1c2d2009-09-24 23:30:46 +00001476 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001477 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001478
1479 VariableArrayTypes.push_back(New);
1480 Types.push_back(New);
1481 return QualType(New, 0);
1482}
1483
Douglas Gregor4619e432008-12-05 23:32:09 +00001484/// getDependentSizedArrayType - Returns a non-unique reference to
1485/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001486/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001487QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1488 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001489 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001490 unsigned EltTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001491 SourceRange Brackets) const {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001492 assert((!NumElts || NumElts->isTypeDependent() ||
1493 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001494 "Size must be type- or value-dependent!");
1495
Douglas Gregorf3f95522009-07-31 00:23:35 +00001496 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001497 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001498 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001499
Douglas Gregorf86c9392010-10-26 00:51:02 +00001500 QualType CanonicalEltTy = getCanonicalType(EltTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001501 if (NumElts) {
1502 // Dependently-sized array types that do not have a specified
1503 // number of elements will have their sizes deduced from an
1504 // initializer.
Douglas Gregorf86c9392010-10-26 00:51:02 +00001505 DependentSizedArrayType::Profile(ID, *this, CanonicalEltTy, ASM,
Douglas Gregorad2956c2009-11-19 18:03:26 +00001506 EltTypeQuals, NumElts);
1507
1508 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1509 }
1510
Douglas Gregorf3f95522009-07-31 00:23:35 +00001511 DependentSizedArrayType *New;
1512 if (Canon) {
1513 // We already have a canonical version of this array type; use it as
1514 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001515 New = new (*this, TypeAlignment)
1516 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1517 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf86c9392010-10-26 00:51:02 +00001518 } else if (CanonicalEltTy == EltTy) {
1519 // This is a canonical type. Record it.
1520 New = new (*this, TypeAlignment)
1521 DependentSizedArrayType(*this, EltTy, QualType(),
1522 NumElts, ASM, EltTypeQuals, Brackets);
1523
1524 if (NumElts) {
1525#ifndef NDEBUG
1526 DependentSizedArrayType *CanonCheck
1527 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1528 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1529 (void)CanonCheck;
1530#endif
1531 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001532 }
Douglas Gregorf86c9392010-10-26 00:51:02 +00001533 } else {
1534 QualType Canon = getDependentSizedArrayType(CanonicalEltTy, NumElts,
1535 ASM, EltTypeQuals,
1536 SourceRange());
1537 New = new (*this, TypeAlignment)
1538 DependentSizedArrayType(*this, EltTy, Canon,
1539 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001540 }
Mike Stump11289f42009-09-09 15:08:12 +00001541
Douglas Gregor4619e432008-12-05 23:32:09 +00001542 Types.push_back(New);
1543 return QualType(New, 0);
1544}
1545
Eli Friedmanbd258282008-02-15 18:16:39 +00001546QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1547 ArrayType::ArraySizeModifier ASM,
Jay Foad39c79802011-01-12 09:06:06 +00001548 unsigned EltTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001549 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001550 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001551
1552 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001553 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001554 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1555 return QualType(ATP, 0);
1556
1557 // If the element type isn't canonical, this won't be a canonical type
1558 // either, so fill in the canonical type field.
1559 QualType Canonical;
1560
John McCallb692a092009-10-22 20:10:53 +00001561 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001562 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001563 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001564
1565 // Get the new insert position for the node we care about.
1566 IncompleteArrayType *NewIP =
1567 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001568 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001569 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001570
John McCall90d1c2d2009-09-24 23:30:46 +00001571 IncompleteArrayType *New = new (*this, TypeAlignment)
1572 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001573
1574 IncompleteArrayTypes.InsertNode(New, InsertPos);
1575 Types.push_back(New);
1576 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001577}
1578
Steve Naroff91fcddb2007-07-18 18:00:27 +00001579/// getVectorType - Return the unique reference to a vector type of
1580/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001581QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001582 VectorType::VectorKind VecKind) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00001583 BuiltinType *BaseType;
Mike Stump11289f42009-09-09 15:08:12 +00001584
Chris Lattnerdc226c22010-10-01 22:42:38 +00001585 BaseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1586 assert(BaseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001587
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001588 // Check if we've already instantiated a vector of this type.
1589 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001590 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001591
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001592 void *InsertPos = 0;
1593 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1594 return QualType(VTP, 0);
1595
1596 // If the element type isn't canonical, this won't be a canonical type either,
1597 // so fill in the canonical type field.
1598 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001599 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001600 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001601
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001602 // Get the new insert position for the node we care about.
1603 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001604 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001605 }
John McCall90d1c2d2009-09-24 23:30:46 +00001606 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001607 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001608 VectorTypes.InsertNode(New, InsertPos);
1609 Types.push_back(New);
1610 return QualType(New, 0);
1611}
1612
Nate Begemance4d7fc2008-04-18 23:10:10 +00001613/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001614/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001615QualType
1616ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001617 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001618
Chris Lattner76a00cf2008-04-06 22:59:24 +00001619 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001620 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001621
Steve Naroff91fcddb2007-07-18 18:00:27 +00001622 // Check if we've already instantiated a vector of this type.
1623 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001624 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001625 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001626 void *InsertPos = 0;
1627 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1628 return QualType(VTP, 0);
1629
1630 // If the element type isn't canonical, this won't be a canonical type either,
1631 // so fill in the canonical type field.
1632 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001633 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001634 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001635
Steve Naroff91fcddb2007-07-18 18:00:27 +00001636 // Get the new insert position for the node we care about.
1637 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001638 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001639 }
John McCall90d1c2d2009-09-24 23:30:46 +00001640 ExtVectorType *New = new (*this, TypeAlignment)
1641 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001642 VectorTypes.InsertNode(New, InsertPos);
1643 Types.push_back(New);
1644 return QualType(New, 0);
1645}
1646
Jay Foad39c79802011-01-12 09:06:06 +00001647QualType
1648ASTContext::getDependentSizedExtVectorType(QualType vecType,
1649 Expr *SizeExpr,
1650 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001651 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001652 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001653 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001654
Douglas Gregor352169a2009-07-31 03:54:25 +00001655 void *InsertPos = 0;
1656 DependentSizedExtVectorType *Canon
1657 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1658 DependentSizedExtVectorType *New;
1659 if (Canon) {
1660 // We already have a canonical version of this array type; use it as
1661 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001662 New = new (*this, TypeAlignment)
1663 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1664 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001665 } else {
1666 QualType CanonVecTy = getCanonicalType(vecType);
1667 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001668 New = new (*this, TypeAlignment)
1669 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1670 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001671
1672 DependentSizedExtVectorType *CanonCheck
1673 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1674 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1675 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001676 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1677 } else {
1678 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1679 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001680 New = new (*this, TypeAlignment)
1681 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001682 }
1683 }
Mike Stump11289f42009-09-09 15:08:12 +00001684
Douglas Gregor758a8692009-06-17 21:51:59 +00001685 Types.push_back(New);
1686 return QualType(New, 0);
1687}
1688
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001689/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001690///
Jay Foad39c79802011-01-12 09:06:06 +00001691QualType
1692ASTContext::getFunctionNoProtoType(QualType ResultTy,
1693 const FunctionType::ExtInfo &Info) const {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001694 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001695 // Unique functions, to guarantee there is only one function of a particular
1696 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001697 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001698 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001699
Chris Lattner47955de2007-01-27 08:37:20 +00001700 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001701 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001702 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001703 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001704
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001705 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001706 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001707 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001708 Canonical =
1709 getFunctionNoProtoType(getCanonicalType(ResultTy),
1710 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001711
Chris Lattner47955de2007-01-27 08:37:20 +00001712 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001713 FunctionNoProtoType *NewIP =
1714 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001715 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001716 }
Mike Stump11289f42009-09-09 15:08:12 +00001717
John McCall90d1c2d2009-09-24 23:30:46 +00001718 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001719 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001720 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001721 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001722 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001723}
1724
1725/// getFunctionType - Return a normal function type with a typed argument
1726/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001727QualType
1728ASTContext::getFunctionType(QualType ResultTy,
1729 const QualType *ArgArray, unsigned NumArgs,
1730 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001731 // Unique functions, to guarantee there is only one function of a particular
1732 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001733 llvm::FoldingSetNodeID ID;
John McCalldb40c7f2010-12-14 08:05:40 +00001734 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001735
1736 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001737 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001738 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001739 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001740
1741 // Determine whether the type being created is already canonical or not.
John McCalldb40c7f2010-12-14 08:05:40 +00001742 bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001743 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001744 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001745 isCanonical = false;
1746
John McCalldb40c7f2010-12-14 08:05:40 +00001747 const CallingConv CallConv = EPI.ExtInfo.getCC();
1748
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001749 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001750 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001751 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001752 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001753 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001754 CanonicalArgs.reserve(NumArgs);
1755 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001756 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001757
John McCalldb40c7f2010-12-14 08:05:40 +00001758 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1759 if (CanonicalEPI.HasExceptionSpec) {
1760 CanonicalEPI.HasExceptionSpec = false;
1761 CanonicalEPI.HasAnyExceptionSpec = false;
1762 CanonicalEPI.NumExceptions = 0;
1763 }
1764 CanonicalEPI.ExtInfo
1765 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1766
Chris Lattner76a00cf2008-04-06 22:59:24 +00001767 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001768 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00001769 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001770
Chris Lattnerfd4de792007-01-27 01:15:32 +00001771 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001772 FunctionProtoType *NewIP =
1773 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001774 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001775 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001776
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001777 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001778 // for two variable size arrays (for parameter and exception types) at the
1779 // end of them.
John McCalldb40c7f2010-12-14 08:05:40 +00001780 size_t Size = sizeof(FunctionProtoType) +
1781 NumArgs * sizeof(QualType) +
1782 EPI.NumExceptions * sizeof(QualType);
1783 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
1784 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, EPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001785 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001786 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001787 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001788}
Chris Lattneref51c202006-11-10 07:17:23 +00001789
John McCalle78aac42010-03-10 03:28:59 +00001790#ifndef NDEBUG
1791static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1792 if (!isa<CXXRecordDecl>(D)) return false;
1793 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1794 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1795 return true;
1796 if (RD->getDescribedClassTemplate() &&
1797 !isa<ClassTemplateSpecializationDecl>(RD))
1798 return true;
1799 return false;
1800}
1801#endif
1802
1803/// getInjectedClassNameType - Return the unique reference to the
1804/// injected class name type for the specified templated declaration.
1805QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00001806 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00001807 assert(NeedsInjectedClassNameType(Decl));
1808 if (Decl->TypeForDecl) {
1809 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001810 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001811 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1812 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1813 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1814 } else {
John McCall2408e322010-04-27 00:57:59 +00001815 Decl->TypeForDecl =
1816 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001817 Types.push_back(Decl->TypeForDecl);
1818 }
1819 return QualType(Decl->TypeForDecl, 0);
1820}
1821
Douglas Gregor83a586e2008-04-13 21:07:44 +00001822/// getTypeDeclType - Return the unique reference to the type for the
1823/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00001824QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001825 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001826 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001827
John McCall81e38502010-02-16 03:57:14 +00001828 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001829 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001830
John McCall96f0b5f2010-03-10 06:48:02 +00001831 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1832 "Template type parameter types are always available.");
1833
John McCall81e38502010-02-16 03:57:14 +00001834 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001835 assert(!Record->getPreviousDeclaration() &&
1836 "struct/union has previous declaration");
1837 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001838 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001839 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001840 assert(!Enum->getPreviousDeclaration() &&
1841 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001842 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001843 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001844 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1845 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001846 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001847 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001848
John McCall96f0b5f2010-03-10 06:48:02 +00001849 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001850 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001851}
1852
Chris Lattner32d920b2007-01-26 02:01:53 +00001853/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001854/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001855QualType
Jay Foad39c79802011-01-12 09:06:06 +00001856ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001857 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001858
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001859 if (Canonical.isNull())
1860 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001861 Decl->TypeForDecl = new(*this, TypeAlignment)
1862 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001863 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001864 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001865}
1866
Jay Foad39c79802011-01-12 09:06:06 +00001867QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001868 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1869
1870 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1871 if (PrevDecl->TypeForDecl)
1872 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1873
1874 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1875 Types.push_back(Decl->TypeForDecl);
1876 return QualType(Decl->TypeForDecl, 0);
1877}
1878
Jay Foad39c79802011-01-12 09:06:06 +00001879QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001880 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1881
1882 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1883 if (PrevDecl->TypeForDecl)
1884 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1885
1886 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1887 Types.push_back(Decl->TypeForDecl);
1888 return QualType(Decl->TypeForDecl, 0);
1889}
1890
John McCall81904512011-01-06 01:58:22 +00001891QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
1892 QualType modifiedType,
1893 QualType equivalentType) {
1894 llvm::FoldingSetNodeID id;
1895 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
1896
1897 void *insertPos = 0;
1898 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
1899 if (type) return QualType(type, 0);
1900
1901 QualType canon = getCanonicalType(equivalentType);
1902 type = new (*this, TypeAlignment)
1903 AttributedType(canon, attrKind, modifiedType, equivalentType);
1904
1905 Types.push_back(type);
1906 AttributedTypes.InsertNode(type, insertPos);
1907
1908 return QualType(type, 0);
1909}
1910
1911
John McCallcebee162009-10-18 09:09:24 +00001912/// \brief Retrieve a substitution-result type.
1913QualType
1914ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00001915 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00001916 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001917 && "replacement types must always be canonical");
1918
1919 llvm::FoldingSetNodeID ID;
1920 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1921 void *InsertPos = 0;
1922 SubstTemplateTypeParmType *SubstParm
1923 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1924
1925 if (!SubstParm) {
1926 SubstParm = new (*this, TypeAlignment)
1927 SubstTemplateTypeParmType(Parm, Replacement);
1928 Types.push_back(SubstParm);
1929 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1930 }
1931
1932 return QualType(SubstParm, 0);
1933}
1934
Douglas Gregoreff93e02009-02-05 23:33:38 +00001935/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001936/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001937/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001938QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001939 bool ParameterPack,
Jay Foad39c79802011-01-12 09:06:06 +00001940 IdentifierInfo *Name) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001941 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001942 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001943 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001944 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001945 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1946
1947 if (TypeParm)
1948 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001949
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001950 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001951 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001952 TypeParm = new (*this, TypeAlignment)
1953 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001954
1955 TemplateTypeParmType *TypeCheck
1956 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1957 assert(!TypeCheck && "Template type parameter canonical type broken");
1958 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001959 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001960 TypeParm = new (*this, TypeAlignment)
1961 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001962
1963 Types.push_back(TypeParm);
1964 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1965
1966 return QualType(TypeParm, 0);
1967}
1968
John McCalle78aac42010-03-10 03:28:59 +00001969TypeSourceInfo *
1970ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1971 SourceLocation NameLoc,
1972 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00001973 QualType CanonType) const {
John McCalle78aac42010-03-10 03:28:59 +00001974 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1975
1976 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1977 TemplateSpecializationTypeLoc TL
1978 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1979 TL.setTemplateNameLoc(NameLoc);
1980 TL.setLAngleLoc(Args.getLAngleLoc());
1981 TL.setRAngleLoc(Args.getRAngleLoc());
1982 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1983 TL.setArgLocInfo(i, Args[i].getLocInfo());
1984 return DI;
1985}
1986
Mike Stump11289f42009-09-09 15:08:12 +00001987QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001988ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001989 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00001990 QualType Canon) const {
John McCall6b51f282009-11-23 01:53:49 +00001991 unsigned NumArgs = Args.size();
1992
John McCall0ad16662009-10-29 08:12:44 +00001993 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1994 ArgVec.reserve(NumArgs);
1995 for (unsigned i = 0; i != NumArgs; ++i)
1996 ArgVec.push_back(Args[i].getArgument());
1997
John McCall2408e322010-04-27 00:57:59 +00001998 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001999 Canon);
John McCall0ad16662009-10-29 08:12:44 +00002000}
2001
2002QualType
2003ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002004 const TemplateArgument *Args,
2005 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002006 QualType Canon) const {
Douglas Gregor15301382009-07-30 17:40:51 +00002007 if (!Canon.isNull())
2008 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002009 else
2010 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00002011
Douglas Gregora8e02e72009-07-28 23:00:59 +00002012 // Allocate the (non-canonical) template specialization type, but don't
2013 // try to unique it: these types typically have location information that
2014 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002015 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002016 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002017 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002018 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002019 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002020 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002021 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002022
Douglas Gregor8bf42052009-02-09 18:46:07 +00002023 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002024 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002025}
2026
Mike Stump11289f42009-09-09 15:08:12 +00002027QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002028ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2029 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002030 unsigned NumArgs) const {
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002031 // Build the canonical template specialization type.
2032 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2033 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2034 CanonArgs.reserve(NumArgs);
2035 for (unsigned I = 0; I != NumArgs; ++I)
2036 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2037
2038 // Determine whether this canonical template specialization type already
2039 // exists.
2040 llvm::FoldingSetNodeID ID;
2041 TemplateSpecializationType::Profile(ID, CanonTemplate,
2042 CanonArgs.data(), NumArgs, *this);
2043
2044 void *InsertPos = 0;
2045 TemplateSpecializationType *Spec
2046 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2047
2048 if (!Spec) {
2049 // Allocate a new canonical template specialization type.
2050 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2051 sizeof(TemplateArgument) * NumArgs),
2052 TypeAlignment);
2053 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2054 CanonArgs.data(), NumArgs,
2055 QualType());
2056 Types.push_back(Spec);
2057 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2058 }
2059
2060 assert(Spec->isDependentType() &&
2061 "Non-dependent template-id type must have a canonical type");
2062 return QualType(Spec, 0);
2063}
2064
2065QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002066ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2067 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002068 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002069 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002070 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002071
2072 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002073 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002074 if (T)
2075 return QualType(T, 0);
2076
Douglas Gregorc42075a2010-02-04 18:10:26 +00002077 QualType Canon = NamedType;
2078 if (!Canon.isCanonical()) {
2079 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002080 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2081 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002082 (void)CheckT;
2083 }
2084
Abramo Bagnara6150c882010-05-11 21:36:43 +00002085 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002086 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002087 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002088 return QualType(T, 0);
2089}
2090
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002091QualType
Jay Foad39c79802011-01-12 09:06:06 +00002092ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002093 llvm::FoldingSetNodeID ID;
2094 ParenType::Profile(ID, InnerType);
2095
2096 void *InsertPos = 0;
2097 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2098 if (T)
2099 return QualType(T, 0);
2100
2101 QualType Canon = InnerType;
2102 if (!Canon.isCanonical()) {
2103 Canon = getCanonicalType(InnerType);
2104 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2105 assert(!CheckT && "Paren canonical type broken");
2106 (void)CheckT;
2107 }
2108
2109 T = new (*this) ParenType(InnerType, Canon);
2110 Types.push_back(T);
2111 ParenTypes.InsertNode(T, InsertPos);
2112 return QualType(T, 0);
2113}
2114
Douglas Gregor02085352010-03-31 20:19:30 +00002115QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2116 NestedNameSpecifier *NNS,
2117 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002118 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002119 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2120
2121 if (Canon.isNull()) {
2122 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002123 ElaboratedTypeKeyword CanonKeyword = Keyword;
2124 if (Keyword == ETK_None)
2125 CanonKeyword = ETK_Typename;
2126
2127 if (CanonNNS != NNS || CanonKeyword != Keyword)
2128 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002129 }
2130
2131 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002132 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002133
2134 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002135 DependentNameType *T
2136 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002137 if (T)
2138 return QualType(T, 0);
2139
Douglas Gregor02085352010-03-31 20:19:30 +00002140 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002141 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002142 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002143 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002144}
2145
Mike Stump11289f42009-09-09 15:08:12 +00002146QualType
John McCallc392f372010-06-11 00:33:02 +00002147ASTContext::getDependentTemplateSpecializationType(
2148 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002149 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002150 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002151 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002152 // TODO: avoid this copy
2153 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2154 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2155 ArgCopy.push_back(Args[I].getArgument());
2156 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2157 ArgCopy.size(),
2158 ArgCopy.data());
2159}
2160
2161QualType
2162ASTContext::getDependentTemplateSpecializationType(
2163 ElaboratedTypeKeyword Keyword,
2164 NestedNameSpecifier *NNS,
2165 const IdentifierInfo *Name,
2166 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002167 const TemplateArgument *Args) const {
Douglas Gregordce2b622009-04-01 00:28:59 +00002168 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2169
Douglas Gregorc42075a2010-02-04 18:10:26 +00002170 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002171 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2172 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002173
2174 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002175 DependentTemplateSpecializationType *T
2176 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002177 if (T)
2178 return QualType(T, 0);
2179
John McCallc392f372010-06-11 00:33:02 +00002180 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002181
John McCallc392f372010-06-11 00:33:02 +00002182 ElaboratedTypeKeyword CanonKeyword = Keyword;
2183 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2184
2185 bool AnyNonCanonArgs = false;
2186 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2187 for (unsigned I = 0; I != NumArgs; ++I) {
2188 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2189 if (!CanonArgs[I].structurallyEquals(Args[I]))
2190 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002191 }
2192
John McCallc392f372010-06-11 00:33:02 +00002193 QualType Canon;
2194 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2195 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2196 Name, NumArgs,
2197 CanonArgs.data());
2198
2199 // Find the insert position again.
2200 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2201 }
2202
2203 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2204 sizeof(TemplateArgument) * NumArgs),
2205 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002206 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002207 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002208 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002209 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002210 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002211}
2212
Douglas Gregord2fa7662010-12-20 02:24:11 +00002213QualType ASTContext::getPackExpansionType(QualType Pattern) {
2214 llvm::FoldingSetNodeID ID;
2215 PackExpansionType::Profile(ID, Pattern);
2216
2217 assert(Pattern->containsUnexpandedParameterPack() &&
2218 "Pack expansions must expand one or more parameter packs");
2219 void *InsertPos = 0;
2220 PackExpansionType *T
2221 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2222 if (T)
2223 return QualType(T, 0);
2224
2225 QualType Canon;
2226 if (!Pattern.isCanonical()) {
2227 Canon = getPackExpansionType(getCanonicalType(Pattern));
2228
2229 // Find the insert position again.
2230 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2231 }
2232
2233 T = new (*this) PackExpansionType(Pattern, Canon);
2234 Types.push_back(T);
2235 PackExpansionTypes.InsertNode(T, InsertPos);
2236 return QualType(T, 0);
2237}
2238
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002239/// CmpProtocolNames - Comparison predicate for sorting protocols
2240/// alphabetically.
2241static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2242 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002243 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002244}
2245
John McCall8b07ec22010-05-15 11:32:37 +00002246static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002247 unsigned NumProtocols) {
2248 if (NumProtocols == 0) return true;
2249
2250 for (unsigned i = 1; i != NumProtocols; ++i)
2251 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2252 return false;
2253 return true;
2254}
2255
2256static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002257 unsigned &NumProtocols) {
2258 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002259
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002260 // Sort protocols, keyed by name.
2261 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2262
2263 // Remove duplicates.
2264 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2265 NumProtocols = ProtocolsEnd-Protocols;
2266}
2267
John McCall8b07ec22010-05-15 11:32:37 +00002268QualType ASTContext::getObjCObjectType(QualType BaseType,
2269 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002270 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002271 // If the base type is an interface and there aren't any protocols
2272 // to add, then the interface type will do just fine.
2273 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2274 return BaseType;
2275
2276 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002277 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002278 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002279 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002280 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2281 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002282
John McCall8b07ec22010-05-15 11:32:37 +00002283 // Build the canonical type, which has the canonical base type and
2284 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002285 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002286 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2287 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2288 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002289 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2290 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002291 unsigned UniqueCount = NumProtocols;
2292
John McCallfc93cf92009-10-22 22:37:11 +00002293 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002294 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2295 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002296 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002297 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2298 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002299 }
2300
2301 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002302 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2303 }
2304
2305 unsigned Size = sizeof(ObjCObjectTypeImpl);
2306 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2307 void *Mem = Allocate(Size, TypeAlignment);
2308 ObjCObjectTypeImpl *T =
2309 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2310
2311 Types.push_back(T);
2312 ObjCObjectTypes.InsertNode(T, InsertPos);
2313 return QualType(T, 0);
2314}
2315
2316/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2317/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002318QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002319 llvm::FoldingSetNodeID ID;
2320 ObjCObjectPointerType::Profile(ID, ObjectT);
2321
2322 void *InsertPos = 0;
2323 if (ObjCObjectPointerType *QT =
2324 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2325 return QualType(QT, 0);
2326
2327 // Find the canonical object type.
2328 QualType Canonical;
2329 if (!ObjectT.isCanonical()) {
2330 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2331
2332 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002333 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2334 }
2335
Douglas Gregorf85bee62010-02-08 22:59:26 +00002336 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002337 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2338 ObjCObjectPointerType *QType =
2339 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002340
Steve Narofffb4330f2009-06-17 22:40:22 +00002341 Types.push_back(QType);
2342 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002343 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002344}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002345
Douglas Gregor1c283312010-08-11 12:19:30 +00002346/// getObjCInterfaceType - Return the unique reference to the type for the
2347/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002348QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002349 if (Decl->TypeForDecl)
2350 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002351
Douglas Gregor1c283312010-08-11 12:19:30 +00002352 // FIXME: redeclarations?
2353 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2354 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2355 Decl->TypeForDecl = T;
2356 Types.push_back(T);
2357 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002358}
2359
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002360/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2361/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002362/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002363/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002364/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002365QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002366 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002367 if (tofExpr->isTypeDependent()) {
2368 llvm::FoldingSetNodeID ID;
2369 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002370
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002371 void *InsertPos = 0;
2372 DependentTypeOfExprType *Canon
2373 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2374 if (Canon) {
2375 // We already have a "canonical" version of an identical, dependent
2376 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002377 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002378 QualType((TypeOfExprType*)Canon, 0));
2379 }
2380 else {
2381 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002382 Canon
2383 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002384 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2385 toe = Canon;
2386 }
2387 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002388 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002389 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002390 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002391 Types.push_back(toe);
2392 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002393}
2394
Steve Naroffa773cd52007-08-01 18:02:17 +00002395/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2396/// TypeOfType AST's. The only motivation to unique these nodes would be
2397/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002398/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002399/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002400QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002401 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002402 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002403 Types.push_back(tot);
2404 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002405}
2406
Anders Carlssonad6bd352009-06-24 21:24:56 +00002407/// getDecltypeForExpr - Given an expr, will return the decltype for that
2408/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002409static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002410 if (e->isTypeDependent())
2411 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002412
Anders Carlssonad6bd352009-06-24 21:24:56 +00002413 // If e is an id expression or a class member access, decltype(e) is defined
2414 // as the type of the entity named by e.
2415 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2416 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2417 return VD->getType();
2418 }
2419 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2420 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2421 return FD->getType();
2422 }
2423 // If e is a function call or an invocation of an overloaded operator,
2424 // (parentheses around e are ignored), decltype(e) is defined as the
2425 // return type of that function.
2426 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2427 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002428
Anders Carlssonad6bd352009-06-24 21:24:56 +00002429 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002430
2431 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002432 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002433 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002434 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002435
Anders Carlssonad6bd352009-06-24 21:24:56 +00002436 return T;
2437}
2438
Anders Carlsson81df7b82009-06-24 19:06:50 +00002439/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2440/// DecltypeType AST's. The only motivation to unique these nodes would be
2441/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002442/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002443/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002444QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002445 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002446 if (e->isTypeDependent()) {
2447 llvm::FoldingSetNodeID ID;
2448 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002449
Douglas Gregora21f6c32009-07-30 23:36:40 +00002450 void *InsertPos = 0;
2451 DependentDecltypeType *Canon
2452 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2453 if (Canon) {
2454 // We already have a "canonical" version of an equivalent, dependent
2455 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002456 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002457 QualType((DecltypeType*)Canon, 0));
2458 }
2459 else {
2460 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002461 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002462 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2463 dt = Canon;
2464 }
2465 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002466 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002467 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002468 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002469 Types.push_back(dt);
2470 return QualType(dt, 0);
2471}
2472
Chris Lattnerfb072462007-01-23 05:45:31 +00002473/// getTagDeclType - Return the unique reference to the type for the
2474/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002475QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002476 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002477 // FIXME: What is the design on getTagDeclType when it requires casting
2478 // away const? mutable?
2479 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002480}
2481
Mike Stump11289f42009-09-09 15:08:12 +00002482/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2483/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2484/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002485CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002486 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002487}
Chris Lattnerfb072462007-01-23 05:45:31 +00002488
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002489/// getSignedWCharType - Return the type of "signed wchar_t".
2490/// Used when in C++, as a GCC extension.
2491QualType ASTContext::getSignedWCharType() const {
2492 // FIXME: derive from "Target" ?
2493 return WCharTy;
2494}
2495
2496/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2497/// Used when in C++, as a GCC extension.
2498QualType ASTContext::getUnsignedWCharType() const {
2499 // FIXME: derive from "Target" ?
2500 return UnsignedIntTy;
2501}
2502
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002503/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2504/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2505QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002506 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002507}
2508
Chris Lattnera21ad802008-04-02 05:18:44 +00002509//===----------------------------------------------------------------------===//
2510// Type Operators
2511//===----------------------------------------------------------------------===//
2512
Jay Foad39c79802011-01-12 09:06:06 +00002513CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002514 // Push qualifiers into arrays, and then discard any remaining
2515 // qualifiers.
2516 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002517 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002518 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002519 QualType Result;
2520 if (isa<ArrayType>(Ty)) {
2521 Result = getArrayDecayedType(QualType(Ty,0));
2522 } else if (isa<FunctionType>(Ty)) {
2523 Result = getPointerType(QualType(Ty, 0));
2524 } else {
2525 Result = QualType(Ty, 0);
2526 }
2527
2528 return CanQualType::CreateUnsafe(Result);
2529}
2530
Chris Lattnered0d0792008-04-06 22:41:35 +00002531/// getCanonicalType - Return the canonical (structural) type corresponding to
2532/// the specified potentially non-canonical type. The non-canonical version
2533/// of a type may have many "decorated" versions of types. Decorators can
2534/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2535/// to be free of any of these, allowing two canonical types to be compared
2536/// for exact equality with a simple pointer comparison.
Jay Foad39c79802011-01-12 09:06:06 +00002537CanQualType ASTContext::getCanonicalType(QualType T) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002538 QualifierCollector Quals;
2539 const Type *Ptr = Quals.strip(T);
2540 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002541
John McCall8ccfcb52009-09-24 19:53:00 +00002542 // The canonical internal type will be the canonical type *except*
2543 // that we push type qualifiers down through array types.
2544
2545 // If there are no new qualifiers to push down, stop here.
2546 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002547 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002548
John McCall8ccfcb52009-09-24 19:53:00 +00002549 // If the type qualifiers are on an array type, get the canonical
2550 // type of the array with the qualifiers applied to the element
2551 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002552 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2553 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002554 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002555
Chris Lattner7adf0762008-08-04 07:31:14 +00002556 // Get the canonical version of the element with the extra qualifiers on it.
2557 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002558 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002559 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002560
Chris Lattner7adf0762008-08-04 07:31:14 +00002561 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002562 return CanQualType::CreateUnsafe(
2563 getConstantArrayType(NewEltTy, CAT->getSize(),
2564 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002565 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002566 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002567 return CanQualType::CreateUnsafe(
2568 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002569 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002570
Douglas Gregor4619e432008-12-05 23:32:09 +00002571 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002572 return CanQualType::CreateUnsafe(
2573 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002574 DSAT->getSizeExpr(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002575 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002576 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002577 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002578
Chris Lattner7adf0762008-08-04 07:31:14 +00002579 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002580 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002581 VAT->getSizeExpr(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002582 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002583 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002584 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002585}
2586
Chandler Carruth607f38e2009-12-29 07:16:59 +00002587QualType ASTContext::getUnqualifiedArrayType(QualType T,
2588 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002589 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002590 const ArrayType *AT = getAsArrayType(T);
2591 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002592 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002593 }
2594
Chandler Carruth607f38e2009-12-29 07:16:59 +00002595 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002596 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002597 if (Elt == UnqualElt)
2598 return T;
2599
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002600 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002601 return getConstantArrayType(UnqualElt, CAT->getSize(),
2602 CAT->getSizeModifier(), 0);
2603 }
2604
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002605 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002606 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2607 }
2608
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002609 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2610 return getVariableArrayType(UnqualElt,
John McCallc3007a22010-10-26 07:05:15 +00002611 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002612 VAT->getSizeModifier(),
2613 VAT->getIndexTypeCVRQualifiers(),
2614 VAT->getBracketsRange());
2615 }
2616
2617 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCallc3007a22010-10-26 07:05:15 +00002618 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002619 DSAT->getSizeModifier(), 0,
2620 SourceRange());
2621}
2622
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002623/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2624/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2625/// they point to and return true. If T1 and T2 aren't pointer types
2626/// or pointer-to-member types, or if they are not similar at this
2627/// level, returns false and leaves T1 and T2 unchanged. Top-level
2628/// qualifiers on T1 and T2 are ignored. This function will typically
2629/// be called in a loop that successively "unwraps" pointer and
2630/// pointer-to-member types to compare them at each level.
2631bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2632 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2633 *T2PtrType = T2->getAs<PointerType>();
2634 if (T1PtrType && T2PtrType) {
2635 T1 = T1PtrType->getPointeeType();
2636 T2 = T2PtrType->getPointeeType();
2637 return true;
2638 }
2639
2640 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2641 *T2MPType = T2->getAs<MemberPointerType>();
2642 if (T1MPType && T2MPType &&
2643 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2644 QualType(T2MPType->getClass(), 0))) {
2645 T1 = T1MPType->getPointeeType();
2646 T2 = T2MPType->getPointeeType();
2647 return true;
2648 }
2649
2650 if (getLangOptions().ObjC1) {
2651 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2652 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2653 if (T1OPType && T2OPType) {
2654 T1 = T1OPType->getPointeeType();
2655 T2 = T2OPType->getPointeeType();
2656 return true;
2657 }
2658 }
2659
2660 // FIXME: Block pointers, too?
2661
2662 return false;
2663}
2664
Jay Foad39c79802011-01-12 09:06:06 +00002665DeclarationNameInfo
2666ASTContext::getNameForTemplate(TemplateName Name,
2667 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002668 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002669 // DNInfo work in progress: CHECKME: what about DNLoc?
2670 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2671
John McCall847e2a12009-11-24 18:42:40 +00002672 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002673 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002674 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002675 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2676 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002677 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002678 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2679 // DNInfo work in progress: FIXME: source locations?
2680 DeclarationNameLoc DNLoc;
2681 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2682 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2683 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002684 }
2685 }
2686
John McCalld28ae272009-12-02 08:04:21 +00002687 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2688 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002689 // DNInfo work in progress: CHECKME: what about DNLoc?
2690 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002691}
2692
Jay Foad39c79802011-01-12 09:06:06 +00002693TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002694 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2695 if (TemplateTemplateParmDecl *TTP
2696 = dyn_cast<TemplateTemplateParmDecl>(Template))
2697 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2698
2699 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002700 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002701 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002702
John McCalld28ae272009-12-02 08:04:21 +00002703 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002704
Douglas Gregor6bc50582009-05-07 06:41:52 +00002705 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2706 assert(DTN && "Non-dependent template names must refer to template decls.");
2707 return DTN->CanonicalTemplateName;
2708}
2709
Douglas Gregoradee3e32009-11-11 23:06:43 +00002710bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2711 X = getCanonicalTemplateName(X);
2712 Y = getCanonicalTemplateName(Y);
2713 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2714}
2715
Mike Stump11289f42009-09-09 15:08:12 +00002716TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00002717ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00002718 switch (Arg.getKind()) {
2719 case TemplateArgument::Null:
2720 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002721
Douglas Gregora8e02e72009-07-28 23:00:59 +00002722 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002723 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002724
Douglas Gregora8e02e72009-07-28 23:00:59 +00002725 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002726 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002727
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002728 case TemplateArgument::Template:
2729 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002730
2731 case TemplateArgument::TemplateExpansion:
2732 return TemplateArgument(getCanonicalTemplateName(
2733 Arg.getAsTemplateOrTemplatePattern()),
2734 true);
2735
Douglas Gregora8e02e72009-07-28 23:00:59 +00002736 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002737 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002738 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002739
Douglas Gregora8e02e72009-07-28 23:00:59 +00002740 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002741 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002742
Douglas Gregora8e02e72009-07-28 23:00:59 +00002743 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00002744 if (Arg.pack_size() == 0)
2745 return Arg;
2746
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002747 TemplateArgument *CanonArgs
2748 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00002749 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002750 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002751 AEnd = Arg.pack_end();
2752 A != AEnd; (void)++A, ++Idx)
2753 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002754
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002755 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00002756 }
2757 }
2758
2759 // Silence GCC warning
2760 assert(false && "Unhandled template argument kind");
2761 return TemplateArgument();
2762}
2763
Douglas Gregor333489b2009-03-27 23:10:48 +00002764NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00002765ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00002766 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002767 return 0;
2768
2769 switch (NNS->getKind()) {
2770 case NestedNameSpecifier::Identifier:
2771 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002772 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002773 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2774 NNS->getAsIdentifier());
2775
2776 case NestedNameSpecifier::Namespace:
2777 // A namespace is canonical; build a nested-name-specifier with
2778 // this namespace and no prefix.
2779 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2780
2781 case NestedNameSpecifier::TypeSpec:
2782 case NestedNameSpecifier::TypeSpecWithTemplate: {
2783 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00002784
2785 // If we have some kind of dependent-named type (e.g., "typename T::type"),
2786 // break it apart into its prefix and identifier, then reconsititute those
2787 // as the canonical nested-name-specifier. This is required to canonicalize
2788 // a dependent nested-name-specifier involving typedefs of dependent-name
2789 // types, e.g.,
2790 // typedef typename T::type T1;
2791 // typedef typename T1::type T2;
2792 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
2793 NestedNameSpecifier *Prefix
2794 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
2795 return NestedNameSpecifier::Create(*this, Prefix,
2796 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
2797 }
2798
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00002799 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00002800 if (const DependentTemplateSpecializationType *DTST
2801 = T->getAs<DependentTemplateSpecializationType>()) {
2802 NestedNameSpecifier *Prefix
2803 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
2804 TemplateName Name
2805 = getDependentTemplateName(Prefix, DTST->getIdentifier());
2806 T = getTemplateSpecializationType(Name,
2807 DTST->getArgs(), DTST->getNumArgs());
2808 T = getCanonicalType(T);
2809 }
2810
2811 return NestedNameSpecifier::Create(*this, 0, false, T.getTypePtr());
Douglas Gregor333489b2009-03-27 23:10:48 +00002812 }
2813
2814 case NestedNameSpecifier::Global:
2815 // The global specifier is canonical and unique.
2816 return NNS;
2817 }
2818
2819 // Required to silence a GCC warning
2820 return 0;
2821}
2822
Chris Lattner7adf0762008-08-04 07:31:14 +00002823
Jay Foad39c79802011-01-12 09:06:06 +00002824const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00002825 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002826 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002827 // Handle the common positive case fast.
2828 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2829 return AT;
2830 }
Mike Stump11289f42009-09-09 15:08:12 +00002831
John McCall8ccfcb52009-09-24 19:53:00 +00002832 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002833 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002834 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002835 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002836
John McCall8ccfcb52009-09-24 19:53:00 +00002837 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002838 // implements C99 6.7.3p8: "If the specification of an array type includes
2839 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002840
Chris Lattner7adf0762008-08-04 07:31:14 +00002841 // If we get here, we either have type qualifiers on the type, or we have
2842 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002843 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002844
John McCall8ccfcb52009-09-24 19:53:00 +00002845 QualifierCollector Qs;
John McCall717d9b02010-12-10 11:01:00 +00002846 const Type *Ty = Qs.strip(T.getDesugaredType(*this));
Mike Stump11289f42009-09-09 15:08:12 +00002847
Chris Lattner7adf0762008-08-04 07:31:14 +00002848 // If we have a simple case, just return now.
2849 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002850 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002851 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002852
Chris Lattner7adf0762008-08-04 07:31:14 +00002853 // Otherwise, we have an array and we have qualifiers on it. Push the
2854 // qualifiers into the array element type and return a new array type.
2855 // Get the canonical version of the element with the extra qualifiers on it.
2856 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002857 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002858
Chris Lattner7adf0762008-08-04 07:31:14 +00002859 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2860 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2861 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002862 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002863 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2864 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2865 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002866 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002867
Mike Stump11289f42009-09-09 15:08:12 +00002868 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002869 = dyn_cast<DependentSizedArrayType>(ATy))
2870 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002871 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002872 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00002873 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002874 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002875 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002876
Chris Lattner7adf0762008-08-04 07:31:14 +00002877 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002878 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002879 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00002880 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002881 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002882 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002883}
2884
Chris Lattnera21ad802008-04-02 05:18:44 +00002885/// getArrayDecayedType - Return the properly qualified result of decaying the
2886/// specified array type to a pointer. This operation is non-trivial when
2887/// handling typedefs etc. The canonical type of "T" must be an array type,
2888/// this returns a pointer to a properly qualified element of the array.
2889///
2890/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00002891QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00002892 // Get the element type with 'getAsArrayType' so that we don't lose any
2893 // typedefs in the element type of the array. This also handles propagation
2894 // of type qualifiers from the array type into the element type if present
2895 // (C99 6.7.3p8).
2896 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2897 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002898
Chris Lattner7adf0762008-08-04 07:31:14 +00002899 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002900
2901 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002902 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002903}
2904
Jay Foad39c79802011-01-12 09:06:06 +00002905QualType ASTContext::getBaseElementType(QualType QT) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002906 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002907 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2908 QT = AT->getElementType();
John McCall717d9b02010-12-10 11:01:00 +00002909 return Qs.apply(*this, QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002910}
2911
Jay Foad39c79802011-01-12 09:06:06 +00002912QualType ASTContext::getBaseElementType(const ArrayType *AT) const {
Anders Carlsson4bf82142009-09-25 01:23:32 +00002913 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002914
Anders Carlsson4bf82142009-09-25 01:23:32 +00002915 if (const ArrayType *AT = getAsArrayType(ElemTy))
2916 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002917
Anders Carlssone0808df2008-12-21 03:44:36 +00002918 return ElemTy;
2919}
2920
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002921/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002922uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002923ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2924 uint64_t ElementCount = 1;
2925 do {
2926 ElementCount *= CA->getSize().getZExtValue();
2927 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2928 } while (CA);
2929 return ElementCount;
2930}
2931
Steve Naroff0af91202007-04-27 21:51:21 +00002932/// getFloatingRank - Return a relative rank for floating point types.
2933/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002934static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002935 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002936 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002937
John McCall9dd450b2009-09-21 23:43:11 +00002938 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2939 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002940 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002941 case BuiltinType::Float: return FloatRank;
2942 case BuiltinType::Double: return DoubleRank;
2943 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002944 }
2945}
2946
Mike Stump11289f42009-09-09 15:08:12 +00002947/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2948/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002949/// 'typeDomain' is a real floating point or complex type.
2950/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002951QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2952 QualType Domain) const {
2953 FloatingRank EltRank = getFloatingRank(Size);
2954 if (Domain->isComplexType()) {
2955 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002956 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002957 case FloatRank: return FloatComplexTy;
2958 case DoubleRank: return DoubleComplexTy;
2959 case LongDoubleRank: return LongDoubleComplexTy;
2960 }
Steve Naroff0af91202007-04-27 21:51:21 +00002961 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002962
2963 assert(Domain->isRealFloatingType() && "Unknown domain!");
2964 switch (EltRank) {
2965 default: assert(0 && "getFloatingRank(): illegal value for rank");
2966 case FloatRank: return FloatTy;
2967 case DoubleRank: return DoubleTy;
2968 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002969 }
Steve Naroffe4718892007-04-27 18:30:00 +00002970}
2971
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002972/// getFloatingTypeOrder - Compare the rank of the two specified floating
2973/// point types, ignoring the domain of the type (i.e. 'double' ==
2974/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002975/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00002976int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002977 FloatingRank LHSR = getFloatingRank(LHS);
2978 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002979
Chris Lattnerb90739d2008-04-06 23:38:49 +00002980 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002981 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002982 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002983 return 1;
2984 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002985}
2986
Chris Lattner76a00cf2008-04-06 22:59:24 +00002987/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2988/// routine will assert if passed a built-in type that isn't an integer or enum,
2989/// or if it is not canonicalized.
Jay Foad39c79802011-01-12 09:06:06 +00002990unsigned ASTContext::getIntegerRank(Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00002991 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002992 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002993 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002994
Chris Lattnerad3467e2010-12-25 23:25:43 +00002995 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
2996 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002997 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2998
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002999 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3000 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3001
3002 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3003 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3004
Chris Lattner76a00cf2008-04-06 22:59:24 +00003005 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003006 default: assert(0 && "getIntegerRank(): not a built-in integer");
3007 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003008 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003009 case BuiltinType::Char_S:
3010 case BuiltinType::Char_U:
3011 case BuiltinType::SChar:
3012 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003013 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003014 case BuiltinType::Short:
3015 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003016 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003017 case BuiltinType::Int:
3018 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003019 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003020 case BuiltinType::Long:
3021 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003022 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003023 case BuiltinType::LongLong:
3024 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003025 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003026 case BuiltinType::Int128:
3027 case BuiltinType::UInt128:
3028 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003029 }
3030}
3031
Eli Friedman629ffb92009-08-20 04:21:42 +00003032/// \brief Whether this is a promotable bitfield reference according
3033/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3034///
3035/// \returns the type this bit-field will promote to, or NULL if no
3036/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003037QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003038 if (E->isTypeDependent() || E->isValueDependent())
3039 return QualType();
3040
Eli Friedman629ffb92009-08-20 04:21:42 +00003041 FieldDecl *Field = E->getBitField();
3042 if (!Field)
3043 return QualType();
3044
3045 QualType FT = Field->getType();
3046
3047 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3048 uint64_t BitWidth = BitWidthAP.getZExtValue();
3049 uint64_t IntSize = getTypeSize(IntTy);
3050 // GCC extension compatibility: if the bit-field size is less than or equal
3051 // to the size of int, it gets promoted no matter what its type is.
3052 // For instance, unsigned long bf : 4 gets promoted to signed int.
3053 if (BitWidth < IntSize)
3054 return IntTy;
3055
3056 if (BitWidth == IntSize)
3057 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3058
3059 // Types bigger than int are not subject to promotions, and therefore act
3060 // like the base type.
3061 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3062 // is ridiculous.
3063 return QualType();
3064}
3065
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003066/// getPromotedIntegerType - Returns the type that Promotable will
3067/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3068/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003069QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003070 assert(!Promotable.isNull());
3071 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003072 if (const EnumType *ET = Promotable->getAs<EnumType>())
3073 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003074 if (Promotable->isSignedIntegerType())
3075 return IntTy;
3076 uint64_t PromotableSize = getTypeSize(Promotable);
3077 uint64_t IntSize = getTypeSize(IntTy);
3078 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3079 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3080}
3081
Mike Stump11289f42009-09-09 15:08:12 +00003082/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003083/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003084/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003085int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003086 Type *LHSC = getCanonicalType(LHS).getTypePtr();
3087 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003088 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003089
Chris Lattner76a00cf2008-04-06 22:59:24 +00003090 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3091 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003092
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003093 unsigned LHSRank = getIntegerRank(LHSC);
3094 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003095
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003096 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3097 if (LHSRank == RHSRank) return 0;
3098 return LHSRank > RHSRank ? 1 : -1;
3099 }
Mike Stump11289f42009-09-09 15:08:12 +00003100
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003101 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3102 if (LHSUnsigned) {
3103 // If the unsigned [LHS] type is larger, return it.
3104 if (LHSRank >= RHSRank)
3105 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003106
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003107 // If the signed type can represent all values of the unsigned type, it
3108 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003109 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003110 return -1;
3111 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003112
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003113 // If the unsigned [RHS] type is larger, return it.
3114 if (RHSRank >= LHSRank)
3115 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003116
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003117 // If the signed type can represent all values of the unsigned type, it
3118 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003119 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003120 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003121}
Anders Carlsson98f07902007-08-17 05:31:46 +00003122
Anders Carlsson6d417272009-11-14 21:45:58 +00003123static RecordDecl *
Jay Foad39c79802011-01-12 09:06:06 +00003124CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
Anders Carlsson6d417272009-11-14 21:45:58 +00003125 SourceLocation L, IdentifierInfo *Id) {
3126 if (Ctx.getLangOptions().CPlusPlus)
3127 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3128 else
3129 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3130}
3131
Mike Stump11289f42009-09-09 15:08:12 +00003132// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003133QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003134 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003135 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003136 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003137 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003138 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003139
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003140 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003141
Anders Carlsson98f07902007-08-17 05:31:46 +00003142 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003143 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003144 // int flags;
3145 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003146 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003147 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003148 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003149 FieldTypes[3] = LongTy;
3150
Anders Carlsson98f07902007-08-17 05:31:46 +00003151 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003152 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003153 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003154 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003155 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003156 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003157 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003158 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003159 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003160 }
3161
Douglas Gregord5058122010-02-11 01:19:42 +00003162 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003163 }
Mike Stump11289f42009-09-09 15:08:12 +00003164
Anders Carlsson98f07902007-08-17 05:31:46 +00003165 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003166}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003167
Douglas Gregor512b0772009-04-23 22:29:11 +00003168void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003169 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003170 assert(Rec && "Invalid CFConstantStringType");
3171 CFConstantStringTypeDecl = Rec->getDecl();
3172}
3173
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003174// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003175QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003176 if (!NSConstantStringTypeDecl) {
3177 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003178 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003179 &Idents.get("__builtin_NSString"));
3180 NSConstantStringTypeDecl->startDefinition();
3181
3182 QualType FieldTypes[3];
3183
3184 // const int *isa;
3185 FieldTypes[0] = getPointerType(IntTy.withConst());
3186 // const char *str;
3187 FieldTypes[1] = getPointerType(CharTy.withConst());
3188 // unsigned int length;
3189 FieldTypes[2] = UnsignedIntTy;
3190
3191 // Create fields
3192 for (unsigned i = 0; i < 3; ++i) {
3193 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3194 SourceLocation(), 0,
3195 FieldTypes[i], /*TInfo=*/0,
3196 /*BitWidth=*/0,
3197 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003198 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003199 NSConstantStringTypeDecl->addDecl(Field);
3200 }
3201
3202 NSConstantStringTypeDecl->completeDefinition();
3203 }
3204
3205 return getTagDeclType(NSConstantStringTypeDecl);
3206}
3207
3208void ASTContext::setNSConstantStringType(QualType T) {
3209 const RecordType *Rec = T->getAs<RecordType>();
3210 assert(Rec && "Invalid NSConstantStringType");
3211 NSConstantStringTypeDecl = Rec->getDecl();
3212}
3213
Jay Foad39c79802011-01-12 09:06:06 +00003214QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003215 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003216 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003217 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003218 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003219 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003220
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003221 QualType FieldTypes[] = {
3222 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003223 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003224 getPointerType(UnsignedLongTy),
3225 getConstantArrayType(UnsignedLongTy,
3226 llvm::APInt(32, 5), ArrayType::Normal, 0)
3227 };
Mike Stump11289f42009-09-09 15:08:12 +00003228
Douglas Gregor91f84212008-12-11 16:49:14 +00003229 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003230 FieldDecl *Field = FieldDecl::Create(*this,
3231 ObjCFastEnumerationStateTypeDecl,
3232 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003233 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003234 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003235 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003236 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003237 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003238 }
Mike Stump11289f42009-09-09 15:08:12 +00003239
Douglas Gregord5058122010-02-11 01:19:42 +00003240 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003241 }
Mike Stump11289f42009-09-09 15:08:12 +00003242
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003243 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3244}
3245
Jay Foad39c79802011-01-12 09:06:06 +00003246QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003247 if (BlockDescriptorType)
3248 return getTagDeclType(BlockDescriptorType);
3249
3250 RecordDecl *T;
3251 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003252 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003253 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003254 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003255
3256 QualType FieldTypes[] = {
3257 UnsignedLongTy,
3258 UnsignedLongTy,
3259 };
3260
3261 const char *FieldNames[] = {
3262 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003263 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003264 };
3265
3266 for (size_t i = 0; i < 2; ++i) {
3267 FieldDecl *Field = FieldDecl::Create(*this,
3268 T,
3269 SourceLocation(),
3270 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003271 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003272 /*BitWidth=*/0,
3273 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003274 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003275 T->addDecl(Field);
3276 }
3277
Douglas Gregord5058122010-02-11 01:19:42 +00003278 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003279
3280 BlockDescriptorType = T;
3281
3282 return getTagDeclType(BlockDescriptorType);
3283}
3284
3285void ASTContext::setBlockDescriptorType(QualType T) {
3286 const RecordType *Rec = T->getAs<RecordType>();
3287 assert(Rec && "Invalid BlockDescriptorType");
3288 BlockDescriptorType = Rec->getDecl();
3289}
3290
Jay Foad39c79802011-01-12 09:06:06 +00003291QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003292 if (BlockDescriptorExtendedType)
3293 return getTagDeclType(BlockDescriptorExtendedType);
3294
3295 RecordDecl *T;
3296 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003297 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003298 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003299 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003300
3301 QualType FieldTypes[] = {
3302 UnsignedLongTy,
3303 UnsignedLongTy,
3304 getPointerType(VoidPtrTy),
3305 getPointerType(VoidPtrTy)
3306 };
3307
3308 const char *FieldNames[] = {
3309 "reserved",
3310 "Size",
3311 "CopyFuncPtr",
3312 "DestroyFuncPtr"
3313 };
3314
3315 for (size_t i = 0; i < 4; ++i) {
3316 FieldDecl *Field = FieldDecl::Create(*this,
3317 T,
3318 SourceLocation(),
3319 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003320 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003321 /*BitWidth=*/0,
3322 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003323 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003324 T->addDecl(Field);
3325 }
3326
Douglas Gregord5058122010-02-11 01:19:42 +00003327 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003328
3329 BlockDescriptorExtendedType = T;
3330
3331 return getTagDeclType(BlockDescriptorExtendedType);
3332}
3333
3334void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3335 const RecordType *Rec = T->getAs<RecordType>();
3336 assert(Rec && "Invalid BlockDescriptorType");
3337 BlockDescriptorExtendedType = Rec->getDecl();
3338}
3339
Jay Foad39c79802011-01-12 09:06:06 +00003340bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003341 if (Ty->isBlockPointerType())
3342 return true;
3343 if (isObjCNSObjectType(Ty))
3344 return true;
3345 if (Ty->isObjCObjectPointerType())
3346 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003347 if (getLangOptions().CPlusPlus) {
3348 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3349 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3350 return RD->hasConstCopyConstructor(*this);
3351
3352 }
3353 }
Mike Stump94967902009-10-21 18:16:27 +00003354 return false;
3355}
3356
Jay Foad39c79802011-01-12 09:06:06 +00003357QualType
3358ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003359 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003360 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003361 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003362 // unsigned int __flags;
3363 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003364 // void *__copy_helper; // as needed
3365 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003366 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003367 // } *
3368
Mike Stump94967902009-10-21 18:16:27 +00003369 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3370
3371 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003372 llvm::SmallString<36> Name;
3373 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3374 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003375 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003376 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003377 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003378 T->startDefinition();
3379 QualType Int32Ty = IntTy;
3380 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3381 QualType FieldTypes[] = {
3382 getPointerType(VoidPtrTy),
3383 getPointerType(getTagDeclType(T)),
3384 Int32Ty,
3385 Int32Ty,
3386 getPointerType(VoidPtrTy),
3387 getPointerType(VoidPtrTy),
3388 Ty
3389 };
3390
Daniel Dunbar56df9772010-08-17 22:39:59 +00003391 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003392 "__isa",
3393 "__forwarding",
3394 "__flags",
3395 "__size",
3396 "__copy_helper",
3397 "__destroy_helper",
3398 DeclName,
3399 };
3400
3401 for (size_t i = 0; i < 7; ++i) {
3402 if (!HasCopyAndDispose && i >=4 && i <= 5)
3403 continue;
3404 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3405 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003406 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003407 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003408 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003409 T->addDecl(Field);
3410 }
3411
Douglas Gregord5058122010-02-11 01:19:42 +00003412 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003413
3414 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003415}
3416
3417
3418QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003419 bool BlockHasCopyDispose,
Jay Foad39c79802011-01-12 09:06:06 +00003420 llvm::SmallVectorImpl<const Expr *> &Layout) const {
John McCall87fe5d52010-05-20 01:18:31 +00003421
Mike Stumpd0153282009-10-20 02:12:22 +00003422 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003423 llvm::SmallString<36> Name;
3424 llvm::raw_svector_ostream(Name) << "__block_literal_"
3425 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003426 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003427 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003428 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003429 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003430 QualType FieldTypes[] = {
3431 getPointerType(VoidPtrTy),
3432 IntTy,
3433 IntTy,
3434 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003435 (BlockHasCopyDispose ?
3436 getPointerType(getBlockDescriptorExtendedType()) :
3437 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003438 };
3439
3440 const char *FieldNames[] = {
3441 "__isa",
3442 "__flags",
3443 "__reserved",
3444 "__FuncPtr",
3445 "__descriptor"
3446 };
3447
3448 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003449 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003450 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003451 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003452 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003453 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003454 T->addDecl(Field);
3455 }
3456
John McCall87fe5d52010-05-20 01:18:31 +00003457 for (unsigned i = 0; i < Layout.size(); ++i) {
3458 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003459
John McCall87fe5d52010-05-20 01:18:31 +00003460 QualType FieldType = E->getType();
3461 IdentifierInfo *FieldName = 0;
3462 if (isa<CXXThisExpr>(E)) {
3463 FieldName = &Idents.get("this");
3464 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3465 const ValueDecl *D = BDRE->getDecl();
3466 FieldName = D->getIdentifier();
3467 if (BDRE->isByRef())
Daniel Dunbar56df9772010-08-17 22:39:59 +00003468 FieldType = BuildByRefType(D->getName(), FieldType);
John McCall87fe5d52010-05-20 01:18:31 +00003469 } else {
3470 // Padding.
3471 assert(isa<ConstantArrayType>(FieldType) &&
3472 isa<DeclRefExpr>(E) &&
3473 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3474 "doesn't match characteristics of padding decl");
3475 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003476
3477 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003478 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003479 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003480 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003481 T->addDecl(Field);
3482 }
3483
Douglas Gregord5058122010-02-11 01:19:42 +00003484 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003485
3486 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003487}
3488
Douglas Gregor512b0772009-04-23 22:29:11 +00003489void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003490 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003491 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3492 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3493}
3494
Anders Carlsson18acd442007-10-29 06:33:42 +00003495// This returns true if a type has been typedefed to BOOL:
3496// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003497static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003498 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003499 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3500 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003501
Anders Carlssond8499822007-10-29 05:01:08 +00003502 return false;
3503}
3504
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003505/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003506/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003507CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003508 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003509
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003510 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003511 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003512 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003513 // Treat arrays as pointers, since that's how they're passed in.
3514 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003515 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003516 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003517}
3518
3519static inline
3520std::string charUnitsToString(const CharUnits &CU) {
3521 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003522}
3523
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003524/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003525/// declaration.
3526void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
Jay Foad39c79802011-01-12 09:06:06 +00003527 std::string& S) const {
David Chisnall950a9512009-11-17 19:33:30 +00003528 const BlockDecl *Decl = Expr->getBlockDecl();
3529 QualType BlockTy =
3530 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3531 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003532 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003533 // Compute size of all parameters.
3534 // Start with computing size of a pointer in number of bytes.
3535 // FIXME: There might(should) be a better way of doing this computation!
3536 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003537 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3538 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003539 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003540 E = Decl->param_end(); PI != E; ++PI) {
3541 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003542 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003543 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003544 ParmOffset += sz;
3545 }
3546 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003547 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003548 // Block pointer and offset.
3549 S += "@?0";
3550 ParmOffset = PtrSize;
3551
3552 // Argument types.
3553 ParmOffset = PtrSize;
3554 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3555 Decl->param_end(); PI != E; ++PI) {
3556 ParmVarDecl *PVDecl = *PI;
3557 QualType PType = PVDecl->getOriginalType();
3558 if (const ArrayType *AT =
3559 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3560 // Use array's original type only if it has known number of
3561 // elements.
3562 if (!isa<ConstantArrayType>(AT))
3563 PType = PVDecl->getType();
3564 } else if (PType->isFunctionType())
3565 PType = PVDecl->getType();
3566 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003567 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003568 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003569 }
3570}
3571
David Chisnall50e4eba2010-12-30 14:05:53 +00003572void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3573 std::string& S) {
3574 // Encode result type.
3575 getObjCEncodingForType(Decl->getResultType(), S);
3576 CharUnits ParmOffset;
3577 // Compute size of all parameters.
3578 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3579 E = Decl->param_end(); PI != E; ++PI) {
3580 QualType PType = (*PI)->getType();
3581 CharUnits sz = getObjCEncodingTypeSize(PType);
3582 assert (sz.isPositive() &&
3583 "getObjCEncodingForMethodDecl - Incomplete param type");
3584 ParmOffset += sz;
3585 }
3586 S += charUnitsToString(ParmOffset);
3587 ParmOffset = CharUnits::Zero();
3588
3589 // Argument types.
3590 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3591 E = Decl->param_end(); PI != E; ++PI) {
3592 ParmVarDecl *PVDecl = *PI;
3593 QualType PType = PVDecl->getOriginalType();
3594 if (const ArrayType *AT =
3595 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3596 // Use array's original type only if it has known number of
3597 // elements.
3598 if (!isa<ConstantArrayType>(AT))
3599 PType = PVDecl->getType();
3600 } else if (PType->isFunctionType())
3601 PType = PVDecl->getType();
3602 getObjCEncodingForType(PType, S);
3603 S += charUnitsToString(ParmOffset);
3604 ParmOffset += getObjCEncodingTypeSize(PType);
3605 }
3606}
3607
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003608/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003609/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003610void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003611 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003612 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003613 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003614 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003615 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003616 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003617 // Compute size of all parameters.
3618 // Start with computing size of a pointer in number of bytes.
3619 // FIXME: There might(should) be a better way of doing this computation!
3620 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003621 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003622 // The first two arguments (self and _cmd) are pointers; account for
3623 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003624 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003625 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003626 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003627 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003628 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003629 assert (sz.isPositive() &&
3630 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003631 ParmOffset += sz;
3632 }
Ken Dyck40775002010-01-11 17:06:35 +00003633 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003634 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003635 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003636
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003637 // Argument types.
3638 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003639 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003640 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003641 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003642 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003643 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003644 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3645 // Use array's original type only if it has known number of
3646 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003647 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003648 PType = PVDecl->getType();
3649 } else if (PType->isFunctionType())
3650 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003651 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003652 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003653 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003654 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003655 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003656 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003657 }
3658}
3659
Daniel Dunbar4932b362008-08-28 04:38:10 +00003660/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003661/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003662/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3663/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003664/// Property attributes are stored as a comma-delimited C string. The simple
3665/// attributes readonly and bycopy are encoded as single characters. The
3666/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3667/// encoded as single characters, followed by an identifier. Property types
3668/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003669/// these attributes are defined by the following enumeration:
3670/// @code
3671/// enum PropertyAttributes {
3672/// kPropertyReadOnly = 'R', // property is read-only.
3673/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3674/// kPropertyByref = '&', // property is a reference to the value last assigned
3675/// kPropertyDynamic = 'D', // property is dynamic
3676/// kPropertyGetter = 'G', // followed by getter selector name
3677/// kPropertySetter = 'S', // followed by setter selector name
3678/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3679/// kPropertyType = 't' // followed by old-style type encoding.
3680/// kPropertyWeak = 'W' // 'weak' property
3681/// kPropertyStrong = 'P' // property GC'able
3682/// kPropertyNonAtomic = 'N' // property non-atomic
3683/// };
3684/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003685void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003686 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003687 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003688 // Collect information from the property implementation decl(s).
3689 bool Dynamic = false;
3690 ObjCPropertyImplDecl *SynthesizePID = 0;
3691
3692 // FIXME: Duplicated code due to poor abstraction.
3693 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003694 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003695 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3696 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003697 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003698 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003699 ObjCPropertyImplDecl *PID = *i;
3700 if (PID->getPropertyDecl() == PD) {
3701 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3702 Dynamic = true;
3703 } else {
3704 SynthesizePID = PID;
3705 }
3706 }
3707 }
3708 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003709 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003710 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003711 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003712 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003713 ObjCPropertyImplDecl *PID = *i;
3714 if (PID->getPropertyDecl() == PD) {
3715 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3716 Dynamic = true;
3717 } else {
3718 SynthesizePID = PID;
3719 }
3720 }
Mike Stump11289f42009-09-09 15:08:12 +00003721 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003722 }
3723 }
3724
3725 // FIXME: This is not very efficient.
3726 S = "T";
3727
3728 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003729 // GCC has some special rules regarding encoding of properties which
3730 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003731 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003732 true /* outermost type */,
3733 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003734
3735 if (PD->isReadOnly()) {
3736 S += ",R";
3737 } else {
3738 switch (PD->getSetterKind()) {
3739 case ObjCPropertyDecl::Assign: break;
3740 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003741 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003742 }
3743 }
3744
3745 // It really isn't clear at all what this means, since properties
3746 // are "dynamic by default".
3747 if (Dynamic)
3748 S += ",D";
3749
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003750 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3751 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003752
Daniel Dunbar4932b362008-08-28 04:38:10 +00003753 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3754 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003755 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003756 }
3757
3758 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3759 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003760 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003761 }
3762
3763 if (SynthesizePID) {
3764 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3765 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003766 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003767 }
3768
3769 // FIXME: OBJCGC: weak & strong
3770}
3771
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003772/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003773/// Another legacy compatibility encoding: 32-bit longs are encoded as
3774/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003775/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3776///
3777void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003778 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003779 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00003780 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003781 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003782 else
Jay Foad39c79802011-01-12 09:06:06 +00003783 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003784 PointeeTy = IntTy;
3785 }
3786 }
3787}
3788
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003789void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00003790 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003791 // We follow the behavior of gcc, expanding structures which are
3792 // directly pointed to, and expanding embedded structures. Note that
3793 // these rules are sufficient to prevent recursive encoding of the
3794 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003795 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003796 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003797}
3798
David Chisnallb190a2c2010-06-04 01:10:52 +00003799static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3800 switch (T->getAs<BuiltinType>()->getKind()) {
3801 default: assert(0 && "Unhandled builtin type kind");
3802 case BuiltinType::Void: return 'v';
3803 case BuiltinType::Bool: return 'B';
3804 case BuiltinType::Char_U:
3805 case BuiltinType::UChar: return 'C';
3806 case BuiltinType::UShort: return 'S';
3807 case BuiltinType::UInt: return 'I';
3808 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00003809 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003810 case BuiltinType::UInt128: return 'T';
3811 case BuiltinType::ULongLong: return 'Q';
3812 case BuiltinType::Char_S:
3813 case BuiltinType::SChar: return 'c';
3814 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00003815 case BuiltinType::WChar_S:
3816 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00003817 case BuiltinType::Int: return 'i';
3818 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00003819 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003820 case BuiltinType::LongLong: return 'q';
3821 case BuiltinType::Int128: return 't';
3822 case BuiltinType::Float: return 'f';
3823 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00003824 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00003825 }
3826}
3827
Jay Foad39c79802011-01-12 09:06:06 +00003828static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003829 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003830 const Expr *E = FD->getBitWidth();
3831 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003832 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003833 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3834 // The GNU runtime requires more information; bitfields are encoded as b,
3835 // then the offset (in bits) of the first element, then the type of the
3836 // bitfield, then the size in bits. For example, in this structure:
3837 //
3838 // struct
3839 // {
3840 // int integer;
3841 // int flags:2;
3842 // };
3843 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3844 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3845 // information is not especially sensible, but we're stuck with it for
3846 // compatibility with GCC, although providing it breaks anything that
3847 // actually uses runtime introspection and wants to work on both runtimes...
3848 if (!Ctx->getLangOptions().NeXTRuntime) {
3849 const RecordDecl *RD = FD->getParent();
3850 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3851 // FIXME: This same linear search is also used in ExprConstant - it might
3852 // be better if the FieldDecl stored its offset. We'd be increasing the
3853 // size of the object slightly, but saving some time every time it is used.
3854 unsigned i = 0;
3855 for (RecordDecl::field_iterator Field = RD->field_begin(),
3856 FieldEnd = RD->field_end();
3857 Field != FieldEnd; (void)++Field, ++i) {
3858 if (*Field == FD)
3859 break;
3860 }
3861 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00003862 if (T->isEnumeralType())
3863 S += 'i';
3864 else
Jay Foad39c79802011-01-12 09:06:06 +00003865 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00003866 }
3867 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003868 S += llvm::utostr(N);
3869}
3870
Daniel Dunbar07d07852009-10-18 21:17:35 +00003871// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003872void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3873 bool ExpandPointedToStructures,
3874 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003875 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003876 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00003877 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00003878 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003879 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003880 return EncodeBitField(this, S, T, FD);
3881 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003882 return;
3883 }
Mike Stump11289f42009-09-09 15:08:12 +00003884
John McCall9dd450b2009-09-21 23:43:11 +00003885 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003886 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003887 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003888 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003889 return;
3890 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003891
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003892 // encoding for pointer or r3eference types.
3893 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003894 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003895 if (PT->isObjCSelType()) {
3896 S += ':';
3897 return;
3898 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003899 PointeeTy = PT->getPointeeType();
3900 }
3901 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3902 PointeeTy = RT->getPointeeType();
3903 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003904 bool isReadOnly = false;
3905 // For historical/compatibility reasons, the read-only qualifier of the
3906 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3907 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003908 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003909 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003910 if (OutermostType && T.isConstQualified()) {
3911 isReadOnly = true;
3912 S += 'r';
3913 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003914 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003915 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003916 while (P->getAs<PointerType>())
3917 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003918 if (P.isConstQualified()) {
3919 isReadOnly = true;
3920 S += 'r';
3921 }
3922 }
3923 if (isReadOnly) {
3924 // Another legacy compatibility encoding. Some ObjC qualifier and type
3925 // combinations need to be rearranged.
3926 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003927 if (llvm::StringRef(S).endswith("nr"))
3928 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003929 }
Mike Stump11289f42009-09-09 15:08:12 +00003930
Anders Carlssond8499822007-10-29 05:01:08 +00003931 if (PointeeTy->isCharType()) {
3932 // char pointer types should be encoded as '*' unless it is a
3933 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003934 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003935 S += '*';
3936 return;
3937 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003938 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003939 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3940 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3941 S += '#';
3942 return;
3943 }
3944 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3945 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3946 S += '@';
3947 return;
3948 }
3949 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003950 }
Anders Carlssond8499822007-10-29 05:01:08 +00003951 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003952 getLegacyIntegralTypeEncoding(PointeeTy);
3953
Mike Stump11289f42009-09-09 15:08:12 +00003954 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003955 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003956 return;
3957 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003958
Chris Lattnere7cabb92009-07-13 00:10:46 +00003959 if (const ArrayType *AT =
3960 // Ignore type qualifiers etc.
3961 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003962 if (isa<IncompleteArrayType>(AT)) {
3963 // Incomplete arrays are encoded as a pointer to the array element.
3964 S += '^';
3965
Mike Stump11289f42009-09-09 15:08:12 +00003966 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003967 false, ExpandStructures, FD);
3968 } else {
3969 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003970
Anders Carlssond05f44b2009-02-22 01:38:57 +00003971 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3972 S += llvm::utostr(CAT->getSize().getZExtValue());
3973 else {
3974 //Variable length arrays are encoded as a regular array with 0 elements.
3975 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3976 S += '0';
3977 }
Mike Stump11289f42009-09-09 15:08:12 +00003978
3979 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003980 false, ExpandStructures, FD);
3981 S += ']';
3982 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003983 return;
3984 }
Mike Stump11289f42009-09-09 15:08:12 +00003985
John McCall9dd450b2009-09-21 23:43:11 +00003986 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003987 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003988 return;
3989 }
Mike Stump11289f42009-09-09 15:08:12 +00003990
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003991 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003992 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003993 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003994 // Anonymous structures print as '?'
3995 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3996 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003997 if (ClassTemplateSpecializationDecl *Spec
3998 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3999 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4000 std::string TemplateArgsStr
4001 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004002 TemplateArgs.data(),
4003 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004004 (*this).PrintingPolicy);
4005
4006 S += TemplateArgsStr;
4007 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004008 } else {
4009 S += '?';
4010 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004011 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004012 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004013 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4014 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004015 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004016 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004017 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004018 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004019 S += '"';
4020 }
Mike Stump11289f42009-09-09 15:08:12 +00004021
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004022 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004023 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004024 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004025 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004026 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004027 QualType qt = Field->getType();
4028 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004029 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004030 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004031 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004032 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004033 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004034 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004035 return;
4036 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004037
Chris Lattnere7cabb92009-07-13 00:10:46 +00004038 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004039 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004040 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004041 else
4042 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004043 return;
4044 }
Mike Stump11289f42009-09-09 15:08:12 +00004045
Chris Lattnere7cabb92009-07-13 00:10:46 +00004046 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004047 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004048 return;
4049 }
Mike Stump11289f42009-09-09 15:08:12 +00004050
John McCall8b07ec22010-05-15 11:32:37 +00004051 // Ignore protocol qualifiers when mangling at this level.
4052 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4053 T = OT->getBaseType();
4054
John McCall8ccfcb52009-09-24 19:53:00 +00004055 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004056 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004057 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004058 S += '{';
4059 const IdentifierInfo *II = OI->getIdentifier();
4060 S += II->getName();
4061 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004062 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4063 DeepCollectObjCIvars(OI, true, Ivars);
4064 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4065 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4066 if (Field->isBitField())
4067 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004068 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004069 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004070 }
4071 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004072 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004073 }
Mike Stump11289f42009-09-09 15:08:12 +00004074
John McCall9dd450b2009-09-21 23:43:11 +00004075 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004076 if (OPT->isObjCIdType()) {
4077 S += '@';
4078 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004079 }
Mike Stump11289f42009-09-09 15:08:12 +00004080
Steve Narofff0c86112009-10-28 22:03:49 +00004081 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4082 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4083 // Since this is a binary compatibility issue, need to consult with runtime
4084 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004085 S += '#';
4086 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004087 }
Mike Stump11289f42009-09-09 15:08:12 +00004088
Chris Lattnere7cabb92009-07-13 00:10:46 +00004089 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004090 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004091 ExpandPointedToStructures,
4092 ExpandStructures, FD);
4093 if (FD || EncodingProperty) {
4094 // Note that we do extended encoding of protocol qualifer list
4095 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004096 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004097 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4098 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004099 S += '<';
4100 S += (*I)->getNameAsString();
4101 S += '>';
4102 }
4103 S += '"';
4104 }
4105 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004106 }
Mike Stump11289f42009-09-09 15:08:12 +00004107
Chris Lattnere7cabb92009-07-13 00:10:46 +00004108 QualType PointeeTy = OPT->getPointeeType();
4109 if (!EncodingProperty &&
4110 isa<TypedefType>(PointeeTy.getTypePtr())) {
4111 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004112 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004113 // {...};
4114 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004115 getObjCEncodingForTypeImpl(PointeeTy, S,
4116 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004117 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004118 return;
4119 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004120
4121 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004122 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004123 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004124 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004125 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4126 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004127 S += '<';
4128 S += (*I)->getNameAsString();
4129 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004130 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004131 S += '"';
4132 }
4133 return;
4134 }
Mike Stump11289f42009-09-09 15:08:12 +00004135
John McCalla9e6e8d2010-05-17 23:56:34 +00004136 // gcc just blithely ignores member pointers.
4137 // TODO: maybe there should be a mangling for these
4138 if (T->getAs<MemberPointerType>())
4139 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004140
4141 if (T->isVectorType()) {
4142 // This matches gcc's encoding, even though technically it is
4143 // insufficient.
4144 // FIXME. We should do a better job than gcc.
4145 return;
4146 }
4147
Chris Lattnere7cabb92009-07-13 00:10:46 +00004148 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004149}
4150
Mike Stump11289f42009-09-09 15:08:12 +00004151void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004152 std::string& S) const {
4153 if (QT & Decl::OBJC_TQ_In)
4154 S += 'n';
4155 if (QT & Decl::OBJC_TQ_Inout)
4156 S += 'N';
4157 if (QT & Decl::OBJC_TQ_Out)
4158 S += 'o';
4159 if (QT & Decl::OBJC_TQ_Bycopy)
4160 S += 'O';
4161 if (QT & Decl::OBJC_TQ_Byref)
4162 S += 'R';
4163 if (QT & Decl::OBJC_TQ_Oneway)
4164 S += 'V';
4165}
4166
Chris Lattnere7cabb92009-07-13 00:10:46 +00004167void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004168 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004169
Anders Carlsson87c149b2007-10-11 01:00:40 +00004170 BuiltinVaListType = T;
4171}
4172
Chris Lattnere7cabb92009-07-13 00:10:46 +00004173void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004174 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004175}
4176
Chris Lattnere7cabb92009-07-13 00:10:46 +00004177void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004178 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004179}
4180
Chris Lattnere7cabb92009-07-13 00:10:46 +00004181void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004182 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004183}
4184
Chris Lattnere7cabb92009-07-13 00:10:46 +00004185void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004186 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004187}
4188
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004189void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004190 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004191 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004192
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004193 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004194}
4195
John McCalld28ae272009-12-02 08:04:21 +00004196/// \brief Retrieve the template name that corresponds to a non-empty
4197/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004198TemplateName
4199ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4200 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004201 unsigned size = End - Begin;
4202 assert(size > 1 && "set is not overloaded!");
4203
4204 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4205 size * sizeof(FunctionTemplateDecl*));
4206 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4207
4208 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004209 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004210 NamedDecl *D = *I;
4211 assert(isa<FunctionTemplateDecl>(D) ||
4212 (isa<UsingShadowDecl>(D) &&
4213 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4214 *Storage++ = D;
4215 }
4216
4217 return TemplateName(OT);
4218}
4219
Douglas Gregordc572a32009-03-30 22:58:21 +00004220/// \brief Retrieve the template name that represents a qualified
4221/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004222TemplateName
4223ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4224 bool TemplateKeyword,
4225 TemplateDecl *Template) const {
Douglas Gregorc42075a2010-02-04 18:10:26 +00004226 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004227 llvm::FoldingSetNodeID ID;
4228 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4229
4230 void *InsertPos = 0;
4231 QualifiedTemplateName *QTN =
4232 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4233 if (!QTN) {
4234 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4235 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4236 }
4237
4238 return TemplateName(QTN);
4239}
4240
4241/// \brief Retrieve the template name that represents a dependent
4242/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004243TemplateName
4244ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4245 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004246 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004247 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004248
4249 llvm::FoldingSetNodeID ID;
4250 DependentTemplateName::Profile(ID, NNS, Name);
4251
4252 void *InsertPos = 0;
4253 DependentTemplateName *QTN =
4254 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4255
4256 if (QTN)
4257 return TemplateName(QTN);
4258
4259 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4260 if (CanonNNS == NNS) {
4261 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4262 } else {
4263 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4264 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004265 DependentTemplateName *CheckQTN =
4266 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4267 assert(!CheckQTN && "Dependent type name canonicalization broken");
4268 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004269 }
4270
4271 DependentTemplateNames.InsertNode(QTN, InsertPos);
4272 return TemplateName(QTN);
4273}
4274
Douglas Gregor71395fa2009-11-04 00:56:37 +00004275/// \brief Retrieve the template name that represents a dependent
4276/// template name such as \c MetaFun::template operator+.
4277TemplateName
4278ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004279 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004280 assert((!NNS || NNS->isDependent()) &&
4281 "Nested name specifier must be dependent");
4282
4283 llvm::FoldingSetNodeID ID;
4284 DependentTemplateName::Profile(ID, NNS, Operator);
4285
4286 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004287 DependentTemplateName *QTN
4288 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004289
4290 if (QTN)
4291 return TemplateName(QTN);
4292
4293 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4294 if (CanonNNS == NNS) {
4295 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4296 } else {
4297 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4298 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004299
4300 DependentTemplateName *CheckQTN
4301 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4302 assert(!CheckQTN && "Dependent template name canonicalization broken");
4303 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004304 }
4305
4306 DependentTemplateNames.InsertNode(QTN, InsertPos);
4307 return TemplateName(QTN);
4308}
4309
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004310/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004311/// TargetInfo, produce the corresponding type. The unsigned @p Type
4312/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004313CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004314 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004315 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004316 case TargetInfo::SignedShort: return ShortTy;
4317 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4318 case TargetInfo::SignedInt: return IntTy;
4319 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4320 case TargetInfo::SignedLong: return LongTy;
4321 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4322 case TargetInfo::SignedLongLong: return LongLongTy;
4323 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4324 }
4325
4326 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004327 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004328}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004329
4330//===----------------------------------------------------------------------===//
4331// Type Predicates.
4332//===----------------------------------------------------------------------===//
4333
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004334/// isObjCNSObjectType - Return true if this is an NSObject object using
4335/// NSObject attribute on a c-style pointer type.
4336/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004337/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004338///
4339bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4340 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4341 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004342 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004343 return true;
4344 }
Mike Stump11289f42009-09-09 15:08:12 +00004345 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004346}
4347
Fariborz Jahanian96207692009-02-18 21:49:28 +00004348/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4349/// garbage collection attribute.
4350///
John McCall553d45a2011-01-12 00:34:59 +00004351Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4352 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4353 return Qualifiers::GCNone;
4354
4355 assert(getLangOptions().ObjC1);
4356 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4357
4358 // Default behaviour under objective-C's gc is for ObjC pointers
4359 // (or pointers to them) be treated as though they were declared
4360 // as __strong.
4361 if (GCAttrs == Qualifiers::GCNone) {
4362 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4363 return Qualifiers::Strong;
4364 else if (Ty->isPointerType())
4365 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4366 } else {
4367 // It's not valid to set GC attributes on anything that isn't a
4368 // pointer.
4369#ifndef NDEBUG
4370 QualType CT = Ty->getCanonicalTypeInternal();
4371 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4372 CT = AT->getElementType();
4373 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4374#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004375 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004376 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004377}
4378
Chris Lattner49af6a42008-04-07 06:51:04 +00004379//===----------------------------------------------------------------------===//
4380// Type Compatibility Testing
4381//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004382
Mike Stump11289f42009-09-09 15:08:12 +00004383/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004384/// compatible.
4385static bool areCompatVectorTypes(const VectorType *LHS,
4386 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004387 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004388 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004389 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004390}
4391
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004392bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4393 QualType SecondVec) {
4394 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4395 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4396
4397 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4398 return true;
4399
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004400 // Treat Neon vector types and most AltiVec vector types as if they are the
4401 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004402 const VectorType *First = FirstVec->getAs<VectorType>();
4403 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004404 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004405 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004406 First->getVectorKind() != VectorType::AltiVecPixel &&
4407 First->getVectorKind() != VectorType::AltiVecBool &&
4408 Second->getVectorKind() != VectorType::AltiVecPixel &&
4409 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004410 return true;
4411
4412 return false;
4413}
4414
Steve Naroff8e6aee52009-07-23 01:01:38 +00004415//===----------------------------------------------------------------------===//
4416// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4417//===----------------------------------------------------------------------===//
4418
4419/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4420/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004421bool
4422ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4423 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004424 if (lProto == rProto)
4425 return true;
4426 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4427 E = rProto->protocol_end(); PI != E; ++PI)
4428 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4429 return true;
4430 return false;
4431}
4432
Steve Naroff8e6aee52009-07-23 01:01:38 +00004433/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4434/// return true if lhs's protocols conform to rhs's protocol; false
4435/// otherwise.
4436bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4437 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4438 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4439 return false;
4440}
4441
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004442/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4443/// Class<p1, ...>.
4444bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4445 QualType rhs) {
4446 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4447 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4448 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4449
4450 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4451 E = lhsQID->qual_end(); I != E; ++I) {
4452 bool match = false;
4453 ObjCProtocolDecl *lhsProto = *I;
4454 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4455 E = rhsOPT->qual_end(); J != E; ++J) {
4456 ObjCProtocolDecl *rhsProto = *J;
4457 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4458 match = true;
4459 break;
4460 }
4461 }
4462 if (!match)
4463 return false;
4464 }
4465 return true;
4466}
4467
Steve Naroff8e6aee52009-07-23 01:01:38 +00004468/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4469/// ObjCQualifiedIDType.
4470bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4471 bool compare) {
4472 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004473 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004474 lhs->isObjCIdType() || lhs->isObjCClassType())
4475 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004476 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004477 rhs->isObjCIdType() || rhs->isObjCClassType())
4478 return true;
4479
4480 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004481 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004482
Steve Naroff8e6aee52009-07-23 01:01:38 +00004483 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004484
Steve Naroff8e6aee52009-07-23 01:01:38 +00004485 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004486 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004487 // make sure we check the class hierarchy.
4488 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4489 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4490 E = lhsQID->qual_end(); I != E; ++I) {
4491 // when comparing an id<P> on lhs with a static type on rhs,
4492 // see if static class implements all of id's protocols, directly or
4493 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004494 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004495 return false;
4496 }
4497 }
4498 // If there are no qualifiers and no interface, we have an 'id'.
4499 return true;
4500 }
Mike Stump11289f42009-09-09 15:08:12 +00004501 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004502 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4503 E = lhsQID->qual_end(); I != E; ++I) {
4504 ObjCProtocolDecl *lhsProto = *I;
4505 bool match = false;
4506
4507 // when comparing an id<P> on lhs with a static type on rhs,
4508 // see if static class implements all of id's protocols, directly or
4509 // through its super class and categories.
4510 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4511 E = rhsOPT->qual_end(); J != E; ++J) {
4512 ObjCProtocolDecl *rhsProto = *J;
4513 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4514 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4515 match = true;
4516 break;
4517 }
4518 }
Mike Stump11289f42009-09-09 15:08:12 +00004519 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004520 // make sure we check the class hierarchy.
4521 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4522 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4523 E = lhsQID->qual_end(); I != E; ++I) {
4524 // when comparing an id<P> on lhs with a static type on rhs,
4525 // see if static class implements all of id's protocols, directly or
4526 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004527 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004528 match = true;
4529 break;
4530 }
4531 }
4532 }
4533 if (!match)
4534 return false;
4535 }
Mike Stump11289f42009-09-09 15:08:12 +00004536
Steve Naroff8e6aee52009-07-23 01:01:38 +00004537 return true;
4538 }
Mike Stump11289f42009-09-09 15:08:12 +00004539
Steve Naroff8e6aee52009-07-23 01:01:38 +00004540 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4541 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4542
Mike Stump11289f42009-09-09 15:08:12 +00004543 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004544 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004545 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004546 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4547 E = lhsOPT->qual_end(); I != E; ++I) {
4548 ObjCProtocolDecl *lhsProto = *I;
4549 bool match = false;
4550
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004551 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004552 // see if static class implements all of id's protocols, directly or
4553 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004554 // First, lhs protocols in the qualifier list must be found, direct
4555 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004556 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4557 E = rhsQID->qual_end(); J != E; ++J) {
4558 ObjCProtocolDecl *rhsProto = *J;
4559 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4560 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4561 match = true;
4562 break;
4563 }
4564 }
4565 if (!match)
4566 return false;
4567 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004568
4569 // Static class's protocols, or its super class or category protocols
4570 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4571 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4572 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4573 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4574 // This is rather dubious but matches gcc's behavior. If lhs has
4575 // no type qualifier and its class has no static protocol(s)
4576 // assume that it is mismatch.
4577 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4578 return false;
4579 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4580 LHSInheritedProtocols.begin(),
4581 E = LHSInheritedProtocols.end(); I != E; ++I) {
4582 bool match = false;
4583 ObjCProtocolDecl *lhsProto = (*I);
4584 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4585 E = rhsQID->qual_end(); J != E; ++J) {
4586 ObjCProtocolDecl *rhsProto = *J;
4587 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4588 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4589 match = true;
4590 break;
4591 }
4592 }
4593 if (!match)
4594 return false;
4595 }
4596 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004597 return true;
4598 }
4599 return false;
4600}
4601
Eli Friedman47f77112008-08-22 00:56:42 +00004602/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004603/// compatible for assignment from RHS to LHS. This handles validation of any
4604/// protocol qualifiers on the LHS or RHS.
4605///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004606bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4607 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004608 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4609 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4610
Steve Naroff1329fa02009-07-15 18:40:39 +00004611 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004612 if (LHS->isObjCUnqualifiedIdOrClass() ||
4613 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004614 return true;
4615
John McCall8b07ec22010-05-15 11:32:37 +00004616 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004617 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4618 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004619 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004620
4621 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4622 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4623 QualType(RHSOPT,0));
4624
John McCall8b07ec22010-05-15 11:32:37 +00004625 // If we have 2 user-defined types, fall into that path.
4626 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004627 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004628
Steve Naroff8e6aee52009-07-23 01:01:38 +00004629 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004630}
4631
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004632/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4633/// for providing type-safty for objective-c pointers used to pass/return
4634/// arguments in block literals. When passed as arguments, passing 'A*' where
4635/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4636/// not OK. For the return type, the opposite is not OK.
4637bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4638 const ObjCObjectPointerType *LHSOPT,
4639 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004640 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004641 return true;
4642
4643 if (LHSOPT->isObjCBuiltinType()) {
4644 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4645 }
4646
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004647 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004648 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4649 QualType(RHSOPT,0),
4650 false);
4651
4652 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4653 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4654 if (LHS && RHS) { // We have 2 user-defined types.
4655 if (LHS != RHS) {
4656 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4657 return false;
4658 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4659 return true;
4660 }
4661 else
4662 return true;
4663 }
4664 return false;
4665}
4666
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004667/// getIntersectionOfProtocols - This routine finds the intersection of set
4668/// of protocols inherited from two distinct objective-c pointer objects.
4669/// It is used to build composite qualifier list of the composite type of
4670/// the conditional expression involving two objective-c pointer objects.
4671static
4672void getIntersectionOfProtocols(ASTContext &Context,
4673 const ObjCObjectPointerType *LHSOPT,
4674 const ObjCObjectPointerType *RHSOPT,
4675 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4676
John McCall8b07ec22010-05-15 11:32:37 +00004677 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4678 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4679 assert(LHS->getInterface() && "LHS must have an interface base");
4680 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004681
4682 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4683 unsigned LHSNumProtocols = LHS->getNumProtocols();
4684 if (LHSNumProtocols > 0)
4685 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4686 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004687 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004688 Context.CollectInheritedProtocols(LHS->getInterface(),
4689 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004690 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4691 LHSInheritedProtocols.end());
4692 }
4693
4694 unsigned RHSNumProtocols = RHS->getNumProtocols();
4695 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004696 ObjCProtocolDecl **RHSProtocols =
4697 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004698 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4699 if (InheritedProtocolSet.count(RHSProtocols[i]))
4700 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4701 }
4702 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004703 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004704 Context.CollectInheritedProtocols(RHS->getInterface(),
4705 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004706 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4707 RHSInheritedProtocols.begin(),
4708 E = RHSInheritedProtocols.end(); I != E; ++I)
4709 if (InheritedProtocolSet.count((*I)))
4710 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004711 }
4712}
4713
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004714/// areCommonBaseCompatible - Returns common base class of the two classes if
4715/// one found. Note that this is O'2 algorithm. But it will be called as the
4716/// last type comparison in a ?-exp of ObjC pointer types before a
4717/// warning is issued. So, its invokation is extremely rare.
4718QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004719 const ObjCObjectPointerType *Lptr,
4720 const ObjCObjectPointerType *Rptr) {
4721 const ObjCObjectType *LHS = Lptr->getObjectType();
4722 const ObjCObjectType *RHS = Rptr->getObjectType();
4723 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4724 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4725 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004726 return QualType();
4727
John McCall8b07ec22010-05-15 11:32:37 +00004728 while ((LDecl = LDecl->getSuperClass())) {
4729 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004730 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004731 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4732 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4733
4734 QualType Result = QualType(LHS, 0);
4735 if (!Protocols.empty())
4736 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4737 Result = getObjCObjectPointerType(Result);
4738 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004739 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004740 }
4741
4742 return QualType();
4743}
4744
John McCall8b07ec22010-05-15 11:32:37 +00004745bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4746 const ObjCObjectType *RHS) {
4747 assert(LHS->getInterface() && "LHS is not an interface type");
4748 assert(RHS->getInterface() && "RHS is not an interface type");
4749
Chris Lattner49af6a42008-04-07 06:51:04 +00004750 // Verify that the base decls are compatible: the RHS must be a subclass of
4751 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004752 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004753 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004754
Chris Lattner49af6a42008-04-07 06:51:04 +00004755 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4756 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004757 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004758 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004759
Chris Lattner49af6a42008-04-07 06:51:04 +00004760 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4761 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004762 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004763 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004764
John McCall8b07ec22010-05-15 11:32:37 +00004765 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4766 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004767 LHSPI != LHSPE; LHSPI++) {
4768 bool RHSImplementsProtocol = false;
4769
4770 // If the RHS doesn't implement the protocol on the left, the types
4771 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004772 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4773 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004774 RHSPI != RHSPE; RHSPI++) {
4775 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004776 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004777 break;
4778 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004779 }
4780 // FIXME: For better diagnostics, consider passing back the protocol name.
4781 if (!RHSImplementsProtocol)
4782 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004783 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004784 // The RHS implements all protocols listed on the LHS.
4785 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004786}
4787
Steve Naroffb7605152009-02-12 17:52:19 +00004788bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4789 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004790 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4791 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004792
Steve Naroff7cae42b2009-07-10 23:34:53 +00004793 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004794 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004795
4796 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4797 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004798}
4799
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004800bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4801 return canAssignObjCInterfaces(
4802 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4803 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4804}
4805
Mike Stump11289f42009-09-09 15:08:12 +00004806/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004807/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004808/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004809/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004810bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4811 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004812 if (getLangOptions().CPlusPlus)
4813 return hasSameType(LHS, RHS);
4814
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004815 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00004816}
4817
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004818bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4819 return !mergeTypes(LHS, RHS, true).isNull();
4820}
4821
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004822/// mergeTransparentUnionType - if T is a transparent union type and a member
4823/// of T is compatible with SubType, return the merged type, else return
4824/// QualType()
4825QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
4826 bool OfBlockPointer,
4827 bool Unqualified) {
4828 if (const RecordType *UT = T->getAsUnionType()) {
4829 RecordDecl *UD = UT->getDecl();
4830 if (UD->hasAttr<TransparentUnionAttr>()) {
4831 for (RecordDecl::field_iterator it = UD->field_begin(),
4832 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00004833 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004834 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
4835 if (!MT.isNull())
4836 return MT;
4837 }
4838 }
4839 }
4840
4841 return QualType();
4842}
4843
4844/// mergeFunctionArgumentTypes - merge two types which appear as function
4845/// argument types
4846QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
4847 bool OfBlockPointer,
4848 bool Unqualified) {
4849 // GNU extension: two types are compatible if they appear as a function
4850 // argument, one of the types is a transparent union type and the other
4851 // type is compatible with a union member
4852 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
4853 Unqualified);
4854 if (!lmerge.isNull())
4855 return lmerge;
4856
4857 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
4858 Unqualified);
4859 if (!rmerge.isNull())
4860 return rmerge;
4861
4862 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
4863}
4864
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004865QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004866 bool OfBlockPointer,
4867 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00004868 const FunctionType *lbase = lhs->getAs<FunctionType>();
4869 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004870 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4871 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004872 bool allLTypes = true;
4873 bool allRTypes = true;
4874
4875 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004876 QualType retType;
4877 if (OfBlockPointer)
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004878 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4879 Unqualified);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004880 else
John McCall8c6b56f2010-12-15 01:06:38 +00004881 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
4882 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004883 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004884
4885 if (Unqualified)
4886 retType = retType.getUnqualifiedType();
4887
4888 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4889 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4890 if (Unqualified) {
4891 LRetType = LRetType.getUnqualifiedType();
4892 RRetType = RRetType.getUnqualifiedType();
4893 }
4894
4895 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004896 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004897 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004898 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00004899
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004900 // FIXME: double check this
4901 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4902 // rbase->getRegParmAttr() != 0 &&
4903 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004904 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4905 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00004906
Douglas Gregor8c940862010-01-18 17:14:39 +00004907 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00004908 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00004909 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004910
John McCall8c6b56f2010-12-15 01:06:38 +00004911 // Regparm is part of the calling convention.
4912 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
4913 return QualType();
4914
4915 // It's noreturn if either type is.
4916 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
4917 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4918 if (NoReturn != lbaseInfo.getNoReturn())
4919 allLTypes = false;
4920 if (NoReturn != rbaseInfo.getNoReturn())
4921 allRTypes = false;
4922
4923 FunctionType::ExtInfo einfo(NoReturn,
4924 lbaseInfo.getRegParm(),
4925 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00004926
Eli Friedman47f77112008-08-22 00:56:42 +00004927 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004928 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4929 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004930 unsigned lproto_nargs = lproto->getNumArgs();
4931 unsigned rproto_nargs = rproto->getNumArgs();
4932
4933 // Compatible functions must have the same number of arguments
4934 if (lproto_nargs != rproto_nargs)
4935 return QualType();
4936
4937 // Variadic and non-variadic functions aren't compatible
4938 if (lproto->isVariadic() != rproto->isVariadic())
4939 return QualType();
4940
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004941 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4942 return QualType();
4943
Eli Friedman47f77112008-08-22 00:56:42 +00004944 // Check argument compatibility
4945 llvm::SmallVector<QualType, 10> types;
4946 for (unsigned i = 0; i < lproto_nargs; i++) {
4947 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4948 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004949 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
4950 OfBlockPointer,
4951 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004952 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004953
4954 if (Unqualified)
4955 argtype = argtype.getUnqualifiedType();
4956
Eli Friedman47f77112008-08-22 00:56:42 +00004957 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004958 if (Unqualified) {
4959 largtype = largtype.getUnqualifiedType();
4960 rargtype = rargtype.getUnqualifiedType();
4961 }
4962
Chris Lattner465fa322008-10-05 17:34:18 +00004963 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4964 allLTypes = false;
4965 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4966 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004967 }
4968 if (allLTypes) return lhs;
4969 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00004970
4971 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
4972 EPI.ExtInfo = einfo;
4973 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00004974 }
4975
4976 if (lproto) allRTypes = false;
4977 if (rproto) allLTypes = false;
4978
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004979 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004980 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004981 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004982 if (proto->isVariadic()) return QualType();
4983 // Check that the types are compatible with the types that
4984 // would result from default argument promotions (C99 6.7.5.3p15).
4985 // The only types actually affected are promotable integer
4986 // types and floats, which would be passed as a different
4987 // type depending on whether the prototype is visible.
4988 unsigned proto_nargs = proto->getNumArgs();
4989 for (unsigned i = 0; i < proto_nargs; ++i) {
4990 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004991
4992 // Look at the promotion type of enum types, since that is the type used
4993 // to pass enum values.
4994 if (const EnumType *Enum = argTy->getAs<EnumType>())
4995 argTy = Enum->getDecl()->getPromotionType();
4996
Eli Friedman47f77112008-08-22 00:56:42 +00004997 if (argTy->isPromotableIntegerType() ||
4998 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4999 return QualType();
5000 }
5001
5002 if (allLTypes) return lhs;
5003 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005004
5005 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5006 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005007 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005008 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005009 }
5010
5011 if (allLTypes) return lhs;
5012 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005013 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005014}
5015
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005016QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005017 bool OfBlockPointer,
5018 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005019 // C++ [expr]: If an expression initially has the type "reference to T", the
5020 // type is adjusted to "T" prior to any further analysis, the expression
5021 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005022 // expression is an lvalue unless the reference is an rvalue reference and
5023 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005024 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5025 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005026
5027 if (Unqualified) {
5028 LHS = LHS.getUnqualifiedType();
5029 RHS = RHS.getUnqualifiedType();
5030 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005031
Eli Friedman47f77112008-08-22 00:56:42 +00005032 QualType LHSCan = getCanonicalType(LHS),
5033 RHSCan = getCanonicalType(RHS);
5034
5035 // If two types are identical, they are compatible.
5036 if (LHSCan == RHSCan)
5037 return LHS;
5038
John McCall8ccfcb52009-09-24 19:53:00 +00005039 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005040 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5041 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005042 if (LQuals != RQuals) {
5043 // If any of these qualifiers are different, we have a type
5044 // mismatch.
5045 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5046 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5047 return QualType();
5048
5049 // Exactly one GC qualifier difference is allowed: __strong is
5050 // okay if the other type has no GC qualifier but is an Objective
5051 // C object pointer (i.e. implicitly strong by default). We fix
5052 // this by pretending that the unqualified type was actually
5053 // qualified __strong.
5054 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5055 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5056 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5057
5058 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5059 return QualType();
5060
5061 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5062 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5063 }
5064 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5065 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5066 }
Eli Friedman47f77112008-08-22 00:56:42 +00005067 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005068 }
5069
5070 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005071
Eli Friedmandcca6332009-06-01 01:22:52 +00005072 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5073 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005074
Chris Lattnerfd652912008-01-14 05:45:46 +00005075 // We want to consider the two function types to be the same for these
5076 // comparisons, just force one to the other.
5077 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5078 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005079
5080 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005081 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5082 LHSClass = Type::ConstantArray;
5083 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5084 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005085
John McCall8b07ec22010-05-15 11:32:37 +00005086 // ObjCInterfaces are just specialized ObjCObjects.
5087 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5088 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5089
Nate Begemance4d7fc2008-04-18 23:10:10 +00005090 // Canonicalize ExtVector -> Vector.
5091 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5092 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005093
Chris Lattner95554662008-04-07 05:43:21 +00005094 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005095 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005096 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005097 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005098 // Compatibility is based on the underlying type, not the promotion
5099 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005100 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005101 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5102 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005103 }
John McCall9dd450b2009-09-21 23:43:11 +00005104 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005105 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5106 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005107 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005108
Eli Friedman47f77112008-08-22 00:56:42 +00005109 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005110 }
Eli Friedman47f77112008-08-22 00:56:42 +00005111
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005112 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005113 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005114#define TYPE(Class, Base)
5115#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005116#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005117#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5118#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5119#include "clang/AST/TypeNodes.def"
5120 assert(false && "Non-canonical and dependent types shouldn't get here");
5121 return QualType();
5122
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005123 case Type::LValueReference:
5124 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005125 case Type::MemberPointer:
5126 assert(false && "C++ should never be in mergeTypes");
5127 return QualType();
5128
John McCall8b07ec22010-05-15 11:32:37 +00005129 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005130 case Type::IncompleteArray:
5131 case Type::VariableArray:
5132 case Type::FunctionProto:
5133 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005134 assert(false && "Types are eliminated above");
5135 return QualType();
5136
Chris Lattnerfd652912008-01-14 05:45:46 +00005137 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005138 {
5139 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005140 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5141 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005142 if (Unqualified) {
5143 LHSPointee = LHSPointee.getUnqualifiedType();
5144 RHSPointee = RHSPointee.getUnqualifiedType();
5145 }
5146 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5147 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005148 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005149 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005150 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005151 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005152 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005153 return getPointerType(ResultType);
5154 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005155 case Type::BlockPointer:
5156 {
5157 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005158 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5159 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005160 if (Unqualified) {
5161 LHSPointee = LHSPointee.getUnqualifiedType();
5162 RHSPointee = RHSPointee.getUnqualifiedType();
5163 }
5164 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5165 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005166 if (ResultType.isNull()) return QualType();
5167 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5168 return LHS;
5169 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5170 return RHS;
5171 return getBlockPointerType(ResultType);
5172 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005173 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005174 {
5175 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5176 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5177 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5178 return QualType();
5179
5180 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5181 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005182 if (Unqualified) {
5183 LHSElem = LHSElem.getUnqualifiedType();
5184 RHSElem = RHSElem.getUnqualifiedType();
5185 }
5186
5187 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005188 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005189 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5190 return LHS;
5191 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5192 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005193 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5194 ArrayType::ArraySizeModifier(), 0);
5195 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5196 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005197 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5198 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005199 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5200 return LHS;
5201 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5202 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005203 if (LVAT) {
5204 // FIXME: This isn't correct! But tricky to implement because
5205 // the array's size has to be the size of LHS, but the type
5206 // has to be different.
5207 return LHS;
5208 }
5209 if (RVAT) {
5210 // FIXME: This isn't correct! But tricky to implement because
5211 // the array's size has to be the size of RHS, but the type
5212 // has to be different.
5213 return RHS;
5214 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005215 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5216 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005217 return getIncompleteArrayType(ResultType,
5218 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005219 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005220 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005221 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005222 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005223 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005224 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005225 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005226 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005227 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005228 case Type::Complex:
5229 // Distinct complex types are incompatible.
5230 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005231 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005232 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005233 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5234 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005235 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005236 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005237 case Type::ObjCObject: {
5238 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005239 // FIXME: This should be type compatibility, e.g. whether
5240 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005241 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5242 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5243 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005244 return LHS;
5245
Eli Friedman47f77112008-08-22 00:56:42 +00005246 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005247 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005248 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005249 if (OfBlockPointer) {
5250 if (canAssignObjCInterfacesInBlockPointer(
5251 LHS->getAs<ObjCObjectPointerType>(),
5252 RHS->getAs<ObjCObjectPointerType>()))
5253 return LHS;
5254 return QualType();
5255 }
John McCall9dd450b2009-09-21 23:43:11 +00005256 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5257 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005258 return LHS;
5259
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005260 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005261 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005262 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005263
5264 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005265}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005266
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005267/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5268/// 'RHS' attributes and returns the merged version; including for function
5269/// return types.
5270QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5271 QualType LHSCan = getCanonicalType(LHS),
5272 RHSCan = getCanonicalType(RHS);
5273 // If two types are identical, they are compatible.
5274 if (LHSCan == RHSCan)
5275 return LHS;
5276 if (RHSCan->isFunctionType()) {
5277 if (!LHSCan->isFunctionType())
5278 return QualType();
5279 QualType OldReturnType =
5280 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5281 QualType NewReturnType =
5282 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5283 QualType ResReturnType =
5284 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5285 if (ResReturnType.isNull())
5286 return QualType();
5287 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5288 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5289 // In either case, use OldReturnType to build the new function type.
5290 const FunctionType *F = LHS->getAs<FunctionType>();
5291 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005292 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5293 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005294 QualType ResultType
5295 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005296 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005297 return ResultType;
5298 }
5299 }
5300 return QualType();
5301 }
5302
5303 // If the qualifiers are different, the types can still be merged.
5304 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5305 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5306 if (LQuals != RQuals) {
5307 // If any of these qualifiers are different, we have a type mismatch.
5308 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5309 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5310 return QualType();
5311
5312 // Exactly one GC qualifier difference is allowed: __strong is
5313 // okay if the other type has no GC qualifier but is an Objective
5314 // C object pointer (i.e. implicitly strong by default). We fix
5315 // this by pretending that the unqualified type was actually
5316 // qualified __strong.
5317 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5318 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5319 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5320
5321 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5322 return QualType();
5323
5324 if (GC_L == Qualifiers::Strong)
5325 return LHS;
5326 if (GC_R == Qualifiers::Strong)
5327 return RHS;
5328 return QualType();
5329 }
5330
5331 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5332 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5333 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5334 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5335 if (ResQT == LHSBaseQT)
5336 return LHS;
5337 if (ResQT == RHSBaseQT)
5338 return RHS;
5339 }
5340 return QualType();
5341}
5342
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005343//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005344// Integer Predicates
5345//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005346
Jay Foad39c79802011-01-12 09:06:06 +00005347unsigned ASTContext::getIntWidth(QualType T) const {
John McCall56774992009-12-09 09:09:27 +00005348 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005349 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005350 if (T->isBooleanType())
5351 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005352 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005353 return (unsigned)getTypeSize(T);
5354}
5355
5356QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005357 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005358
5359 // Turn <4 x signed int> -> <4 x unsigned int>
5360 if (const VectorType *VTy = T->getAs<VectorType>())
5361 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005362 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005363
5364 // For enums, we return the unsigned version of the base type.
5365 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005366 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005367
5368 const BuiltinType *BTy = T->getAs<BuiltinType>();
5369 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005370 switch (BTy->getKind()) {
5371 case BuiltinType::Char_S:
5372 case BuiltinType::SChar:
5373 return UnsignedCharTy;
5374 case BuiltinType::Short:
5375 return UnsignedShortTy;
5376 case BuiltinType::Int:
5377 return UnsignedIntTy;
5378 case BuiltinType::Long:
5379 return UnsignedLongTy;
5380 case BuiltinType::LongLong:
5381 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005382 case BuiltinType::Int128:
5383 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005384 default:
5385 assert(0 && "Unexpected signed integer type");
5386 return QualType();
5387 }
5388}
5389
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005390ExternalASTSource::~ExternalASTSource() { }
5391
5392void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00005393
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005394ASTMutationListener::~ASTMutationListener() { }
5395
Chris Lattnerecd79c62009-06-14 00:45:47 +00005396
5397//===----------------------------------------------------------------------===//
5398// Builtin Type Computation
5399//===----------------------------------------------------------------------===//
5400
5401/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005402/// pointer over the consumed characters. This returns the resultant type. If
5403/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5404/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5405/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005406///
5407/// RequiresICE is filled in on return to indicate whether the value is required
5408/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005409static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005410 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005411 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005412 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005413 // Modifiers.
5414 int HowLong = 0;
5415 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005416 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005417
Chris Lattnerdc226c22010-10-01 22:42:38 +00005418 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005419 bool Done = false;
5420 while (!Done) {
5421 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005422 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005423 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005424 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005425 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005426 case 'S':
5427 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5428 assert(!Signed && "Can't use 'S' modifier multiple times!");
5429 Signed = true;
5430 break;
5431 case 'U':
5432 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5433 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5434 Unsigned = true;
5435 break;
5436 case 'L':
5437 assert(HowLong <= 2 && "Can't have LLLL modifier");
5438 ++HowLong;
5439 break;
5440 }
5441 }
5442
5443 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005444
Chris Lattnerecd79c62009-06-14 00:45:47 +00005445 // Read the base type.
5446 switch (*Str++) {
5447 default: assert(0 && "Unknown builtin type letter!");
5448 case 'v':
5449 assert(HowLong == 0 && !Signed && !Unsigned &&
5450 "Bad modifiers used with 'v'!");
5451 Type = Context.VoidTy;
5452 break;
5453 case 'f':
5454 assert(HowLong == 0 && !Signed && !Unsigned &&
5455 "Bad modifiers used with 'f'!");
5456 Type = Context.FloatTy;
5457 break;
5458 case 'd':
5459 assert(HowLong < 2 && !Signed && !Unsigned &&
5460 "Bad modifiers used with 'd'!");
5461 if (HowLong)
5462 Type = Context.LongDoubleTy;
5463 else
5464 Type = Context.DoubleTy;
5465 break;
5466 case 's':
5467 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5468 if (Unsigned)
5469 Type = Context.UnsignedShortTy;
5470 else
5471 Type = Context.ShortTy;
5472 break;
5473 case 'i':
5474 if (HowLong == 3)
5475 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5476 else if (HowLong == 2)
5477 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5478 else if (HowLong == 1)
5479 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5480 else
5481 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5482 break;
5483 case 'c':
5484 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5485 if (Signed)
5486 Type = Context.SignedCharTy;
5487 else if (Unsigned)
5488 Type = Context.UnsignedCharTy;
5489 else
5490 Type = Context.CharTy;
5491 break;
5492 case 'b': // boolean
5493 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5494 Type = Context.BoolTy;
5495 break;
5496 case 'z': // size_t.
5497 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5498 Type = Context.getSizeType();
5499 break;
5500 case 'F':
5501 Type = Context.getCFConstantStringType();
5502 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005503 case 'G':
5504 Type = Context.getObjCIdType();
5505 break;
5506 case 'H':
5507 Type = Context.getObjCSelType();
5508 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005509 case 'a':
5510 Type = Context.getBuiltinVaListType();
5511 assert(!Type.isNull() && "builtin va list type not initialized!");
5512 break;
5513 case 'A':
5514 // This is a "reference" to a va_list; however, what exactly
5515 // this means depends on how va_list is defined. There are two
5516 // different kinds of va_list: ones passed by value, and ones
5517 // passed by reference. An example of a by-value va_list is
5518 // x86, where va_list is a char*. An example of by-ref va_list
5519 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5520 // we want this argument to be a char*&; for x86-64, we want
5521 // it to be a __va_list_tag*.
5522 Type = Context.getBuiltinVaListType();
5523 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005524 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005525 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005526 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005527 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005528 break;
5529 case 'V': {
5530 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005531 unsigned NumElements = strtoul(Str, &End, 10);
5532 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005533 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005534
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005535 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5536 RequiresICE, false);
5537 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005538
5539 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005540 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005541 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005542 break;
5543 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005544 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005545 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5546 false);
5547 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005548 Type = Context.getComplexType(ElementType);
5549 break;
5550 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005551 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005552 Type = Context.getFILEType();
5553 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005554 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005555 return QualType();
5556 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005557 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005558 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005559 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005560 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005561 else
5562 Type = Context.getjmp_bufType();
5563
Mike Stump2adb4da2009-07-28 23:47:15 +00005564 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005565 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005566 return QualType();
5567 }
5568 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005569 }
Mike Stump11289f42009-09-09 15:08:12 +00005570
Chris Lattnerdc226c22010-10-01 22:42:38 +00005571 // If there are modifiers and if we're allowed to parse them, go for it.
5572 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005573 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005574 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005575 default: Done = true; --Str; break;
5576 case '*':
5577 case '&': {
5578 // Both pointers and references can have their pointee types
5579 // qualified with an address space.
5580 char *End;
5581 unsigned AddrSpace = strtoul(Str, &End, 10);
5582 if (End != Str && AddrSpace != 0) {
5583 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5584 Str = End;
5585 }
5586 if (c == '*')
5587 Type = Context.getPointerType(Type);
5588 else
5589 Type = Context.getLValueReferenceType(Type);
5590 break;
5591 }
5592 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5593 case 'C':
5594 Type = Type.withConst();
5595 break;
5596 case 'D':
5597 Type = Context.getVolatileType(Type);
5598 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005599 }
5600 }
Chris Lattner84733392010-10-01 07:13:18 +00005601
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005602 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005603 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005604
Chris Lattnerecd79c62009-06-14 00:45:47 +00005605 return Type;
5606}
5607
5608/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005609QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005610 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005611 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005612 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005613
Chris Lattnerecd79c62009-06-14 00:45:47 +00005614 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005615
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005616 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005617 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005618 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5619 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005620 if (Error != GE_None)
5621 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005622
5623 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5624
Chris Lattnerecd79c62009-06-14 00:45:47 +00005625 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005626 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005627 if (Error != GE_None)
5628 return QualType();
5629
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005630 // If this argument is required to be an IntegerConstantExpression and the
5631 // caller cares, fill in the bitmask we return.
5632 if (RequiresICE && IntegerConstantArgs)
5633 *IntegerConstantArgs |= 1 << ArgTypes.size();
5634
Chris Lattnerecd79c62009-06-14 00:45:47 +00005635 // Do array -> pointer decay. The builtin should use the decayed type.
5636 if (Ty->isArrayType())
5637 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005638
Chris Lattnerecd79c62009-06-14 00:45:47 +00005639 ArgTypes.push_back(Ty);
5640 }
5641
5642 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5643 "'.' should only occur at end of builtin type list!");
5644
John McCall991eb4b2010-12-21 00:44:39 +00005645 FunctionType::ExtInfo EI;
5646 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5647
5648 bool Variadic = (TypeStr[0] == '.');
5649
5650 // We really shouldn't be making a no-proto type here, especially in C++.
5651 if (ArgTypes.empty() && Variadic)
5652 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005653
John McCalldb40c7f2010-12-14 08:05:40 +00005654 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005655 EPI.ExtInfo = EI;
5656 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00005657
5658 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005659}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005660
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005661GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5662 GVALinkage External = GVA_StrongExternal;
5663
5664 Linkage L = FD->getLinkage();
5665 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5666 FD->getType()->getLinkage() == UniqueExternalLinkage)
5667 L = UniqueExternalLinkage;
5668
5669 switch (L) {
5670 case NoLinkage:
5671 case InternalLinkage:
5672 case UniqueExternalLinkage:
5673 return GVA_Internal;
5674
5675 case ExternalLinkage:
5676 switch (FD->getTemplateSpecializationKind()) {
5677 case TSK_Undeclared:
5678 case TSK_ExplicitSpecialization:
5679 External = GVA_StrongExternal;
5680 break;
5681
5682 case TSK_ExplicitInstantiationDefinition:
5683 return GVA_ExplicitTemplateInstantiation;
5684
5685 case TSK_ExplicitInstantiationDeclaration:
5686 case TSK_ImplicitInstantiation:
5687 External = GVA_TemplateInstantiation;
5688 break;
5689 }
5690 }
5691
5692 if (!FD->isInlined())
5693 return External;
5694
5695 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5696 // GNU or C99 inline semantics. Determine whether this symbol should be
5697 // externally visible.
5698 if (FD->isInlineDefinitionExternallyVisible())
5699 return External;
5700
5701 // C99 inline semantics, where the symbol is not externally visible.
5702 return GVA_C99Inline;
5703 }
5704
5705 // C++0x [temp.explicit]p9:
5706 // [ Note: The intent is that an inline function that is the subject of
5707 // an explicit instantiation declaration will still be implicitly
5708 // instantiated when used so that the body can be considered for
5709 // inlining, but that no out-of-line copy of the inline function would be
5710 // generated in the translation unit. -- end note ]
5711 if (FD->getTemplateSpecializationKind()
5712 == TSK_ExplicitInstantiationDeclaration)
5713 return GVA_C99Inline;
5714
5715 return GVA_CXXInline;
5716}
5717
5718GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5719 // If this is a static data member, compute the kind of template
5720 // specialization. Otherwise, this variable is not part of a
5721 // template.
5722 TemplateSpecializationKind TSK = TSK_Undeclared;
5723 if (VD->isStaticDataMember())
5724 TSK = VD->getTemplateSpecializationKind();
5725
5726 Linkage L = VD->getLinkage();
5727 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5728 VD->getType()->getLinkage() == UniqueExternalLinkage)
5729 L = UniqueExternalLinkage;
5730
5731 switch (L) {
5732 case NoLinkage:
5733 case InternalLinkage:
5734 case UniqueExternalLinkage:
5735 return GVA_Internal;
5736
5737 case ExternalLinkage:
5738 switch (TSK) {
5739 case TSK_Undeclared:
5740 case TSK_ExplicitSpecialization:
5741 return GVA_StrongExternal;
5742
5743 case TSK_ExplicitInstantiationDeclaration:
5744 llvm_unreachable("Variable should not be instantiated");
5745 // Fall through to treat this like any other instantiation.
5746
5747 case TSK_ExplicitInstantiationDefinition:
5748 return GVA_ExplicitTemplateInstantiation;
5749
5750 case TSK_ImplicitInstantiation:
5751 return GVA_TemplateInstantiation;
5752 }
5753 }
5754
5755 return GVA_StrongExternal;
5756}
5757
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005758bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005759 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5760 if (!VD->isFileVarDecl())
5761 return false;
5762 } else if (!isa<FunctionDecl>(D))
5763 return false;
5764
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005765 // Weak references don't produce any output by themselves.
5766 if (D->hasAttr<WeakRefAttr>())
5767 return false;
5768
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005769 // Aliases and used decls are required.
5770 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5771 return true;
5772
5773 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5774 // Forward declarations aren't required.
5775 if (!FD->isThisDeclarationADefinition())
5776 return false;
5777
5778 // Constructors and destructors are required.
5779 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5780 return true;
5781
5782 // The key function for a class is required.
5783 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5784 const CXXRecordDecl *RD = MD->getParent();
5785 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5786 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5787 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5788 return true;
5789 }
5790 }
5791
5792 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5793
5794 // static, static inline, always_inline, and extern inline functions can
5795 // always be deferred. Normal inline functions can be deferred in C99/C++.
5796 // Implicit template instantiations can also be deferred in C++.
5797 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5798 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5799 return false;
5800 return true;
5801 }
5802
5803 const VarDecl *VD = cast<VarDecl>(D);
5804 assert(VD->isFileVarDecl() && "Expected file scoped var");
5805
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005806 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5807 return false;
5808
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005809 // Structs that have non-trivial constructors or destructors are required.
5810
5811 // FIXME: Handle references.
5812 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5813 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00005814 if (RD->hasDefinition() &&
5815 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005816 return true;
5817 }
5818 }
5819
5820 GVALinkage L = GetGVALinkageForVariable(VD);
5821 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5822 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5823 return false;
5824 }
5825
5826 return true;
5827}
Charles Davis53c59df2010-08-16 03:33:14 +00005828
Charles Davis99202b32010-11-09 18:04:24 +00005829CallingConv ASTContext::getDefaultMethodCallConv() {
5830 // Pass through to the C++ ABI object
5831 return ABI->getDefaultMethodCallConv();
5832}
5833
Jay Foad39c79802011-01-12 09:06:06 +00005834bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00005835 // Pass through to the C++ ABI object
5836 return ABI->isNearlyEmpty(RD);
5837}
5838
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00005839MangleContext *ASTContext::createMangleContext() {
5840 switch (Target.getCXXABI()) {
5841 case CXXABI_ARM:
5842 case CXXABI_Itanium:
5843 return createItaniumMangleContext(*this, getDiagnostics());
5844 case CXXABI_Microsoft:
5845 return createMicrosoftMangleContext(*this, getDiagnostics());
5846 }
5847 assert(0 && "Unsupported ABI");
5848 return 0;
5849}
5850
Charles Davis53c59df2010-08-16 03:33:14 +00005851CXXABI::~CXXABI() {}