blob: dc484c88061680357a6cce5800b02fe90ebc2d54 [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 Dyckcc56c542011-01-15 18:38:59 +0000595 return toCharUnitsFromBits(Align);
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);
Ken Dyckcc56c542011-01-15 18:38:59 +0000601 return std::make_pair(toCharUnitsFromBits(Info.first),
602 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000603}
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 Dyckcc56c542011-01-15 18:38:59 +0000865/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
866CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
867 return CharUnits::fromQuantity(BitSize / getCharWidth());
868}
869
Ken Dyck8c89d592009-12-22 14:23:30 +0000870/// getTypeSizeInChars - Return the size of the specified type, in characters.
871/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000872CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000873 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000874}
Jay Foad39c79802011-01-12 09:06:06 +0000875CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000876 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000877}
878
Ken Dycka6046ab2010-01-26 17:25:18 +0000879/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000880/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000881CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000882 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000883}
Jay Foad39c79802011-01-12 09:06:06 +0000884CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000885 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000886}
887
Chris Lattnera3402cd2009-01-27 18:08:34 +0000888/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
889/// type for the current target in bits. This can be different than the ABI
890/// alignment in cases where it is beneficial for performance to overalign
891/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +0000892unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +0000893 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000894
895 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000896 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000897 T = CT->getElementType().getTypePtr();
898 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
899 T->isSpecificBuiltinType(BuiltinType::LongLong))
900 return std::max(ABIAlign, (unsigned)getTypeSize(T));
901
Chris Lattnera3402cd2009-01-27 18:08:34 +0000902 return ABIAlign;
903}
904
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000905/// ShallowCollectObjCIvars -
906/// Collect all ivars, including those synthesized, in the current class.
907///
908void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +0000909 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000910 // FIXME. This need be removed but there are two many places which
911 // assume const-ness of ObjCInterfaceDecl
912 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
913 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
914 Iv= Iv->getNextIvar())
915 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000916}
917
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000918/// DeepCollectObjCIvars -
919/// This routine first collects all declared, but not synthesized, ivars in
920/// super class and then collects all ivars, including those synthesized for
921/// current class. This routine is used for implementation of current class
922/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000923///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000924void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
925 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +0000926 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000927 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
928 DeepCollectObjCIvars(SuperClass, false, Ivars);
929 if (!leafClass) {
930 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
931 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000932 Ivars.push_back(*I);
933 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000934 else
935 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000936}
937
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000938/// CollectInheritedProtocols - Collect all protocols in current class and
939/// those inherited by it.
940void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000941 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000942 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000943 // We can use protocol_iterator here instead of
944 // all_referenced_protocol_iterator since we are walking all categories.
945 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
946 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000947 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000948 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000949 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000950 PE = Proto->protocol_end(); P != PE; ++P) {
951 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000952 CollectInheritedProtocols(*P, Protocols);
953 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000954 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000955
956 // Categories of this Interface.
957 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
958 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
959 CollectInheritedProtocols(CDeclChain, Protocols);
960 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
961 while (SD) {
962 CollectInheritedProtocols(SD, Protocols);
963 SD = SD->getSuperClass();
964 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000965 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000966 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000967 PE = OC->protocol_end(); P != PE; ++P) {
968 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000969 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000970 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
971 PE = Proto->protocol_end(); P != PE; ++P)
972 CollectInheritedProtocols(*P, Protocols);
973 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000974 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000975 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
976 PE = OP->protocol_end(); P != PE; ++P) {
977 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000978 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000979 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
980 PE = Proto->protocol_end(); P != PE; ++P)
981 CollectInheritedProtocols(*P, Protocols);
982 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000983 }
984}
985
Jay Foad39c79802011-01-12 09:06:06 +0000986unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000987 unsigned count = 0;
988 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000989 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
990 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000991 count += CDecl->ivar_size();
992
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000993 // Count ivar defined in this class's implementation. This
994 // includes synthesized ivars.
995 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000996 count += ImplDecl->ivar_size();
997
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000998 return count;
999}
1000
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001001/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1002ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1003 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1004 I = ObjCImpls.find(D);
1005 if (I != ObjCImpls.end())
1006 return cast<ObjCImplementationDecl>(I->second);
1007 return 0;
1008}
1009/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1010ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1011 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1012 I = ObjCImpls.find(D);
1013 if (I != ObjCImpls.end())
1014 return cast<ObjCCategoryImplDecl>(I->second);
1015 return 0;
1016}
1017
1018/// \brief Set the implementation of ObjCInterfaceDecl.
1019void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1020 ObjCImplementationDecl *ImplD) {
1021 assert(IFaceD && ImplD && "Passed null params");
1022 ObjCImpls[IFaceD] = ImplD;
1023}
1024/// \brief Set the implementation of ObjCCategoryDecl.
1025void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1026 ObjCCategoryImplDecl *ImplD) {
1027 assert(CatD && ImplD && "Passed null params");
1028 ObjCImpls[CatD] = ImplD;
1029}
1030
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001031/// \brief Get the copy initialization expression of VarDecl,or NULL if
1032/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001033Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001034 assert(VD && "Passed null params");
1035 assert(VD->hasAttr<BlocksAttr>() &&
1036 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001037 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001038 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001039 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1040}
1041
1042/// \brief Set the copy inialization expression of a block var decl.
1043void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1044 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001045 assert(VD->hasAttr<BlocksAttr>() &&
1046 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001047 BlockVarCopyInits[VD] = Init;
1048}
1049
John McCallbcd03502009-12-07 02:54:59 +00001050/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001051///
John McCallbcd03502009-12-07 02:54:59 +00001052/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001053/// the TypeLoc wrappers.
1054///
1055/// \param T the type that will be the basis for type source info. This type
1056/// should refer to how the declarator was written in source code, not to
1057/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001058TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001059 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001060 if (!DataSize)
1061 DataSize = TypeLoc::getFullDataSizeForType(T);
1062 else
1063 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001064 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001065
John McCallbcd03502009-12-07 02:54:59 +00001066 TypeSourceInfo *TInfo =
1067 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1068 new (TInfo) TypeSourceInfo(T);
1069 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001070}
1071
John McCallbcd03502009-12-07 02:54:59 +00001072TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001073 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001074 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001075 DI->getTypeLoc().initialize(L);
1076 return DI;
1077}
1078
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001079const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001080ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001081 return getObjCLayout(D, 0);
1082}
1083
1084const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001085ASTContext::getASTObjCImplementationLayout(
1086 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001087 return getObjCLayout(D->getClassInterface(), D);
1088}
1089
Chris Lattner983a8bb2007-07-13 22:13:22 +00001090//===----------------------------------------------------------------------===//
1091// Type creation/memoization methods
1092//===----------------------------------------------------------------------===//
1093
Jay Foad39c79802011-01-12 09:06:06 +00001094QualType
1095ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) const {
John McCall8ccfcb52009-09-24 19:53:00 +00001096 unsigned Fast = Quals.getFastQualifiers();
1097 Quals.removeFastQualifiers();
1098
1099 // Check if we've already instantiated this type.
1100 llvm::FoldingSetNodeID ID;
1101 ExtQuals::Profile(ID, TypeNode, Quals);
1102 void *InsertPos = 0;
1103 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1104 assert(EQ->getQualifiers() == Quals);
1105 QualType T = QualType(EQ, Fast);
1106 return T;
1107 }
1108
John McCall717d9b02010-12-10 11:01:00 +00001109 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001110 ExtQualNodes.InsertNode(New, InsertPos);
1111 QualType T = QualType(New, Fast);
1112 return T;
1113}
1114
Jay Foad39c79802011-01-12 09:06:06 +00001115QualType
1116ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001117 QualType CanT = getCanonicalType(T);
1118 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001119 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001120
John McCall8ccfcb52009-09-24 19:53:00 +00001121 // If we are composing extended qualifiers together, merge together
1122 // into one ExtQuals node.
1123 QualifierCollector Quals;
1124 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001125
John McCall8ccfcb52009-09-24 19:53:00 +00001126 // If this type already has an address space specified, it cannot get
1127 // another one.
1128 assert(!Quals.hasAddressSpace() &&
1129 "Type cannot be in multiple addr spaces!");
1130 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001131
John McCall8ccfcb52009-09-24 19:53:00 +00001132 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001133}
1134
Chris Lattnerd60183d2009-02-18 22:53:11 +00001135QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001136 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001137 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001138 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001139 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001140
John McCall53fa7142010-12-24 02:08:15 +00001141 if (const PointerType *ptr = T->getAs<PointerType>()) {
1142 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001143 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001144 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1145 return getPointerType(ResultType);
1146 }
1147 }
Mike Stump11289f42009-09-09 15:08:12 +00001148
John McCall8ccfcb52009-09-24 19:53:00 +00001149 // If we are composing extended qualifiers together, merge together
1150 // into one ExtQuals node.
1151 QualifierCollector Quals;
1152 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001153
John McCall8ccfcb52009-09-24 19:53:00 +00001154 // If this type already has an ObjCGC specified, it cannot get
1155 // another one.
1156 assert(!Quals.hasObjCGCAttr() &&
1157 "Type cannot have multiple ObjCGCs!");
1158 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001159
John McCall8ccfcb52009-09-24 19:53:00 +00001160 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001161}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001162
John McCall4f5019e2010-12-19 02:44:49 +00001163const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1164 FunctionType::ExtInfo Info) {
1165 if (T->getExtInfo() == Info)
1166 return T;
1167
1168 QualType Result;
1169 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1170 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1171 } else {
1172 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1173 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1174 EPI.ExtInfo = Info;
1175 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1176 FPT->getNumArgs(), EPI);
1177 }
1178
1179 return cast<FunctionType>(Result.getTypePtr());
1180}
1181
Chris Lattnerc6395932007-06-22 20:56:16 +00001182/// getComplexType - Return the uniqued reference to the type for a complex
1183/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001184QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001185 // Unique pointers, to guarantee there is only one pointer of a particular
1186 // structure.
1187 llvm::FoldingSetNodeID ID;
1188 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001189
Chris Lattnerc6395932007-06-22 20:56:16 +00001190 void *InsertPos = 0;
1191 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1192 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001193
Chris Lattnerc6395932007-06-22 20:56:16 +00001194 // If the pointee type isn't canonical, this won't be a canonical type either,
1195 // so fill in the canonical type field.
1196 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001197 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001198 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001199
Chris Lattnerc6395932007-06-22 20:56:16 +00001200 // Get the new insert position for the node we care about.
1201 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001202 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001203 }
John McCall90d1c2d2009-09-24 23:30:46 +00001204 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001205 Types.push_back(New);
1206 ComplexTypes.InsertNode(New, InsertPos);
1207 return QualType(New, 0);
1208}
1209
Chris Lattner970e54e2006-11-12 00:37:36 +00001210/// getPointerType - Return the uniqued reference to the type for a pointer to
1211/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001212QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001213 // Unique pointers, to guarantee there is only one pointer of a particular
1214 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001215 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001216 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001217
Chris Lattner67521df2007-01-27 01:29:36 +00001218 void *InsertPos = 0;
1219 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001220 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001221
Chris Lattner7ccecb92006-11-12 08:50:50 +00001222 // If the pointee type isn't canonical, this won't be a canonical type either,
1223 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001224 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001225 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001226 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001227
Chris Lattner67521df2007-01-27 01:29:36 +00001228 // Get the new insert position for the node we care about.
1229 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001230 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001231 }
John McCall90d1c2d2009-09-24 23:30:46 +00001232 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001233 Types.push_back(New);
1234 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001235 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001236}
1237
Mike Stump11289f42009-09-09 15:08:12 +00001238/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001239/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001240QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001241 assert(T->isFunctionType() && "block of function types only");
1242 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001243 // structure.
1244 llvm::FoldingSetNodeID ID;
1245 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001246
Steve Naroffec33ed92008-08-27 16:04:49 +00001247 void *InsertPos = 0;
1248 if (BlockPointerType *PT =
1249 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1250 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001251
1252 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001253 // type either so fill in the canonical type field.
1254 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001255 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001256 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001257
Steve Naroffec33ed92008-08-27 16:04:49 +00001258 // Get the new insert position for the node we care about.
1259 BlockPointerType *NewIP =
1260 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001261 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001262 }
John McCall90d1c2d2009-09-24 23:30:46 +00001263 BlockPointerType *New
1264 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001265 Types.push_back(New);
1266 BlockPointerTypes.InsertNode(New, InsertPos);
1267 return QualType(New, 0);
1268}
1269
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001270/// getLValueReferenceType - Return the uniqued reference to the type for an
1271/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001272QualType
1273ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001274 // Unique pointers, to guarantee there is only one pointer of a particular
1275 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001276 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001277 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001278
1279 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001280 if (LValueReferenceType *RT =
1281 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001282 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001283
John McCallfc93cf92009-10-22 22:37:11 +00001284 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1285
Bill Wendling3708c182007-05-27 10:15:43 +00001286 // If the referencee type isn't canonical, this won't be a canonical type
1287 // either, so fill in the canonical type field.
1288 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001289 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1290 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1291 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001292
Bill Wendling3708c182007-05-27 10:15:43 +00001293 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001294 LValueReferenceType *NewIP =
1295 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001296 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001297 }
1298
John McCall90d1c2d2009-09-24 23:30:46 +00001299 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001300 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1301 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001302 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001303 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001304
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001305 return QualType(New, 0);
1306}
1307
1308/// getRValueReferenceType - Return the uniqued reference to the type for an
1309/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001310QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001311 // Unique pointers, to guarantee there is only one pointer of a particular
1312 // structure.
1313 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001314 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001315
1316 void *InsertPos = 0;
1317 if (RValueReferenceType *RT =
1318 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1319 return QualType(RT, 0);
1320
John McCallfc93cf92009-10-22 22:37:11 +00001321 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1322
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001323 // If the referencee type isn't canonical, this won't be a canonical type
1324 // either, so fill in the canonical type field.
1325 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001326 if (InnerRef || !T.isCanonical()) {
1327 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1328 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001329
1330 // Get the new insert position for the node we care about.
1331 RValueReferenceType *NewIP =
1332 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001333 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001334 }
1335
John McCall90d1c2d2009-09-24 23:30:46 +00001336 RValueReferenceType *New
1337 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001338 Types.push_back(New);
1339 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001340 return QualType(New, 0);
1341}
1342
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001343/// getMemberPointerType - Return the uniqued reference to the type for a
1344/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001345QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001346 // Unique pointers, to guarantee there is only one pointer of a particular
1347 // structure.
1348 llvm::FoldingSetNodeID ID;
1349 MemberPointerType::Profile(ID, T, Cls);
1350
1351 void *InsertPos = 0;
1352 if (MemberPointerType *PT =
1353 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1354 return QualType(PT, 0);
1355
1356 // If the pointee or class type isn't canonical, this won't be a canonical
1357 // type either, so fill in the canonical type field.
1358 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001359 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001360 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1361
1362 // Get the new insert position for the node we care about.
1363 MemberPointerType *NewIP =
1364 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001365 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001366 }
John McCall90d1c2d2009-09-24 23:30:46 +00001367 MemberPointerType *New
1368 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001369 Types.push_back(New);
1370 MemberPointerTypes.InsertNode(New, InsertPos);
1371 return QualType(New, 0);
1372}
1373
Mike Stump11289f42009-09-09 15:08:12 +00001374/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001375/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001376QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001377 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001378 ArrayType::ArraySizeModifier ASM,
Jay Foad39c79802011-01-12 09:06:06 +00001379 unsigned EltTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001380 assert((EltTy->isDependentType() ||
1381 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001382 "Constant array of VLAs is illegal!");
1383
Chris Lattnere2df3f92009-05-13 04:12:56 +00001384 // Convert the array size into a canonical width matching the pointer size for
1385 // the target.
1386 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001387 ArySize =
1388 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001389
Chris Lattner23b7eb62007-06-15 23:05:46 +00001390 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001391 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001392
Chris Lattner36f8e652007-01-27 08:31:04 +00001393 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001394 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001395 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001396 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001397
Chris Lattner7ccecb92006-11-12 08:50:50 +00001398 // If the element type isn't canonical, this won't be a canonical type either,
1399 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001400 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001401 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001402 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001403 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001404 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001405 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001406 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001407 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001408 }
Mike Stump11289f42009-09-09 15:08:12 +00001409
John McCall90d1c2d2009-09-24 23:30:46 +00001410 ConstantArrayType *New = new(*this,TypeAlignment)
1411 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001412 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001413 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001414 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001415}
1416
John McCall06549462011-01-18 08:40:38 +00001417/// getVariableArrayDecayedType - Turns the given type, which may be
1418/// variably-modified, into the corresponding type with all the known
1419/// sizes replaced with [*].
1420QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1421 // Vastly most common case.
1422 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001423
John McCall06549462011-01-18 08:40:38 +00001424 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001425
John McCall06549462011-01-18 08:40:38 +00001426 SplitQualType split = type.getSplitDesugaredType();
1427 const Type *ty = split.first;
1428 switch (ty->getTypeClass()) {
1429#define TYPE(Class, Base)
1430#define ABSTRACT_TYPE(Class, Base)
1431#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1432#include "clang/AST/TypeNodes.def"
1433 llvm_unreachable("didn't desugar past all non-canonical types?");
1434
1435 // These types should never be variably-modified.
1436 case Type::Builtin:
1437 case Type::Complex:
1438 case Type::Vector:
1439 case Type::ExtVector:
1440 case Type::DependentSizedExtVector:
1441 case Type::ObjCObject:
1442 case Type::ObjCInterface:
1443 case Type::ObjCObjectPointer:
1444 case Type::Record:
1445 case Type::Enum:
1446 case Type::UnresolvedUsing:
1447 case Type::TypeOfExpr:
1448 case Type::TypeOf:
1449 case Type::Decltype:
1450 case Type::DependentName:
1451 case Type::InjectedClassName:
1452 case Type::TemplateSpecialization:
1453 case Type::DependentTemplateSpecialization:
1454 case Type::TemplateTypeParm:
1455 case Type::SubstTemplateTypeParmPack:
1456 case Type::PackExpansion:
1457 llvm_unreachable("type should never be variably-modified");
1458
1459 // These types can be variably-modified but should never need to
1460 // further decay.
1461 case Type::FunctionNoProto:
1462 case Type::FunctionProto:
1463 case Type::BlockPointer:
1464 case Type::MemberPointer:
1465 return type;
1466
1467 // These types can be variably-modified. All these modifications
1468 // preserve structure except as noted by comments.
1469 // TODO: if we ever care about optimizing VLAs, there are no-op
1470 // optimizations available here.
1471 case Type::Pointer:
1472 result = getPointerType(getVariableArrayDecayedType(
1473 cast<PointerType>(ty)->getPointeeType()));
1474 break;
1475
1476 case Type::LValueReference: {
1477 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1478 result = getLValueReferenceType(
1479 getVariableArrayDecayedType(lv->getPointeeType()),
1480 lv->isSpelledAsLValue());
1481 break;
1482 }
1483
1484 case Type::RValueReference: {
1485 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1486 result = getRValueReferenceType(
1487 getVariableArrayDecayedType(lv->getPointeeType()));
1488 break;
1489 }
1490
1491 case Type::ConstantArray: {
1492 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1493 result = getConstantArrayType(
1494 getVariableArrayDecayedType(cat->getElementType()),
1495 cat->getSize(),
1496 cat->getSizeModifier(),
1497 cat->getIndexTypeCVRQualifiers());
1498 break;
1499 }
1500
1501 case Type::DependentSizedArray: {
1502 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1503 result = getDependentSizedArrayType(
1504 getVariableArrayDecayedType(dat->getElementType()),
1505 dat->getSizeExpr(),
1506 dat->getSizeModifier(),
1507 dat->getIndexTypeCVRQualifiers(),
1508 dat->getBracketsRange());
1509 break;
1510 }
1511
1512 // Turn incomplete types into [*] types.
1513 case Type::IncompleteArray: {
1514 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1515 result = getVariableArrayType(
1516 getVariableArrayDecayedType(iat->getElementType()),
1517 /*size*/ 0,
1518 ArrayType::Normal,
1519 iat->getIndexTypeCVRQualifiers(),
1520 SourceRange());
1521 break;
1522 }
1523
1524 // Turn VLA types into [*] types.
1525 case Type::VariableArray: {
1526 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1527 result = getVariableArrayType(
1528 getVariableArrayDecayedType(vat->getElementType()),
1529 /*size*/ 0,
1530 ArrayType::Star,
1531 vat->getIndexTypeCVRQualifiers(),
1532 vat->getBracketsRange());
1533 break;
1534 }
1535 }
1536
1537 // Apply the top-level qualifiers from the original.
1538 return getQualifiedType(result, split.second);
1539}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001540
Steve Naroffcadebd02007-08-30 18:14:25 +00001541/// getVariableArrayType - Returns a non-unique reference to the type for a
1542/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001543QualType ASTContext::getVariableArrayType(QualType EltTy,
1544 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001545 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001546 unsigned EltTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001547 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001548 // Since we don't unique expressions, it isn't possible to unique VLA's
1549 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001550 QualType CanonType;
1551
1552 if (!EltTy.isCanonical()) {
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001553 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1554 EltTypeQuals, Brackets);
1555 }
1556
John McCall90d1c2d2009-09-24 23:30:46 +00001557 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001558 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001559
1560 VariableArrayTypes.push_back(New);
1561 Types.push_back(New);
1562 return QualType(New, 0);
1563}
1564
Douglas Gregor4619e432008-12-05 23:32:09 +00001565/// getDependentSizedArrayType - Returns a non-unique reference to
1566/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001567/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001568QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1569 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001570 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001571 unsigned EltTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001572 SourceRange Brackets) const {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001573 assert((!NumElts || NumElts->isTypeDependent() ||
1574 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001575 "Size must be type- or value-dependent!");
1576
Douglas Gregorf3f95522009-07-31 00:23:35 +00001577 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001578 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001579 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001580
Douglas Gregorf86c9392010-10-26 00:51:02 +00001581 QualType CanonicalEltTy = getCanonicalType(EltTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001582 if (NumElts) {
1583 // Dependently-sized array types that do not have a specified
1584 // number of elements will have their sizes deduced from an
1585 // initializer.
Douglas Gregorf86c9392010-10-26 00:51:02 +00001586 DependentSizedArrayType::Profile(ID, *this, CanonicalEltTy, ASM,
Douglas Gregorad2956c2009-11-19 18:03:26 +00001587 EltTypeQuals, NumElts);
1588
1589 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1590 }
1591
Douglas Gregorf3f95522009-07-31 00:23:35 +00001592 DependentSizedArrayType *New;
1593 if (Canon) {
1594 // We already have a canonical version of this array type; use it as
1595 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001596 New = new (*this, TypeAlignment)
1597 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1598 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf86c9392010-10-26 00:51:02 +00001599 } else if (CanonicalEltTy == EltTy) {
1600 // This is a canonical type. Record it.
1601 New = new (*this, TypeAlignment)
1602 DependentSizedArrayType(*this, EltTy, QualType(),
1603 NumElts, ASM, EltTypeQuals, Brackets);
1604
1605 if (NumElts) {
1606#ifndef NDEBUG
1607 DependentSizedArrayType *CanonCheck
1608 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1609 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1610 (void)CanonCheck;
1611#endif
1612 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001613 }
Douglas Gregorf86c9392010-10-26 00:51:02 +00001614 } else {
1615 QualType Canon = getDependentSizedArrayType(CanonicalEltTy, NumElts,
1616 ASM, EltTypeQuals,
1617 SourceRange());
1618 New = new (*this, TypeAlignment)
1619 DependentSizedArrayType(*this, EltTy, Canon,
1620 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001621 }
Mike Stump11289f42009-09-09 15:08:12 +00001622
Douglas Gregor4619e432008-12-05 23:32:09 +00001623 Types.push_back(New);
1624 return QualType(New, 0);
1625}
1626
Eli Friedmanbd258282008-02-15 18:16:39 +00001627QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1628 ArrayType::ArraySizeModifier ASM,
Jay Foad39c79802011-01-12 09:06:06 +00001629 unsigned EltTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001630 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001631 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001632
1633 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001634 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001635 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1636 return QualType(ATP, 0);
1637
1638 // If the element type isn't canonical, this won't be a canonical type
1639 // either, so fill in the canonical type field.
1640 QualType Canonical;
1641
John McCallb692a092009-10-22 20:10:53 +00001642 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001643 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001644 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001645
1646 // Get the new insert position for the node we care about.
1647 IncompleteArrayType *NewIP =
1648 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001649 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001650 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001651
John McCall90d1c2d2009-09-24 23:30:46 +00001652 IncompleteArrayType *New = new (*this, TypeAlignment)
1653 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001654
1655 IncompleteArrayTypes.InsertNode(New, InsertPos);
1656 Types.push_back(New);
1657 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001658}
1659
Steve Naroff91fcddb2007-07-18 18:00:27 +00001660/// getVectorType - Return the unique reference to a vector type of
1661/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001662QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001663 VectorType::VectorKind VecKind) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00001664 BuiltinType *BaseType;
Mike Stump11289f42009-09-09 15:08:12 +00001665
Chris Lattnerdc226c22010-10-01 22:42:38 +00001666 BaseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1667 assert(BaseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001668
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001669 // Check if we've already instantiated a vector of this type.
1670 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001671 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001672
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001673 void *InsertPos = 0;
1674 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1675 return QualType(VTP, 0);
1676
1677 // If the element type isn't canonical, this won't be a canonical type either,
1678 // so fill in the canonical type field.
1679 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001680 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001681 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001682
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001683 // Get the new insert position for the node we care about.
1684 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001685 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001686 }
John McCall90d1c2d2009-09-24 23:30:46 +00001687 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001688 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001689 VectorTypes.InsertNode(New, InsertPos);
1690 Types.push_back(New);
1691 return QualType(New, 0);
1692}
1693
Nate Begemance4d7fc2008-04-18 23:10:10 +00001694/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001695/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001696QualType
1697ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001698 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001699
Chris Lattner76a00cf2008-04-06 22:59:24 +00001700 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001701 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001702
Steve Naroff91fcddb2007-07-18 18:00:27 +00001703 // Check if we've already instantiated a vector of this type.
1704 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001705 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001706 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001707 void *InsertPos = 0;
1708 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1709 return QualType(VTP, 0);
1710
1711 // If the element type isn't canonical, this won't be a canonical type either,
1712 // so fill in the canonical type field.
1713 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001714 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001715 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001716
Steve Naroff91fcddb2007-07-18 18:00:27 +00001717 // Get the new insert position for the node we care about.
1718 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001719 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001720 }
John McCall90d1c2d2009-09-24 23:30:46 +00001721 ExtVectorType *New = new (*this, TypeAlignment)
1722 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001723 VectorTypes.InsertNode(New, InsertPos);
1724 Types.push_back(New);
1725 return QualType(New, 0);
1726}
1727
Jay Foad39c79802011-01-12 09:06:06 +00001728QualType
1729ASTContext::getDependentSizedExtVectorType(QualType vecType,
1730 Expr *SizeExpr,
1731 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001732 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001733 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001734 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001735
Douglas Gregor352169a2009-07-31 03:54:25 +00001736 void *InsertPos = 0;
1737 DependentSizedExtVectorType *Canon
1738 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1739 DependentSizedExtVectorType *New;
1740 if (Canon) {
1741 // We already have a canonical version of this array type; use it as
1742 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001743 New = new (*this, TypeAlignment)
1744 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1745 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001746 } else {
1747 QualType CanonVecTy = getCanonicalType(vecType);
1748 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001749 New = new (*this, TypeAlignment)
1750 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1751 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001752
1753 DependentSizedExtVectorType *CanonCheck
1754 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1755 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1756 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001757 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1758 } else {
1759 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1760 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001761 New = new (*this, TypeAlignment)
1762 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001763 }
1764 }
Mike Stump11289f42009-09-09 15:08:12 +00001765
Douglas Gregor758a8692009-06-17 21:51:59 +00001766 Types.push_back(New);
1767 return QualType(New, 0);
1768}
1769
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001770/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001771///
Jay Foad39c79802011-01-12 09:06:06 +00001772QualType
1773ASTContext::getFunctionNoProtoType(QualType ResultTy,
1774 const FunctionType::ExtInfo &Info) const {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001775 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001776 // Unique functions, to guarantee there is only one function of a particular
1777 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001778 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001779 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001780
Chris Lattner47955de2007-01-27 08:37:20 +00001781 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001782 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001783 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001784 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001785
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001786 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001787 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001788 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001789 Canonical =
1790 getFunctionNoProtoType(getCanonicalType(ResultTy),
1791 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001792
Chris Lattner47955de2007-01-27 08:37:20 +00001793 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001794 FunctionNoProtoType *NewIP =
1795 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001796 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001797 }
Mike Stump11289f42009-09-09 15:08:12 +00001798
John McCall90d1c2d2009-09-24 23:30:46 +00001799 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001800 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001801 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001802 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001803 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001804}
1805
1806/// getFunctionType - Return a normal function type with a typed argument
1807/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001808QualType
1809ASTContext::getFunctionType(QualType ResultTy,
1810 const QualType *ArgArray, unsigned NumArgs,
1811 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001812 // Unique functions, to guarantee there is only one function of a particular
1813 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001814 llvm::FoldingSetNodeID ID;
John McCalldb40c7f2010-12-14 08:05:40 +00001815 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001816
1817 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001818 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001819 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001820 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001821
1822 // Determine whether the type being created is already canonical or not.
John McCalldb40c7f2010-12-14 08:05:40 +00001823 bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001824 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001825 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001826 isCanonical = false;
1827
John McCalldb40c7f2010-12-14 08:05:40 +00001828 const CallingConv CallConv = EPI.ExtInfo.getCC();
1829
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001830 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001831 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001832 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001833 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001834 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001835 CanonicalArgs.reserve(NumArgs);
1836 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001837 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001838
John McCalldb40c7f2010-12-14 08:05:40 +00001839 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1840 if (CanonicalEPI.HasExceptionSpec) {
1841 CanonicalEPI.HasExceptionSpec = false;
1842 CanonicalEPI.HasAnyExceptionSpec = false;
1843 CanonicalEPI.NumExceptions = 0;
1844 }
1845 CanonicalEPI.ExtInfo
1846 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1847
Chris Lattner76a00cf2008-04-06 22:59:24 +00001848 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001849 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00001850 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001851
Chris Lattnerfd4de792007-01-27 01:15:32 +00001852 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001853 FunctionProtoType *NewIP =
1854 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001855 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001856 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001857
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001858 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001859 // for two variable size arrays (for parameter and exception types) at the
1860 // end of them.
John McCalldb40c7f2010-12-14 08:05:40 +00001861 size_t Size = sizeof(FunctionProtoType) +
1862 NumArgs * sizeof(QualType) +
1863 EPI.NumExceptions * sizeof(QualType);
1864 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
1865 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, EPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001866 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001867 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001868 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001869}
Chris Lattneref51c202006-11-10 07:17:23 +00001870
John McCalle78aac42010-03-10 03:28:59 +00001871#ifndef NDEBUG
1872static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1873 if (!isa<CXXRecordDecl>(D)) return false;
1874 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1875 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1876 return true;
1877 if (RD->getDescribedClassTemplate() &&
1878 !isa<ClassTemplateSpecializationDecl>(RD))
1879 return true;
1880 return false;
1881}
1882#endif
1883
1884/// getInjectedClassNameType - Return the unique reference to the
1885/// injected class name type for the specified templated declaration.
1886QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00001887 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00001888 assert(NeedsInjectedClassNameType(Decl));
1889 if (Decl->TypeForDecl) {
1890 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001891 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001892 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1893 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1894 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1895 } else {
John McCall2408e322010-04-27 00:57:59 +00001896 Decl->TypeForDecl =
1897 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001898 Types.push_back(Decl->TypeForDecl);
1899 }
1900 return QualType(Decl->TypeForDecl, 0);
1901}
1902
Douglas Gregor83a586e2008-04-13 21:07:44 +00001903/// getTypeDeclType - Return the unique reference to the type for the
1904/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00001905QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001906 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001907 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001908
John McCall81e38502010-02-16 03:57:14 +00001909 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001910 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001911
John McCall96f0b5f2010-03-10 06:48:02 +00001912 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1913 "Template type parameter types are always available.");
1914
John McCall81e38502010-02-16 03:57:14 +00001915 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001916 assert(!Record->getPreviousDeclaration() &&
1917 "struct/union has previous declaration");
1918 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001919 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001920 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001921 assert(!Enum->getPreviousDeclaration() &&
1922 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001923 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001924 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001925 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1926 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001927 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001928 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001929
John McCall96f0b5f2010-03-10 06:48:02 +00001930 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001931 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001932}
1933
Chris Lattner32d920b2007-01-26 02:01:53 +00001934/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001935/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001936QualType
Jay Foad39c79802011-01-12 09:06:06 +00001937ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001938 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001939
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001940 if (Canonical.isNull())
1941 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001942 Decl->TypeForDecl = new(*this, TypeAlignment)
1943 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001944 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001945 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001946}
1947
Jay Foad39c79802011-01-12 09:06:06 +00001948QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001949 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1950
1951 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1952 if (PrevDecl->TypeForDecl)
1953 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1954
1955 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1956 Types.push_back(Decl->TypeForDecl);
1957 return QualType(Decl->TypeForDecl, 0);
1958}
1959
Jay Foad39c79802011-01-12 09:06:06 +00001960QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001961 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1962
1963 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1964 if (PrevDecl->TypeForDecl)
1965 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1966
1967 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1968 Types.push_back(Decl->TypeForDecl);
1969 return QualType(Decl->TypeForDecl, 0);
1970}
1971
John McCall81904512011-01-06 01:58:22 +00001972QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
1973 QualType modifiedType,
1974 QualType equivalentType) {
1975 llvm::FoldingSetNodeID id;
1976 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
1977
1978 void *insertPos = 0;
1979 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
1980 if (type) return QualType(type, 0);
1981
1982 QualType canon = getCanonicalType(equivalentType);
1983 type = new (*this, TypeAlignment)
1984 AttributedType(canon, attrKind, modifiedType, equivalentType);
1985
1986 Types.push_back(type);
1987 AttributedTypes.InsertNode(type, insertPos);
1988
1989 return QualType(type, 0);
1990}
1991
1992
John McCallcebee162009-10-18 09:09:24 +00001993/// \brief Retrieve a substitution-result type.
1994QualType
1995ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00001996 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00001997 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001998 && "replacement types must always be canonical");
1999
2000 llvm::FoldingSetNodeID ID;
2001 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2002 void *InsertPos = 0;
2003 SubstTemplateTypeParmType *SubstParm
2004 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2005
2006 if (!SubstParm) {
2007 SubstParm = new (*this, TypeAlignment)
2008 SubstTemplateTypeParmType(Parm, Replacement);
2009 Types.push_back(SubstParm);
2010 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2011 }
2012
2013 return QualType(SubstParm, 0);
2014}
2015
Douglas Gregorada4b792011-01-14 02:55:32 +00002016/// \brief Retrieve a
2017QualType ASTContext::getSubstTemplateTypeParmPackType(
2018 const TemplateTypeParmType *Parm,
2019 const TemplateArgument &ArgPack) {
2020#ifndef NDEBUG
2021 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2022 PEnd = ArgPack.pack_end();
2023 P != PEnd; ++P) {
2024 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2025 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2026 }
2027#endif
2028
2029 llvm::FoldingSetNodeID ID;
2030 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2031 void *InsertPos = 0;
2032 if (SubstTemplateTypeParmPackType *SubstParm
2033 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2034 return QualType(SubstParm, 0);
2035
2036 QualType Canon;
2037 if (!Parm->isCanonicalUnqualified()) {
2038 Canon = getCanonicalType(QualType(Parm, 0));
2039 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2040 ArgPack);
2041 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2042 }
2043
2044 SubstTemplateTypeParmPackType *SubstParm
2045 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2046 ArgPack);
2047 Types.push_back(SubstParm);
2048 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2049 return QualType(SubstParm, 0);
2050}
2051
Douglas Gregoreff93e02009-02-05 23:33:38 +00002052/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002053/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002054/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002055QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002056 bool ParameterPack,
Jay Foad39c79802011-01-12 09:06:06 +00002057 IdentifierInfo *Name) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002058 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002059 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002060 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002061 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002062 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2063
2064 if (TypeParm)
2065 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002066
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002067 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002068 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002069 TypeParm = new (*this, TypeAlignment)
2070 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002071
2072 TemplateTypeParmType *TypeCheck
2073 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2074 assert(!TypeCheck && "Template type parameter canonical type broken");
2075 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002076 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002077 TypeParm = new (*this, TypeAlignment)
2078 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002079
2080 Types.push_back(TypeParm);
2081 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2082
2083 return QualType(TypeParm, 0);
2084}
2085
John McCalle78aac42010-03-10 03:28:59 +00002086TypeSourceInfo *
2087ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2088 SourceLocation NameLoc,
2089 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002090 QualType CanonType) const {
John McCalle78aac42010-03-10 03:28:59 +00002091 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2092
2093 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2094 TemplateSpecializationTypeLoc TL
2095 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2096 TL.setTemplateNameLoc(NameLoc);
2097 TL.setLAngleLoc(Args.getLAngleLoc());
2098 TL.setRAngleLoc(Args.getRAngleLoc());
2099 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2100 TL.setArgLocInfo(i, Args[i].getLocInfo());
2101 return DI;
2102}
2103
Mike Stump11289f42009-09-09 15:08:12 +00002104QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002105ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002106 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002107 QualType Canon) const {
John McCall6b51f282009-11-23 01:53:49 +00002108 unsigned NumArgs = Args.size();
2109
John McCall0ad16662009-10-29 08:12:44 +00002110 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2111 ArgVec.reserve(NumArgs);
2112 for (unsigned i = 0; i != NumArgs; ++i)
2113 ArgVec.push_back(Args[i].getArgument());
2114
John McCall2408e322010-04-27 00:57:59 +00002115 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00002116 Canon);
John McCall0ad16662009-10-29 08:12:44 +00002117}
2118
2119QualType
2120ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002121 const TemplateArgument *Args,
2122 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002123 QualType Canon) const {
Douglas Gregor15301382009-07-30 17:40:51 +00002124 if (!Canon.isNull())
2125 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002126 else
2127 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00002128
Douglas Gregora8e02e72009-07-28 23:00:59 +00002129 // Allocate the (non-canonical) template specialization type, but don't
2130 // try to unique it: these types typically have location information that
2131 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002132 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002133 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002134 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002135 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002136 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002137 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002138 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002139
Douglas Gregor8bf42052009-02-09 18:46:07 +00002140 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002141 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002142}
2143
Mike Stump11289f42009-09-09 15:08:12 +00002144QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002145ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2146 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002147 unsigned NumArgs) const {
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002148 // Build the canonical template specialization type.
2149 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2150 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2151 CanonArgs.reserve(NumArgs);
2152 for (unsigned I = 0; I != NumArgs; ++I)
2153 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2154
2155 // Determine whether this canonical template specialization type already
2156 // exists.
2157 llvm::FoldingSetNodeID ID;
2158 TemplateSpecializationType::Profile(ID, CanonTemplate,
2159 CanonArgs.data(), NumArgs, *this);
2160
2161 void *InsertPos = 0;
2162 TemplateSpecializationType *Spec
2163 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2164
2165 if (!Spec) {
2166 // Allocate a new canonical template specialization type.
2167 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2168 sizeof(TemplateArgument) * NumArgs),
2169 TypeAlignment);
2170 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2171 CanonArgs.data(), NumArgs,
2172 QualType());
2173 Types.push_back(Spec);
2174 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2175 }
2176
2177 assert(Spec->isDependentType() &&
2178 "Non-dependent template-id type must have a canonical type");
2179 return QualType(Spec, 0);
2180}
2181
2182QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002183ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2184 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002185 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002186 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002187 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002188
2189 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002190 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002191 if (T)
2192 return QualType(T, 0);
2193
Douglas Gregorc42075a2010-02-04 18:10:26 +00002194 QualType Canon = NamedType;
2195 if (!Canon.isCanonical()) {
2196 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002197 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2198 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002199 (void)CheckT;
2200 }
2201
Abramo Bagnara6150c882010-05-11 21:36:43 +00002202 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002203 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002204 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002205 return QualType(T, 0);
2206}
2207
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002208QualType
Jay Foad39c79802011-01-12 09:06:06 +00002209ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002210 llvm::FoldingSetNodeID ID;
2211 ParenType::Profile(ID, InnerType);
2212
2213 void *InsertPos = 0;
2214 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2215 if (T)
2216 return QualType(T, 0);
2217
2218 QualType Canon = InnerType;
2219 if (!Canon.isCanonical()) {
2220 Canon = getCanonicalType(InnerType);
2221 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2222 assert(!CheckT && "Paren canonical type broken");
2223 (void)CheckT;
2224 }
2225
2226 T = new (*this) ParenType(InnerType, Canon);
2227 Types.push_back(T);
2228 ParenTypes.InsertNode(T, InsertPos);
2229 return QualType(T, 0);
2230}
2231
Douglas Gregor02085352010-03-31 20:19:30 +00002232QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2233 NestedNameSpecifier *NNS,
2234 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002235 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002236 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2237
2238 if (Canon.isNull()) {
2239 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002240 ElaboratedTypeKeyword CanonKeyword = Keyword;
2241 if (Keyword == ETK_None)
2242 CanonKeyword = ETK_Typename;
2243
2244 if (CanonNNS != NNS || CanonKeyword != Keyword)
2245 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002246 }
2247
2248 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002249 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002250
2251 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002252 DependentNameType *T
2253 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002254 if (T)
2255 return QualType(T, 0);
2256
Douglas Gregor02085352010-03-31 20:19:30 +00002257 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002258 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002259 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002260 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002261}
2262
Mike Stump11289f42009-09-09 15:08:12 +00002263QualType
John McCallc392f372010-06-11 00:33:02 +00002264ASTContext::getDependentTemplateSpecializationType(
2265 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002266 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002267 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002268 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002269 // TODO: avoid this copy
2270 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2271 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2272 ArgCopy.push_back(Args[I].getArgument());
2273 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2274 ArgCopy.size(),
2275 ArgCopy.data());
2276}
2277
2278QualType
2279ASTContext::getDependentTemplateSpecializationType(
2280 ElaboratedTypeKeyword Keyword,
2281 NestedNameSpecifier *NNS,
2282 const IdentifierInfo *Name,
2283 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002284 const TemplateArgument *Args) const {
Douglas Gregordce2b622009-04-01 00:28:59 +00002285 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2286
Douglas Gregorc42075a2010-02-04 18:10:26 +00002287 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002288 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2289 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002290
2291 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002292 DependentTemplateSpecializationType *T
2293 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002294 if (T)
2295 return QualType(T, 0);
2296
John McCallc392f372010-06-11 00:33:02 +00002297 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002298
John McCallc392f372010-06-11 00:33:02 +00002299 ElaboratedTypeKeyword CanonKeyword = Keyword;
2300 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2301
2302 bool AnyNonCanonArgs = false;
2303 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2304 for (unsigned I = 0; I != NumArgs; ++I) {
2305 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2306 if (!CanonArgs[I].structurallyEquals(Args[I]))
2307 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002308 }
2309
John McCallc392f372010-06-11 00:33:02 +00002310 QualType Canon;
2311 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2312 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2313 Name, NumArgs,
2314 CanonArgs.data());
2315
2316 // Find the insert position again.
2317 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2318 }
2319
2320 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2321 sizeof(TemplateArgument) * NumArgs),
2322 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002323 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002324 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002325 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002326 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002327 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002328}
2329
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002330QualType ASTContext::getPackExpansionType(QualType Pattern,
2331 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002332 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002333 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002334
2335 assert(Pattern->containsUnexpandedParameterPack() &&
2336 "Pack expansions must expand one or more parameter packs");
2337 void *InsertPos = 0;
2338 PackExpansionType *T
2339 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2340 if (T)
2341 return QualType(T, 0);
2342
2343 QualType Canon;
2344 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002345 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002346
2347 // Find the insert position again.
2348 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2349 }
2350
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002351 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002352 Types.push_back(T);
2353 PackExpansionTypes.InsertNode(T, InsertPos);
2354 return QualType(T, 0);
2355}
2356
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002357/// CmpProtocolNames - Comparison predicate for sorting protocols
2358/// alphabetically.
2359static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2360 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002361 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002362}
2363
John McCall8b07ec22010-05-15 11:32:37 +00002364static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002365 unsigned NumProtocols) {
2366 if (NumProtocols == 0) return true;
2367
2368 for (unsigned i = 1; i != NumProtocols; ++i)
2369 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2370 return false;
2371 return true;
2372}
2373
2374static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002375 unsigned &NumProtocols) {
2376 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002377
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002378 // Sort protocols, keyed by name.
2379 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2380
2381 // Remove duplicates.
2382 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2383 NumProtocols = ProtocolsEnd-Protocols;
2384}
2385
John McCall8b07ec22010-05-15 11:32:37 +00002386QualType ASTContext::getObjCObjectType(QualType BaseType,
2387 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002388 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002389 // If the base type is an interface and there aren't any protocols
2390 // to add, then the interface type will do just fine.
2391 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2392 return BaseType;
2393
2394 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002395 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002396 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002397 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002398 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2399 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002400
John McCall8b07ec22010-05-15 11:32:37 +00002401 // Build the canonical type, which has the canonical base type and
2402 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002403 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002404 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2405 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2406 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002407 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2408 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002409 unsigned UniqueCount = NumProtocols;
2410
John McCallfc93cf92009-10-22 22:37:11 +00002411 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002412 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2413 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002414 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002415 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2416 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002417 }
2418
2419 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002420 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2421 }
2422
2423 unsigned Size = sizeof(ObjCObjectTypeImpl);
2424 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2425 void *Mem = Allocate(Size, TypeAlignment);
2426 ObjCObjectTypeImpl *T =
2427 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2428
2429 Types.push_back(T);
2430 ObjCObjectTypes.InsertNode(T, InsertPos);
2431 return QualType(T, 0);
2432}
2433
2434/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2435/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002436QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002437 llvm::FoldingSetNodeID ID;
2438 ObjCObjectPointerType::Profile(ID, ObjectT);
2439
2440 void *InsertPos = 0;
2441 if (ObjCObjectPointerType *QT =
2442 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2443 return QualType(QT, 0);
2444
2445 // Find the canonical object type.
2446 QualType Canonical;
2447 if (!ObjectT.isCanonical()) {
2448 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2449
2450 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002451 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2452 }
2453
Douglas Gregorf85bee62010-02-08 22:59:26 +00002454 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002455 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2456 ObjCObjectPointerType *QType =
2457 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002458
Steve Narofffb4330f2009-06-17 22:40:22 +00002459 Types.push_back(QType);
2460 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002461 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002462}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002463
Douglas Gregor1c283312010-08-11 12:19:30 +00002464/// getObjCInterfaceType - Return the unique reference to the type for the
2465/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002466QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002467 if (Decl->TypeForDecl)
2468 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002469
Douglas Gregor1c283312010-08-11 12:19:30 +00002470 // FIXME: redeclarations?
2471 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2472 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2473 Decl->TypeForDecl = T;
2474 Types.push_back(T);
2475 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002476}
2477
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002478/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2479/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002480/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002481/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002482/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002483QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002484 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002485 if (tofExpr->isTypeDependent()) {
2486 llvm::FoldingSetNodeID ID;
2487 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002488
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002489 void *InsertPos = 0;
2490 DependentTypeOfExprType *Canon
2491 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2492 if (Canon) {
2493 // We already have a "canonical" version of an identical, dependent
2494 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002495 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002496 QualType((TypeOfExprType*)Canon, 0));
2497 }
2498 else {
2499 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002500 Canon
2501 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002502 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2503 toe = Canon;
2504 }
2505 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002506 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002507 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002508 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002509 Types.push_back(toe);
2510 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002511}
2512
Steve Naroffa773cd52007-08-01 18:02:17 +00002513/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2514/// TypeOfType AST's. The only motivation to unique these nodes would be
2515/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002516/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002517/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002518QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002519 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002520 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002521 Types.push_back(tot);
2522 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002523}
2524
Anders Carlssonad6bd352009-06-24 21:24:56 +00002525/// getDecltypeForExpr - Given an expr, will return the decltype for that
2526/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002527static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002528 if (e->isTypeDependent())
2529 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002530
Anders Carlssonad6bd352009-06-24 21:24:56 +00002531 // If e is an id expression or a class member access, decltype(e) is defined
2532 // as the type of the entity named by e.
2533 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2534 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2535 return VD->getType();
2536 }
2537 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2538 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2539 return FD->getType();
2540 }
2541 // If e is a function call or an invocation of an overloaded operator,
2542 // (parentheses around e are ignored), decltype(e) is defined as the
2543 // return type of that function.
2544 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2545 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002546
Anders Carlssonad6bd352009-06-24 21:24:56 +00002547 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002548
2549 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002550 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002551 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002552 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002553
Anders Carlssonad6bd352009-06-24 21:24:56 +00002554 return T;
2555}
2556
Anders Carlsson81df7b82009-06-24 19:06:50 +00002557/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2558/// DecltypeType AST's. The only motivation to unique these nodes would be
2559/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002560/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002561/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002562QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002563 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002564 if (e->isTypeDependent()) {
2565 llvm::FoldingSetNodeID ID;
2566 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002567
Douglas Gregora21f6c32009-07-30 23:36:40 +00002568 void *InsertPos = 0;
2569 DependentDecltypeType *Canon
2570 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2571 if (Canon) {
2572 // We already have a "canonical" version of an equivalent, dependent
2573 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002574 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002575 QualType((DecltypeType*)Canon, 0));
2576 }
2577 else {
2578 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002579 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002580 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2581 dt = Canon;
2582 }
2583 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002584 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002585 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002586 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002587 Types.push_back(dt);
2588 return QualType(dt, 0);
2589}
2590
Chris Lattnerfb072462007-01-23 05:45:31 +00002591/// getTagDeclType - Return the unique reference to the type for the
2592/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002593QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002594 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002595 // FIXME: What is the design on getTagDeclType when it requires casting
2596 // away const? mutable?
2597 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002598}
2599
Mike Stump11289f42009-09-09 15:08:12 +00002600/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2601/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2602/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002603CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002604 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002605}
Chris Lattnerfb072462007-01-23 05:45:31 +00002606
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002607/// getSignedWCharType - Return the type of "signed wchar_t".
2608/// Used when in C++, as a GCC extension.
2609QualType ASTContext::getSignedWCharType() const {
2610 // FIXME: derive from "Target" ?
2611 return WCharTy;
2612}
2613
2614/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2615/// Used when in C++, as a GCC extension.
2616QualType ASTContext::getUnsignedWCharType() const {
2617 // FIXME: derive from "Target" ?
2618 return UnsignedIntTy;
2619}
2620
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002621/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2622/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2623QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002624 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002625}
2626
Chris Lattnera21ad802008-04-02 05:18:44 +00002627//===----------------------------------------------------------------------===//
2628// Type Operators
2629//===----------------------------------------------------------------------===//
2630
Jay Foad39c79802011-01-12 09:06:06 +00002631CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002632 // Push qualifiers into arrays, and then discard any remaining
2633 // qualifiers.
2634 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002635 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002636 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002637 QualType Result;
2638 if (isa<ArrayType>(Ty)) {
2639 Result = getArrayDecayedType(QualType(Ty,0));
2640 } else if (isa<FunctionType>(Ty)) {
2641 Result = getPointerType(QualType(Ty, 0));
2642 } else {
2643 Result = QualType(Ty, 0);
2644 }
2645
2646 return CanQualType::CreateUnsafe(Result);
2647}
2648
Chris Lattnered0d0792008-04-06 22:41:35 +00002649/// getCanonicalType - Return the canonical (structural) type corresponding to
2650/// the specified potentially non-canonical type. The non-canonical version
2651/// of a type may have many "decorated" versions of types. Decorators can
2652/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2653/// to be free of any of these, allowing two canonical types to be compared
2654/// for exact equality with a simple pointer comparison.
Jay Foad39c79802011-01-12 09:06:06 +00002655CanQualType ASTContext::getCanonicalType(QualType T) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002656 QualifierCollector Quals;
2657 const Type *Ptr = Quals.strip(T);
2658 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002659
John McCall8ccfcb52009-09-24 19:53:00 +00002660 // The canonical internal type will be the canonical type *except*
2661 // that we push type qualifiers down through array types.
2662
2663 // If there are no new qualifiers to push down, stop here.
2664 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002665 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002666
John McCall8ccfcb52009-09-24 19:53:00 +00002667 // If the type qualifiers are on an array type, get the canonical
2668 // type of the array with the qualifiers applied to the element
2669 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002670 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2671 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002672 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002673
Chris Lattner7adf0762008-08-04 07:31:14 +00002674 // Get the canonical version of the element with the extra qualifiers on it.
2675 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002676 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002677 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002678
Chris Lattner7adf0762008-08-04 07:31:14 +00002679 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002680 return CanQualType::CreateUnsafe(
2681 getConstantArrayType(NewEltTy, CAT->getSize(),
2682 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002683 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002684 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002685 return CanQualType::CreateUnsafe(
2686 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002687 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002688
Douglas Gregor4619e432008-12-05 23:32:09 +00002689 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002690 return CanQualType::CreateUnsafe(
2691 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002692 DSAT->getSizeExpr(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002693 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002694 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002695 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002696
Chris Lattner7adf0762008-08-04 07:31:14 +00002697 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002698 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002699 VAT->getSizeExpr(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002700 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002701 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002702 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002703}
2704
John McCall6c9dd522011-01-18 07:41:22 +00002705QualType ASTContext::getUnqualifiedArrayType(QualType type,
2706 Qualifiers &quals) {
2707 SplitQualType splitType = type.getSplitUnqualifiedType();
2708
2709 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2710 // the unqualified desugared type and then drops it on the floor.
2711 // We then have to strip that sugar back off with
2712 // getUnqualifiedDesugaredType(), which is silly.
2713 const ArrayType *AT =
2714 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2715
2716 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002717 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002718 quals = splitType.second;
2719 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002720 }
2721
John McCall6c9dd522011-01-18 07:41:22 +00002722 // Otherwise, recurse on the array's element type.
2723 QualType elementType = AT->getElementType();
2724 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2725
2726 // If that didn't change the element type, AT has no qualifiers, so we
2727 // can just use the results in splitType.
2728 if (elementType == unqualElementType) {
2729 assert(quals.empty()); // from the recursive call
2730 quals = splitType.second;
2731 return QualType(splitType.first, 0);
2732 }
2733
2734 // Otherwise, add in the qualifiers from the outermost type, then
2735 // build the type back up.
2736 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002737
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002738 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002739 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002740 CAT->getSizeModifier(), 0);
2741 }
2742
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002743 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002744 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002745 }
2746
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002747 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002748 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002749 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002750 VAT->getSizeModifier(),
2751 VAT->getIndexTypeCVRQualifiers(),
2752 VAT->getBracketsRange());
2753 }
2754
2755 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002756 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002757 DSAT->getSizeModifier(), 0,
2758 SourceRange());
2759}
2760
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002761/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2762/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2763/// they point to and return true. If T1 and T2 aren't pointer types
2764/// or pointer-to-member types, or if they are not similar at this
2765/// level, returns false and leaves T1 and T2 unchanged. Top-level
2766/// qualifiers on T1 and T2 are ignored. This function will typically
2767/// be called in a loop that successively "unwraps" pointer and
2768/// pointer-to-member types to compare them at each level.
2769bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2770 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2771 *T2PtrType = T2->getAs<PointerType>();
2772 if (T1PtrType && T2PtrType) {
2773 T1 = T1PtrType->getPointeeType();
2774 T2 = T2PtrType->getPointeeType();
2775 return true;
2776 }
2777
2778 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2779 *T2MPType = T2->getAs<MemberPointerType>();
2780 if (T1MPType && T2MPType &&
2781 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2782 QualType(T2MPType->getClass(), 0))) {
2783 T1 = T1MPType->getPointeeType();
2784 T2 = T2MPType->getPointeeType();
2785 return true;
2786 }
2787
2788 if (getLangOptions().ObjC1) {
2789 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2790 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2791 if (T1OPType && T2OPType) {
2792 T1 = T1OPType->getPointeeType();
2793 T2 = T2OPType->getPointeeType();
2794 return true;
2795 }
2796 }
2797
2798 // FIXME: Block pointers, too?
2799
2800 return false;
2801}
2802
Jay Foad39c79802011-01-12 09:06:06 +00002803DeclarationNameInfo
2804ASTContext::getNameForTemplate(TemplateName Name,
2805 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002806 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002807 // DNInfo work in progress: CHECKME: what about DNLoc?
2808 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2809
John McCall847e2a12009-11-24 18:42:40 +00002810 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002811 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002812 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002813 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2814 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002815 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002816 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2817 // DNInfo work in progress: FIXME: source locations?
2818 DeclarationNameLoc DNLoc;
2819 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2820 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2821 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002822 }
2823 }
2824
John McCalld28ae272009-12-02 08:04:21 +00002825 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2826 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002827 // DNInfo work in progress: CHECKME: what about DNLoc?
2828 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002829}
2830
Jay Foad39c79802011-01-12 09:06:06 +00002831TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002832 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2833 if (TemplateTemplateParmDecl *TTP
2834 = dyn_cast<TemplateTemplateParmDecl>(Template))
2835 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2836
2837 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002838 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002839 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002840
Douglas Gregor5590be02011-01-15 06:45:20 +00002841 if (SubstTemplateTemplateParmPackStorage *SubstPack
2842 = Name.getAsSubstTemplateTemplateParmPack()) {
2843 TemplateTemplateParmDecl *CanonParam
2844 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2845 TemplateArgument CanonArgPack
2846 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2847 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2848 }
2849
John McCalld28ae272009-12-02 08:04:21 +00002850 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002851
Douglas Gregor6bc50582009-05-07 06:41:52 +00002852 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2853 assert(DTN && "Non-dependent template names must refer to template decls.");
2854 return DTN->CanonicalTemplateName;
2855}
2856
Douglas Gregoradee3e32009-11-11 23:06:43 +00002857bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2858 X = getCanonicalTemplateName(X);
2859 Y = getCanonicalTemplateName(Y);
2860 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2861}
2862
Mike Stump11289f42009-09-09 15:08:12 +00002863TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00002864ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00002865 switch (Arg.getKind()) {
2866 case TemplateArgument::Null:
2867 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002868
Douglas Gregora8e02e72009-07-28 23:00:59 +00002869 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002870 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002871
Douglas Gregora8e02e72009-07-28 23:00:59 +00002872 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002873 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002874
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002875 case TemplateArgument::Template:
2876 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002877
2878 case TemplateArgument::TemplateExpansion:
2879 return TemplateArgument(getCanonicalTemplateName(
2880 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00002881 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002882
Douglas Gregora8e02e72009-07-28 23:00:59 +00002883 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002884 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002885 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002886
Douglas Gregora8e02e72009-07-28 23:00:59 +00002887 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002888 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002889
Douglas Gregora8e02e72009-07-28 23:00:59 +00002890 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00002891 if (Arg.pack_size() == 0)
2892 return Arg;
2893
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002894 TemplateArgument *CanonArgs
2895 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00002896 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002897 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002898 AEnd = Arg.pack_end();
2899 A != AEnd; (void)++A, ++Idx)
2900 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002901
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002902 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00002903 }
2904 }
2905
2906 // Silence GCC warning
2907 assert(false && "Unhandled template argument kind");
2908 return TemplateArgument();
2909}
2910
Douglas Gregor333489b2009-03-27 23:10:48 +00002911NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00002912ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00002913 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002914 return 0;
2915
2916 switch (NNS->getKind()) {
2917 case NestedNameSpecifier::Identifier:
2918 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002919 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002920 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2921 NNS->getAsIdentifier());
2922
2923 case NestedNameSpecifier::Namespace:
2924 // A namespace is canonical; build a nested-name-specifier with
2925 // this namespace and no prefix.
2926 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2927
2928 case NestedNameSpecifier::TypeSpec:
2929 case NestedNameSpecifier::TypeSpecWithTemplate: {
2930 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00002931
2932 // If we have some kind of dependent-named type (e.g., "typename T::type"),
2933 // break it apart into its prefix and identifier, then reconsititute those
2934 // as the canonical nested-name-specifier. This is required to canonicalize
2935 // a dependent nested-name-specifier involving typedefs of dependent-name
2936 // types, e.g.,
2937 // typedef typename T::type T1;
2938 // typedef typename T1::type T2;
2939 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
2940 NestedNameSpecifier *Prefix
2941 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
2942 return NestedNameSpecifier::Create(*this, Prefix,
2943 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
2944 }
2945
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00002946 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00002947 if (const DependentTemplateSpecializationType *DTST
2948 = T->getAs<DependentTemplateSpecializationType>()) {
2949 NestedNameSpecifier *Prefix
2950 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
2951 TemplateName Name
2952 = getDependentTemplateName(Prefix, DTST->getIdentifier());
2953 T = getTemplateSpecializationType(Name,
2954 DTST->getArgs(), DTST->getNumArgs());
2955 T = getCanonicalType(T);
2956 }
2957
2958 return NestedNameSpecifier::Create(*this, 0, false, T.getTypePtr());
Douglas Gregor333489b2009-03-27 23:10:48 +00002959 }
2960
2961 case NestedNameSpecifier::Global:
2962 // The global specifier is canonical and unique.
2963 return NNS;
2964 }
2965
2966 // Required to silence a GCC warning
2967 return 0;
2968}
2969
Chris Lattner7adf0762008-08-04 07:31:14 +00002970
Jay Foad39c79802011-01-12 09:06:06 +00002971const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00002972 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002973 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002974 // Handle the common positive case fast.
2975 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2976 return AT;
2977 }
Mike Stump11289f42009-09-09 15:08:12 +00002978
John McCall8ccfcb52009-09-24 19:53:00 +00002979 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002980 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002981 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002982 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002983
John McCall8ccfcb52009-09-24 19:53:00 +00002984 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002985 // implements C99 6.7.3p8: "If the specification of an array type includes
2986 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002987
Chris Lattner7adf0762008-08-04 07:31:14 +00002988 // If we get here, we either have type qualifiers on the type, or we have
2989 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002990 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002991
John McCall8ccfcb52009-09-24 19:53:00 +00002992 QualifierCollector Qs;
John McCall717d9b02010-12-10 11:01:00 +00002993 const Type *Ty = Qs.strip(T.getDesugaredType(*this));
Mike Stump11289f42009-09-09 15:08:12 +00002994
Chris Lattner7adf0762008-08-04 07:31:14 +00002995 // If we have a simple case, just return now.
2996 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002997 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002998 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002999
Chris Lattner7adf0762008-08-04 07:31:14 +00003000 // Otherwise, we have an array and we have qualifiers on it. Push the
3001 // qualifiers into the array element type and return a new array type.
3002 // Get the canonical version of the element with the extra qualifiers on it.
3003 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00003004 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00003005
Chris Lattner7adf0762008-08-04 07:31:14 +00003006 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3007 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3008 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003009 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003010 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3011 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3012 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003013 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003014
Mike Stump11289f42009-09-09 15:08:12 +00003015 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003016 = dyn_cast<DependentSizedArrayType>(ATy))
3017 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003018 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003019 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003020 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003021 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003022 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003023
Chris Lattner7adf0762008-08-04 07:31:14 +00003024 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003025 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003026 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003027 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003028 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003029 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003030}
3031
Chris Lattnera21ad802008-04-02 05:18:44 +00003032/// getArrayDecayedType - Return the properly qualified result of decaying the
3033/// specified array type to a pointer. This operation is non-trivial when
3034/// handling typedefs etc. The canonical type of "T" must be an array type,
3035/// this returns a pointer to a properly qualified element of the array.
3036///
3037/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003038QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003039 // Get the element type with 'getAsArrayType' so that we don't lose any
3040 // typedefs in the element type of the array. This also handles propagation
3041 // of type qualifiers from the array type into the element type if present
3042 // (C99 6.7.3p8).
3043 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3044 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003045
Chris Lattner7adf0762008-08-04 07:31:14 +00003046 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003047
3048 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003049 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003050}
3051
Jay Foad39c79802011-01-12 09:06:06 +00003052QualType ASTContext::getBaseElementType(QualType QT) const {
John McCall8ccfcb52009-09-24 19:53:00 +00003053 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003054 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
3055 QT = AT->getElementType();
John McCall717d9b02010-12-10 11:01:00 +00003056 return Qs.apply(*this, QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003057}
3058
Jay Foad39c79802011-01-12 09:06:06 +00003059QualType ASTContext::getBaseElementType(const ArrayType *AT) const {
Anders Carlsson4bf82142009-09-25 01:23:32 +00003060 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003061
Anders Carlsson4bf82142009-09-25 01:23:32 +00003062 if (const ArrayType *AT = getAsArrayType(ElemTy))
3063 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00003064
Anders Carlssone0808df2008-12-21 03:44:36 +00003065 return ElemTy;
3066}
3067
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003068/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003069uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003070ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3071 uint64_t ElementCount = 1;
3072 do {
3073 ElementCount *= CA->getSize().getZExtValue();
3074 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3075 } while (CA);
3076 return ElementCount;
3077}
3078
Steve Naroff0af91202007-04-27 21:51:21 +00003079/// getFloatingRank - Return a relative rank for floating point types.
3080/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003081static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003082 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003083 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003084
John McCall9dd450b2009-09-21 23:43:11 +00003085 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3086 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003087 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003088 case BuiltinType::Float: return FloatRank;
3089 case BuiltinType::Double: return DoubleRank;
3090 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003091 }
3092}
3093
Mike Stump11289f42009-09-09 15:08:12 +00003094/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3095/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003096/// 'typeDomain' is a real floating point or complex type.
3097/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003098QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3099 QualType Domain) const {
3100 FloatingRank EltRank = getFloatingRank(Size);
3101 if (Domain->isComplexType()) {
3102 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003103 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003104 case FloatRank: return FloatComplexTy;
3105 case DoubleRank: return DoubleComplexTy;
3106 case LongDoubleRank: return LongDoubleComplexTy;
3107 }
Steve Naroff0af91202007-04-27 21:51:21 +00003108 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003109
3110 assert(Domain->isRealFloatingType() && "Unknown domain!");
3111 switch (EltRank) {
3112 default: assert(0 && "getFloatingRank(): illegal value for rank");
3113 case FloatRank: return FloatTy;
3114 case DoubleRank: return DoubleTy;
3115 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003116 }
Steve Naroffe4718892007-04-27 18:30:00 +00003117}
3118
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003119/// getFloatingTypeOrder - Compare the rank of the two specified floating
3120/// point types, ignoring the domain of the type (i.e. 'double' ==
3121/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003122/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003123int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003124 FloatingRank LHSR = getFloatingRank(LHS);
3125 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003126
Chris Lattnerb90739d2008-04-06 23:38:49 +00003127 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003128 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003129 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003130 return 1;
3131 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003132}
3133
Chris Lattner76a00cf2008-04-06 22:59:24 +00003134/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3135/// routine will assert if passed a built-in type that isn't an integer or enum,
3136/// or if it is not canonicalized.
Jay Foad39c79802011-01-12 09:06:06 +00003137unsigned ASTContext::getIntegerRank(Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003138 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00003139 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003140 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003141
Chris Lattnerad3467e2010-12-25 23:25:43 +00003142 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3143 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003144 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3145
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003146 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3147 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3148
3149 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3150 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3151
Chris Lattner76a00cf2008-04-06 22:59:24 +00003152 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003153 default: assert(0 && "getIntegerRank(): not a built-in integer");
3154 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003155 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003156 case BuiltinType::Char_S:
3157 case BuiltinType::Char_U:
3158 case BuiltinType::SChar:
3159 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003160 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003161 case BuiltinType::Short:
3162 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003163 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003164 case BuiltinType::Int:
3165 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003166 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003167 case BuiltinType::Long:
3168 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003169 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003170 case BuiltinType::LongLong:
3171 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003172 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003173 case BuiltinType::Int128:
3174 case BuiltinType::UInt128:
3175 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003176 }
3177}
3178
Eli Friedman629ffb92009-08-20 04:21:42 +00003179/// \brief Whether this is a promotable bitfield reference according
3180/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3181///
3182/// \returns the type this bit-field will promote to, or NULL if no
3183/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003184QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003185 if (E->isTypeDependent() || E->isValueDependent())
3186 return QualType();
3187
Eli Friedman629ffb92009-08-20 04:21:42 +00003188 FieldDecl *Field = E->getBitField();
3189 if (!Field)
3190 return QualType();
3191
3192 QualType FT = Field->getType();
3193
3194 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3195 uint64_t BitWidth = BitWidthAP.getZExtValue();
3196 uint64_t IntSize = getTypeSize(IntTy);
3197 // GCC extension compatibility: if the bit-field size is less than or equal
3198 // to the size of int, it gets promoted no matter what its type is.
3199 // For instance, unsigned long bf : 4 gets promoted to signed int.
3200 if (BitWidth < IntSize)
3201 return IntTy;
3202
3203 if (BitWidth == IntSize)
3204 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3205
3206 // Types bigger than int are not subject to promotions, and therefore act
3207 // like the base type.
3208 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3209 // is ridiculous.
3210 return QualType();
3211}
3212
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003213/// getPromotedIntegerType - Returns the type that Promotable will
3214/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3215/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003216QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003217 assert(!Promotable.isNull());
3218 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003219 if (const EnumType *ET = Promotable->getAs<EnumType>())
3220 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003221 if (Promotable->isSignedIntegerType())
3222 return IntTy;
3223 uint64_t PromotableSize = getTypeSize(Promotable);
3224 uint64_t IntSize = getTypeSize(IntTy);
3225 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3226 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3227}
3228
Mike Stump11289f42009-09-09 15:08:12 +00003229/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003230/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003231/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003232int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003233 Type *LHSC = getCanonicalType(LHS).getTypePtr();
3234 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003235 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003236
Chris Lattner76a00cf2008-04-06 22:59:24 +00003237 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3238 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003239
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003240 unsigned LHSRank = getIntegerRank(LHSC);
3241 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003242
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003243 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3244 if (LHSRank == RHSRank) return 0;
3245 return LHSRank > RHSRank ? 1 : -1;
3246 }
Mike Stump11289f42009-09-09 15:08:12 +00003247
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003248 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3249 if (LHSUnsigned) {
3250 // If the unsigned [LHS] type is larger, return it.
3251 if (LHSRank >= RHSRank)
3252 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003253
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003254 // If the signed type can represent all values of the unsigned type, it
3255 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003256 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003257 return -1;
3258 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003259
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003260 // If the unsigned [RHS] type is larger, return it.
3261 if (RHSRank >= LHSRank)
3262 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003263
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003264 // If the signed type can represent all values of the unsigned type, it
3265 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003266 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003267 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003268}
Anders Carlsson98f07902007-08-17 05:31:46 +00003269
Anders Carlsson6d417272009-11-14 21:45:58 +00003270static RecordDecl *
Jay Foad39c79802011-01-12 09:06:06 +00003271CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
Anders Carlsson6d417272009-11-14 21:45:58 +00003272 SourceLocation L, IdentifierInfo *Id) {
3273 if (Ctx.getLangOptions().CPlusPlus)
3274 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3275 else
3276 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3277}
3278
Mike Stump11289f42009-09-09 15:08:12 +00003279// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003280QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003281 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003282 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003283 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003284 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003285 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003286
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003287 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003288
Anders Carlsson98f07902007-08-17 05:31:46 +00003289 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003290 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003291 // int flags;
3292 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003293 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003294 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003295 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003296 FieldTypes[3] = LongTy;
3297
Anders Carlsson98f07902007-08-17 05:31:46 +00003298 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003299 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003300 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003301 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003302 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003303 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003304 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003305 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003306 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003307 }
3308
Douglas Gregord5058122010-02-11 01:19:42 +00003309 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003310 }
Mike Stump11289f42009-09-09 15:08:12 +00003311
Anders Carlsson98f07902007-08-17 05:31:46 +00003312 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003313}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003314
Douglas Gregor512b0772009-04-23 22:29:11 +00003315void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003316 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003317 assert(Rec && "Invalid CFConstantStringType");
3318 CFConstantStringTypeDecl = Rec->getDecl();
3319}
3320
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003321// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003322QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003323 if (!NSConstantStringTypeDecl) {
3324 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003325 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003326 &Idents.get("__builtin_NSString"));
3327 NSConstantStringTypeDecl->startDefinition();
3328
3329 QualType FieldTypes[3];
3330
3331 // const int *isa;
3332 FieldTypes[0] = getPointerType(IntTy.withConst());
3333 // const char *str;
3334 FieldTypes[1] = getPointerType(CharTy.withConst());
3335 // unsigned int length;
3336 FieldTypes[2] = UnsignedIntTy;
3337
3338 // Create fields
3339 for (unsigned i = 0; i < 3; ++i) {
3340 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3341 SourceLocation(), 0,
3342 FieldTypes[i], /*TInfo=*/0,
3343 /*BitWidth=*/0,
3344 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003345 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003346 NSConstantStringTypeDecl->addDecl(Field);
3347 }
3348
3349 NSConstantStringTypeDecl->completeDefinition();
3350 }
3351
3352 return getTagDeclType(NSConstantStringTypeDecl);
3353}
3354
3355void ASTContext::setNSConstantStringType(QualType T) {
3356 const RecordType *Rec = T->getAs<RecordType>();
3357 assert(Rec && "Invalid NSConstantStringType");
3358 NSConstantStringTypeDecl = Rec->getDecl();
3359}
3360
Jay Foad39c79802011-01-12 09:06:06 +00003361QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003362 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003363 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003364 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003365 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003366 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003367
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003368 QualType FieldTypes[] = {
3369 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003370 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003371 getPointerType(UnsignedLongTy),
3372 getConstantArrayType(UnsignedLongTy,
3373 llvm::APInt(32, 5), ArrayType::Normal, 0)
3374 };
Mike Stump11289f42009-09-09 15:08:12 +00003375
Douglas Gregor91f84212008-12-11 16:49:14 +00003376 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003377 FieldDecl *Field = FieldDecl::Create(*this,
3378 ObjCFastEnumerationStateTypeDecl,
3379 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003380 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003381 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003382 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003383 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003384 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003385 }
Mike Stump11289f42009-09-09 15:08:12 +00003386
Douglas Gregord5058122010-02-11 01:19:42 +00003387 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003388 }
Mike Stump11289f42009-09-09 15:08:12 +00003389
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003390 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3391}
3392
Jay Foad39c79802011-01-12 09:06:06 +00003393QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003394 if (BlockDescriptorType)
3395 return getTagDeclType(BlockDescriptorType);
3396
3397 RecordDecl *T;
3398 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003399 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003400 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003401 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003402
3403 QualType FieldTypes[] = {
3404 UnsignedLongTy,
3405 UnsignedLongTy,
3406 };
3407
3408 const char *FieldNames[] = {
3409 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003410 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003411 };
3412
3413 for (size_t i = 0; i < 2; ++i) {
3414 FieldDecl *Field = FieldDecl::Create(*this,
3415 T,
3416 SourceLocation(),
3417 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003418 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003419 /*BitWidth=*/0,
3420 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003421 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003422 T->addDecl(Field);
3423 }
3424
Douglas Gregord5058122010-02-11 01:19:42 +00003425 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003426
3427 BlockDescriptorType = T;
3428
3429 return getTagDeclType(BlockDescriptorType);
3430}
3431
3432void ASTContext::setBlockDescriptorType(QualType T) {
3433 const RecordType *Rec = T->getAs<RecordType>();
3434 assert(Rec && "Invalid BlockDescriptorType");
3435 BlockDescriptorType = Rec->getDecl();
3436}
3437
Jay Foad39c79802011-01-12 09:06:06 +00003438QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003439 if (BlockDescriptorExtendedType)
3440 return getTagDeclType(BlockDescriptorExtendedType);
3441
3442 RecordDecl *T;
3443 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003444 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003445 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003446 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003447
3448 QualType FieldTypes[] = {
3449 UnsignedLongTy,
3450 UnsignedLongTy,
3451 getPointerType(VoidPtrTy),
3452 getPointerType(VoidPtrTy)
3453 };
3454
3455 const char *FieldNames[] = {
3456 "reserved",
3457 "Size",
3458 "CopyFuncPtr",
3459 "DestroyFuncPtr"
3460 };
3461
3462 for (size_t i = 0; i < 4; ++i) {
3463 FieldDecl *Field = FieldDecl::Create(*this,
3464 T,
3465 SourceLocation(),
3466 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003467 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003468 /*BitWidth=*/0,
3469 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003470 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003471 T->addDecl(Field);
3472 }
3473
Douglas Gregord5058122010-02-11 01:19:42 +00003474 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003475
3476 BlockDescriptorExtendedType = T;
3477
3478 return getTagDeclType(BlockDescriptorExtendedType);
3479}
3480
3481void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3482 const RecordType *Rec = T->getAs<RecordType>();
3483 assert(Rec && "Invalid BlockDescriptorType");
3484 BlockDescriptorExtendedType = Rec->getDecl();
3485}
3486
Jay Foad39c79802011-01-12 09:06:06 +00003487bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003488 if (Ty->isBlockPointerType())
3489 return true;
3490 if (isObjCNSObjectType(Ty))
3491 return true;
3492 if (Ty->isObjCObjectPointerType())
3493 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003494 if (getLangOptions().CPlusPlus) {
3495 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3496 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3497 return RD->hasConstCopyConstructor(*this);
3498
3499 }
3500 }
Mike Stump94967902009-10-21 18:16:27 +00003501 return false;
3502}
3503
Jay Foad39c79802011-01-12 09:06:06 +00003504QualType
3505ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003506 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003507 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003508 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003509 // unsigned int __flags;
3510 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003511 // void *__copy_helper; // as needed
3512 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003513 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003514 // } *
3515
Mike Stump94967902009-10-21 18:16:27 +00003516 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3517
3518 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003519 llvm::SmallString<36> Name;
3520 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3521 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003522 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003523 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003524 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003525 T->startDefinition();
3526 QualType Int32Ty = IntTy;
3527 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3528 QualType FieldTypes[] = {
3529 getPointerType(VoidPtrTy),
3530 getPointerType(getTagDeclType(T)),
3531 Int32Ty,
3532 Int32Ty,
3533 getPointerType(VoidPtrTy),
3534 getPointerType(VoidPtrTy),
3535 Ty
3536 };
3537
Daniel Dunbar56df9772010-08-17 22:39:59 +00003538 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003539 "__isa",
3540 "__forwarding",
3541 "__flags",
3542 "__size",
3543 "__copy_helper",
3544 "__destroy_helper",
3545 DeclName,
3546 };
3547
3548 for (size_t i = 0; i < 7; ++i) {
3549 if (!HasCopyAndDispose && i >=4 && i <= 5)
3550 continue;
3551 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3552 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003553 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003554 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003555 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003556 T->addDecl(Field);
3557 }
3558
Douglas Gregord5058122010-02-11 01:19:42 +00003559 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003560
3561 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003562}
3563
3564
3565QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003566 bool BlockHasCopyDispose,
Jay Foad39c79802011-01-12 09:06:06 +00003567 llvm::SmallVectorImpl<const Expr *> &Layout) const {
John McCall87fe5d52010-05-20 01:18:31 +00003568
Mike Stumpd0153282009-10-20 02:12:22 +00003569 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003570 llvm::SmallString<36> Name;
3571 llvm::raw_svector_ostream(Name) << "__block_literal_"
3572 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003573 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003574 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003575 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003576 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003577 QualType FieldTypes[] = {
3578 getPointerType(VoidPtrTy),
3579 IntTy,
3580 IntTy,
3581 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003582 (BlockHasCopyDispose ?
3583 getPointerType(getBlockDescriptorExtendedType()) :
3584 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003585 };
3586
3587 const char *FieldNames[] = {
3588 "__isa",
3589 "__flags",
3590 "__reserved",
3591 "__FuncPtr",
3592 "__descriptor"
3593 };
3594
3595 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003596 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003597 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003598 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003599 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003600 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003601 T->addDecl(Field);
3602 }
3603
John McCall87fe5d52010-05-20 01:18:31 +00003604 for (unsigned i = 0; i < Layout.size(); ++i) {
3605 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003606
John McCall87fe5d52010-05-20 01:18:31 +00003607 QualType FieldType = E->getType();
3608 IdentifierInfo *FieldName = 0;
3609 if (isa<CXXThisExpr>(E)) {
3610 FieldName = &Idents.get("this");
3611 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3612 const ValueDecl *D = BDRE->getDecl();
3613 FieldName = D->getIdentifier();
3614 if (BDRE->isByRef())
Daniel Dunbar56df9772010-08-17 22:39:59 +00003615 FieldType = BuildByRefType(D->getName(), FieldType);
John McCall87fe5d52010-05-20 01:18:31 +00003616 } else {
3617 // Padding.
3618 assert(isa<ConstantArrayType>(FieldType) &&
3619 isa<DeclRefExpr>(E) &&
3620 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3621 "doesn't match characteristics of padding decl");
3622 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003623
3624 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003625 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003626 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003627 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003628 T->addDecl(Field);
3629 }
3630
Douglas Gregord5058122010-02-11 01:19:42 +00003631 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003632
3633 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003634}
3635
Douglas Gregor512b0772009-04-23 22:29:11 +00003636void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003637 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003638 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3639 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3640}
3641
Anders Carlsson18acd442007-10-29 06:33:42 +00003642// This returns true if a type has been typedefed to BOOL:
3643// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003644static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003645 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003646 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3647 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003648
Anders Carlssond8499822007-10-29 05:01:08 +00003649 return false;
3650}
3651
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003652/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003653/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003654CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003655 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003656
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003657 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003658 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003659 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003660 // Treat arrays as pointers, since that's how they're passed in.
3661 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003662 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003663 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003664}
3665
3666static inline
3667std::string charUnitsToString(const CharUnits &CU) {
3668 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003669}
3670
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003671/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003672/// declaration.
3673void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
Jay Foad39c79802011-01-12 09:06:06 +00003674 std::string& S) const {
David Chisnall950a9512009-11-17 19:33:30 +00003675 const BlockDecl *Decl = Expr->getBlockDecl();
3676 QualType BlockTy =
3677 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3678 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003679 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003680 // Compute size of all parameters.
3681 // Start with computing size of a pointer in number of bytes.
3682 // FIXME: There might(should) be a better way of doing this computation!
3683 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003684 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3685 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003686 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003687 E = Decl->param_end(); PI != E; ++PI) {
3688 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003689 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003690 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003691 ParmOffset += sz;
3692 }
3693 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003694 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003695 // Block pointer and offset.
3696 S += "@?0";
3697 ParmOffset = PtrSize;
3698
3699 // Argument types.
3700 ParmOffset = PtrSize;
3701 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3702 Decl->param_end(); PI != E; ++PI) {
3703 ParmVarDecl *PVDecl = *PI;
3704 QualType PType = PVDecl->getOriginalType();
3705 if (const ArrayType *AT =
3706 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3707 // Use array's original type only if it has known number of
3708 // elements.
3709 if (!isa<ConstantArrayType>(AT))
3710 PType = PVDecl->getType();
3711 } else if (PType->isFunctionType())
3712 PType = PVDecl->getType();
3713 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003714 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003715 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003716 }
3717}
3718
David Chisnall50e4eba2010-12-30 14:05:53 +00003719void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3720 std::string& S) {
3721 // Encode result type.
3722 getObjCEncodingForType(Decl->getResultType(), S);
3723 CharUnits ParmOffset;
3724 // Compute size of all parameters.
3725 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3726 E = Decl->param_end(); PI != E; ++PI) {
3727 QualType PType = (*PI)->getType();
3728 CharUnits sz = getObjCEncodingTypeSize(PType);
3729 assert (sz.isPositive() &&
3730 "getObjCEncodingForMethodDecl - Incomplete param type");
3731 ParmOffset += sz;
3732 }
3733 S += charUnitsToString(ParmOffset);
3734 ParmOffset = CharUnits::Zero();
3735
3736 // Argument types.
3737 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3738 E = Decl->param_end(); PI != E; ++PI) {
3739 ParmVarDecl *PVDecl = *PI;
3740 QualType PType = PVDecl->getOriginalType();
3741 if (const ArrayType *AT =
3742 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3743 // Use array's original type only if it has known number of
3744 // elements.
3745 if (!isa<ConstantArrayType>(AT))
3746 PType = PVDecl->getType();
3747 } else if (PType->isFunctionType())
3748 PType = PVDecl->getType();
3749 getObjCEncodingForType(PType, S);
3750 S += charUnitsToString(ParmOffset);
3751 ParmOffset += getObjCEncodingTypeSize(PType);
3752 }
3753}
3754
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003755/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003756/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003757void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003758 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003759 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003760 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003761 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003762 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003763 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003764 // Compute size of all parameters.
3765 // Start with computing size of a pointer in number of bytes.
3766 // FIXME: There might(should) be a better way of doing this computation!
3767 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003768 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003769 // The first two arguments (self and _cmd) are pointers; account for
3770 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003771 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003772 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003773 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003774 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003775 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003776 assert (sz.isPositive() &&
3777 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003778 ParmOffset += sz;
3779 }
Ken Dyck40775002010-01-11 17:06:35 +00003780 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003781 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003782 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003783
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003784 // Argument types.
3785 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003786 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003787 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003788 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003789 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003790 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003791 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3792 // Use array's original type only if it has known number of
3793 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003794 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003795 PType = PVDecl->getType();
3796 } else if (PType->isFunctionType())
3797 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003798 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003799 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003800 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003801 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003802 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003803 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003804 }
3805}
3806
Daniel Dunbar4932b362008-08-28 04:38:10 +00003807/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003808/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003809/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3810/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003811/// Property attributes are stored as a comma-delimited C string. The simple
3812/// attributes readonly and bycopy are encoded as single characters. The
3813/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3814/// encoded as single characters, followed by an identifier. Property types
3815/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003816/// these attributes are defined by the following enumeration:
3817/// @code
3818/// enum PropertyAttributes {
3819/// kPropertyReadOnly = 'R', // property is read-only.
3820/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3821/// kPropertyByref = '&', // property is a reference to the value last assigned
3822/// kPropertyDynamic = 'D', // property is dynamic
3823/// kPropertyGetter = 'G', // followed by getter selector name
3824/// kPropertySetter = 'S', // followed by setter selector name
3825/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3826/// kPropertyType = 't' // followed by old-style type encoding.
3827/// kPropertyWeak = 'W' // 'weak' property
3828/// kPropertyStrong = 'P' // property GC'able
3829/// kPropertyNonAtomic = 'N' // property non-atomic
3830/// };
3831/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003832void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003833 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003834 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003835 // Collect information from the property implementation decl(s).
3836 bool Dynamic = false;
3837 ObjCPropertyImplDecl *SynthesizePID = 0;
3838
3839 // FIXME: Duplicated code due to poor abstraction.
3840 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003841 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003842 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3843 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003844 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003845 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003846 ObjCPropertyImplDecl *PID = *i;
3847 if (PID->getPropertyDecl() == PD) {
3848 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3849 Dynamic = true;
3850 } else {
3851 SynthesizePID = PID;
3852 }
3853 }
3854 }
3855 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003856 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003857 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003858 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003859 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003860 ObjCPropertyImplDecl *PID = *i;
3861 if (PID->getPropertyDecl() == PD) {
3862 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3863 Dynamic = true;
3864 } else {
3865 SynthesizePID = PID;
3866 }
3867 }
Mike Stump11289f42009-09-09 15:08:12 +00003868 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003869 }
3870 }
3871
3872 // FIXME: This is not very efficient.
3873 S = "T";
3874
3875 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003876 // GCC has some special rules regarding encoding of properties which
3877 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003878 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003879 true /* outermost type */,
3880 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003881
3882 if (PD->isReadOnly()) {
3883 S += ",R";
3884 } else {
3885 switch (PD->getSetterKind()) {
3886 case ObjCPropertyDecl::Assign: break;
3887 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003888 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003889 }
3890 }
3891
3892 // It really isn't clear at all what this means, since properties
3893 // are "dynamic by default".
3894 if (Dynamic)
3895 S += ",D";
3896
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003897 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3898 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003899
Daniel Dunbar4932b362008-08-28 04:38:10 +00003900 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3901 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003902 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003903 }
3904
3905 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3906 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003907 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003908 }
3909
3910 if (SynthesizePID) {
3911 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3912 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003913 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003914 }
3915
3916 // FIXME: OBJCGC: weak & strong
3917}
3918
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003919/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003920/// Another legacy compatibility encoding: 32-bit longs are encoded as
3921/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003922/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3923///
3924void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003925 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003926 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00003927 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003928 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003929 else
Jay Foad39c79802011-01-12 09:06:06 +00003930 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003931 PointeeTy = IntTy;
3932 }
3933 }
3934}
3935
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003936void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00003937 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003938 // We follow the behavior of gcc, expanding structures which are
3939 // directly pointed to, and expanding embedded structures. Note that
3940 // these rules are sufficient to prevent recursive encoding of the
3941 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003942 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003943 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003944}
3945
David Chisnallb190a2c2010-06-04 01:10:52 +00003946static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3947 switch (T->getAs<BuiltinType>()->getKind()) {
3948 default: assert(0 && "Unhandled builtin type kind");
3949 case BuiltinType::Void: return 'v';
3950 case BuiltinType::Bool: return 'B';
3951 case BuiltinType::Char_U:
3952 case BuiltinType::UChar: return 'C';
3953 case BuiltinType::UShort: return 'S';
3954 case BuiltinType::UInt: return 'I';
3955 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00003956 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003957 case BuiltinType::UInt128: return 'T';
3958 case BuiltinType::ULongLong: return 'Q';
3959 case BuiltinType::Char_S:
3960 case BuiltinType::SChar: return 'c';
3961 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00003962 case BuiltinType::WChar_S:
3963 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00003964 case BuiltinType::Int: return 'i';
3965 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00003966 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003967 case BuiltinType::LongLong: return 'q';
3968 case BuiltinType::Int128: return 't';
3969 case BuiltinType::Float: return 'f';
3970 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00003971 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00003972 }
3973}
3974
Jay Foad39c79802011-01-12 09:06:06 +00003975static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003976 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003977 const Expr *E = FD->getBitWidth();
3978 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003979 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003980 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3981 // The GNU runtime requires more information; bitfields are encoded as b,
3982 // then the offset (in bits) of the first element, then the type of the
3983 // bitfield, then the size in bits. For example, in this structure:
3984 //
3985 // struct
3986 // {
3987 // int integer;
3988 // int flags:2;
3989 // };
3990 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3991 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3992 // information is not especially sensible, but we're stuck with it for
3993 // compatibility with GCC, although providing it breaks anything that
3994 // actually uses runtime introspection and wants to work on both runtimes...
3995 if (!Ctx->getLangOptions().NeXTRuntime) {
3996 const RecordDecl *RD = FD->getParent();
3997 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3998 // FIXME: This same linear search is also used in ExprConstant - it might
3999 // be better if the FieldDecl stored its offset. We'd be increasing the
4000 // size of the object slightly, but saving some time every time it is used.
4001 unsigned i = 0;
4002 for (RecordDecl::field_iterator Field = RD->field_begin(),
4003 FieldEnd = RD->field_end();
4004 Field != FieldEnd; (void)++Field, ++i) {
4005 if (*Field == FD)
4006 break;
4007 }
4008 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004009 if (T->isEnumeralType())
4010 S += 'i';
4011 else
Jay Foad39c79802011-01-12 09:06:06 +00004012 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004013 }
4014 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004015 S += llvm::utostr(N);
4016}
4017
Daniel Dunbar07d07852009-10-18 21:17:35 +00004018// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004019void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4020 bool ExpandPointedToStructures,
4021 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004022 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004023 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00004024 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004025 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004026 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004027 return EncodeBitField(this, S, T, FD);
4028 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004029 return;
4030 }
Mike Stump11289f42009-09-09 15:08:12 +00004031
John McCall9dd450b2009-09-21 23:43:11 +00004032 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004033 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004034 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004035 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004036 return;
4037 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004038
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004039 // encoding for pointer or r3eference types.
4040 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004041 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004042 if (PT->isObjCSelType()) {
4043 S += ':';
4044 return;
4045 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004046 PointeeTy = PT->getPointeeType();
4047 }
4048 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4049 PointeeTy = RT->getPointeeType();
4050 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004051 bool isReadOnly = false;
4052 // For historical/compatibility reasons, the read-only qualifier of the
4053 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4054 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004055 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004056 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004057 if (OutermostType && T.isConstQualified()) {
4058 isReadOnly = true;
4059 S += 'r';
4060 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004061 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004062 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004063 while (P->getAs<PointerType>())
4064 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004065 if (P.isConstQualified()) {
4066 isReadOnly = true;
4067 S += 'r';
4068 }
4069 }
4070 if (isReadOnly) {
4071 // Another legacy compatibility encoding. Some ObjC qualifier and type
4072 // combinations need to be rearranged.
4073 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004074 if (llvm::StringRef(S).endswith("nr"))
4075 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004076 }
Mike Stump11289f42009-09-09 15:08:12 +00004077
Anders Carlssond8499822007-10-29 05:01:08 +00004078 if (PointeeTy->isCharType()) {
4079 // char pointer types should be encoded as '*' unless it is a
4080 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004081 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004082 S += '*';
4083 return;
4084 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004085 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004086 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4087 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4088 S += '#';
4089 return;
4090 }
4091 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4092 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4093 S += '@';
4094 return;
4095 }
4096 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004097 }
Anders Carlssond8499822007-10-29 05:01:08 +00004098 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004099 getLegacyIntegralTypeEncoding(PointeeTy);
4100
Mike Stump11289f42009-09-09 15:08:12 +00004101 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004102 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004103 return;
4104 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004105
Chris Lattnere7cabb92009-07-13 00:10:46 +00004106 if (const ArrayType *AT =
4107 // Ignore type qualifiers etc.
4108 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004109 if (isa<IncompleteArrayType>(AT)) {
4110 // Incomplete arrays are encoded as a pointer to the array element.
4111 S += '^';
4112
Mike Stump11289f42009-09-09 15:08:12 +00004113 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004114 false, ExpandStructures, FD);
4115 } else {
4116 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004117
Anders Carlssond05f44b2009-02-22 01:38:57 +00004118 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4119 S += llvm::utostr(CAT->getSize().getZExtValue());
4120 else {
4121 //Variable length arrays are encoded as a regular array with 0 elements.
4122 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4123 S += '0';
4124 }
Mike Stump11289f42009-09-09 15:08:12 +00004125
4126 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004127 false, ExpandStructures, FD);
4128 S += ']';
4129 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004130 return;
4131 }
Mike Stump11289f42009-09-09 15:08:12 +00004132
John McCall9dd450b2009-09-21 23:43:11 +00004133 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004134 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004135 return;
4136 }
Mike Stump11289f42009-09-09 15:08:12 +00004137
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004138 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004139 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004140 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004141 // Anonymous structures print as '?'
4142 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4143 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004144 if (ClassTemplateSpecializationDecl *Spec
4145 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4146 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4147 std::string TemplateArgsStr
4148 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004149 TemplateArgs.data(),
4150 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004151 (*this).PrintingPolicy);
4152
4153 S += TemplateArgsStr;
4154 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004155 } else {
4156 S += '?';
4157 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004158 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004159 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004160 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4161 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004162 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004163 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004164 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004165 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004166 S += '"';
4167 }
Mike Stump11289f42009-09-09 15:08:12 +00004168
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004169 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004170 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004171 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004172 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004173 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004174 QualType qt = Field->getType();
4175 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004176 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004177 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004178 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004179 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004180 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004181 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004182 return;
4183 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004184
Chris Lattnere7cabb92009-07-13 00:10:46 +00004185 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004186 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004187 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004188 else
4189 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004190 return;
4191 }
Mike Stump11289f42009-09-09 15:08:12 +00004192
Chris Lattnere7cabb92009-07-13 00:10:46 +00004193 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004194 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004195 return;
4196 }
Mike Stump11289f42009-09-09 15:08:12 +00004197
John McCall8b07ec22010-05-15 11:32:37 +00004198 // Ignore protocol qualifiers when mangling at this level.
4199 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4200 T = OT->getBaseType();
4201
John McCall8ccfcb52009-09-24 19:53:00 +00004202 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004203 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004204 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004205 S += '{';
4206 const IdentifierInfo *II = OI->getIdentifier();
4207 S += II->getName();
4208 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004209 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4210 DeepCollectObjCIvars(OI, true, Ivars);
4211 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4212 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4213 if (Field->isBitField())
4214 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004215 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004216 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004217 }
4218 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004219 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004220 }
Mike Stump11289f42009-09-09 15:08:12 +00004221
John McCall9dd450b2009-09-21 23:43:11 +00004222 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004223 if (OPT->isObjCIdType()) {
4224 S += '@';
4225 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004226 }
Mike Stump11289f42009-09-09 15:08:12 +00004227
Steve Narofff0c86112009-10-28 22:03:49 +00004228 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4229 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4230 // Since this is a binary compatibility issue, need to consult with runtime
4231 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004232 S += '#';
4233 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004234 }
Mike Stump11289f42009-09-09 15:08:12 +00004235
Chris Lattnere7cabb92009-07-13 00:10:46 +00004236 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004237 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004238 ExpandPointedToStructures,
4239 ExpandStructures, FD);
4240 if (FD || EncodingProperty) {
4241 // Note that we do extended encoding of protocol qualifer list
4242 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004243 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004244 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4245 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004246 S += '<';
4247 S += (*I)->getNameAsString();
4248 S += '>';
4249 }
4250 S += '"';
4251 }
4252 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004253 }
Mike Stump11289f42009-09-09 15:08:12 +00004254
Chris Lattnere7cabb92009-07-13 00:10:46 +00004255 QualType PointeeTy = OPT->getPointeeType();
4256 if (!EncodingProperty &&
4257 isa<TypedefType>(PointeeTy.getTypePtr())) {
4258 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004259 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004260 // {...};
4261 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004262 getObjCEncodingForTypeImpl(PointeeTy, S,
4263 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004264 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004265 return;
4266 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004267
4268 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004269 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004270 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004271 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004272 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4273 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004274 S += '<';
4275 S += (*I)->getNameAsString();
4276 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004277 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004278 S += '"';
4279 }
4280 return;
4281 }
Mike Stump11289f42009-09-09 15:08:12 +00004282
John McCalla9e6e8d2010-05-17 23:56:34 +00004283 // gcc just blithely ignores member pointers.
4284 // TODO: maybe there should be a mangling for these
4285 if (T->getAs<MemberPointerType>())
4286 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004287
4288 if (T->isVectorType()) {
4289 // This matches gcc's encoding, even though technically it is
4290 // insufficient.
4291 // FIXME. We should do a better job than gcc.
4292 return;
4293 }
4294
Chris Lattnere7cabb92009-07-13 00:10:46 +00004295 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004296}
4297
Mike Stump11289f42009-09-09 15:08:12 +00004298void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004299 std::string& S) const {
4300 if (QT & Decl::OBJC_TQ_In)
4301 S += 'n';
4302 if (QT & Decl::OBJC_TQ_Inout)
4303 S += 'N';
4304 if (QT & Decl::OBJC_TQ_Out)
4305 S += 'o';
4306 if (QT & Decl::OBJC_TQ_Bycopy)
4307 S += 'O';
4308 if (QT & Decl::OBJC_TQ_Byref)
4309 S += 'R';
4310 if (QT & Decl::OBJC_TQ_Oneway)
4311 S += 'V';
4312}
4313
Chris Lattnere7cabb92009-07-13 00:10:46 +00004314void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004315 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004316
Anders Carlsson87c149b2007-10-11 01:00:40 +00004317 BuiltinVaListType = T;
4318}
4319
Chris Lattnere7cabb92009-07-13 00:10:46 +00004320void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004321 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004322}
4323
Chris Lattnere7cabb92009-07-13 00:10:46 +00004324void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004325 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004326}
4327
Chris Lattnere7cabb92009-07-13 00:10:46 +00004328void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004329 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004330}
4331
Chris Lattnere7cabb92009-07-13 00:10:46 +00004332void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004333 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004334}
4335
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004336void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004337 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004338 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004339
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004340 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004341}
4342
John McCalld28ae272009-12-02 08:04:21 +00004343/// \brief Retrieve the template name that corresponds to a non-empty
4344/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004345TemplateName
4346ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4347 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004348 unsigned size = End - Begin;
4349 assert(size > 1 && "set is not overloaded!");
4350
4351 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4352 size * sizeof(FunctionTemplateDecl*));
4353 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4354
4355 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004356 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004357 NamedDecl *D = *I;
4358 assert(isa<FunctionTemplateDecl>(D) ||
4359 (isa<UsingShadowDecl>(D) &&
4360 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4361 *Storage++ = D;
4362 }
4363
4364 return TemplateName(OT);
4365}
4366
Douglas Gregordc572a32009-03-30 22:58:21 +00004367/// \brief Retrieve the template name that represents a qualified
4368/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004369TemplateName
4370ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4371 bool TemplateKeyword,
4372 TemplateDecl *Template) const {
Douglas Gregorc42075a2010-02-04 18:10:26 +00004373 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004374 llvm::FoldingSetNodeID ID;
4375 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4376
4377 void *InsertPos = 0;
4378 QualifiedTemplateName *QTN =
4379 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4380 if (!QTN) {
4381 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4382 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4383 }
4384
4385 return TemplateName(QTN);
4386}
4387
4388/// \brief Retrieve the template name that represents a dependent
4389/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004390TemplateName
4391ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4392 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004393 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004394 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004395
4396 llvm::FoldingSetNodeID ID;
4397 DependentTemplateName::Profile(ID, NNS, Name);
4398
4399 void *InsertPos = 0;
4400 DependentTemplateName *QTN =
4401 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4402
4403 if (QTN)
4404 return TemplateName(QTN);
4405
4406 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4407 if (CanonNNS == NNS) {
4408 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4409 } else {
4410 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4411 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004412 DependentTemplateName *CheckQTN =
4413 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4414 assert(!CheckQTN && "Dependent type name canonicalization broken");
4415 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004416 }
4417
4418 DependentTemplateNames.InsertNode(QTN, InsertPos);
4419 return TemplateName(QTN);
4420}
4421
Douglas Gregor71395fa2009-11-04 00:56:37 +00004422/// \brief Retrieve the template name that represents a dependent
4423/// template name such as \c MetaFun::template operator+.
4424TemplateName
4425ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004426 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004427 assert((!NNS || NNS->isDependent()) &&
4428 "Nested name specifier must be dependent");
4429
4430 llvm::FoldingSetNodeID ID;
4431 DependentTemplateName::Profile(ID, NNS, Operator);
4432
4433 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004434 DependentTemplateName *QTN
4435 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004436
4437 if (QTN)
4438 return TemplateName(QTN);
4439
4440 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4441 if (CanonNNS == NNS) {
4442 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4443 } else {
4444 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4445 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004446
4447 DependentTemplateName *CheckQTN
4448 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4449 assert(!CheckQTN && "Dependent template name canonicalization broken");
4450 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004451 }
4452
4453 DependentTemplateNames.InsertNode(QTN, InsertPos);
4454 return TemplateName(QTN);
4455}
4456
Douglas Gregor5590be02011-01-15 06:45:20 +00004457TemplateName
4458ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4459 const TemplateArgument &ArgPack) const {
4460 ASTContext &Self = const_cast<ASTContext &>(*this);
4461 llvm::FoldingSetNodeID ID;
4462 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4463
4464 void *InsertPos = 0;
4465 SubstTemplateTemplateParmPackStorage *Subst
4466 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4467
4468 if (!Subst) {
4469 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4470 ArgPack.pack_size(),
4471 ArgPack.pack_begin());
4472 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4473 }
4474
4475 return TemplateName(Subst);
4476}
4477
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004478/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004479/// TargetInfo, produce the corresponding type. The unsigned @p Type
4480/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004481CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004482 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004483 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004484 case TargetInfo::SignedShort: return ShortTy;
4485 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4486 case TargetInfo::SignedInt: return IntTy;
4487 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4488 case TargetInfo::SignedLong: return LongTy;
4489 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4490 case TargetInfo::SignedLongLong: return LongLongTy;
4491 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4492 }
4493
4494 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004495 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004496}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004497
4498//===----------------------------------------------------------------------===//
4499// Type Predicates.
4500//===----------------------------------------------------------------------===//
4501
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004502/// isObjCNSObjectType - Return true if this is an NSObject object using
4503/// NSObject attribute on a c-style pointer type.
4504/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004505/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004506///
4507bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4508 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4509 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004510 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004511 return true;
4512 }
Mike Stump11289f42009-09-09 15:08:12 +00004513 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004514}
4515
Fariborz Jahanian96207692009-02-18 21:49:28 +00004516/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4517/// garbage collection attribute.
4518///
John McCall553d45a2011-01-12 00:34:59 +00004519Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4520 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4521 return Qualifiers::GCNone;
4522
4523 assert(getLangOptions().ObjC1);
4524 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4525
4526 // Default behaviour under objective-C's gc is for ObjC pointers
4527 // (or pointers to them) be treated as though they were declared
4528 // as __strong.
4529 if (GCAttrs == Qualifiers::GCNone) {
4530 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4531 return Qualifiers::Strong;
4532 else if (Ty->isPointerType())
4533 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4534 } else {
4535 // It's not valid to set GC attributes on anything that isn't a
4536 // pointer.
4537#ifndef NDEBUG
4538 QualType CT = Ty->getCanonicalTypeInternal();
4539 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4540 CT = AT->getElementType();
4541 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4542#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004543 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004544 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004545}
4546
Chris Lattner49af6a42008-04-07 06:51:04 +00004547//===----------------------------------------------------------------------===//
4548// Type Compatibility Testing
4549//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004550
Mike Stump11289f42009-09-09 15:08:12 +00004551/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004552/// compatible.
4553static bool areCompatVectorTypes(const VectorType *LHS,
4554 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004555 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004556 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004557 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004558}
4559
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004560bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4561 QualType SecondVec) {
4562 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4563 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4564
4565 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4566 return true;
4567
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004568 // Treat Neon vector types and most AltiVec vector types as if they are the
4569 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004570 const VectorType *First = FirstVec->getAs<VectorType>();
4571 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004572 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004573 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004574 First->getVectorKind() != VectorType::AltiVecPixel &&
4575 First->getVectorKind() != VectorType::AltiVecBool &&
4576 Second->getVectorKind() != VectorType::AltiVecPixel &&
4577 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004578 return true;
4579
4580 return false;
4581}
4582
Steve Naroff8e6aee52009-07-23 01:01:38 +00004583//===----------------------------------------------------------------------===//
4584// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4585//===----------------------------------------------------------------------===//
4586
4587/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4588/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004589bool
4590ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4591 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004592 if (lProto == rProto)
4593 return true;
4594 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4595 E = rProto->protocol_end(); PI != E; ++PI)
4596 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4597 return true;
4598 return false;
4599}
4600
Steve Naroff8e6aee52009-07-23 01:01:38 +00004601/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4602/// return true if lhs's protocols conform to rhs's protocol; false
4603/// otherwise.
4604bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4605 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4606 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4607 return false;
4608}
4609
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004610/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4611/// Class<p1, ...>.
4612bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4613 QualType rhs) {
4614 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4615 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4616 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4617
4618 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4619 E = lhsQID->qual_end(); I != E; ++I) {
4620 bool match = false;
4621 ObjCProtocolDecl *lhsProto = *I;
4622 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4623 E = rhsOPT->qual_end(); J != E; ++J) {
4624 ObjCProtocolDecl *rhsProto = *J;
4625 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4626 match = true;
4627 break;
4628 }
4629 }
4630 if (!match)
4631 return false;
4632 }
4633 return true;
4634}
4635
Steve Naroff8e6aee52009-07-23 01:01:38 +00004636/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4637/// ObjCQualifiedIDType.
4638bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4639 bool compare) {
4640 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004641 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004642 lhs->isObjCIdType() || lhs->isObjCClassType())
4643 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004644 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004645 rhs->isObjCIdType() || rhs->isObjCClassType())
4646 return true;
4647
4648 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004649 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004650
Steve Naroff8e6aee52009-07-23 01:01:38 +00004651 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004652
Steve Naroff8e6aee52009-07-23 01:01:38 +00004653 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004654 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004655 // make sure we check the class hierarchy.
4656 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4657 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4658 E = lhsQID->qual_end(); I != E; ++I) {
4659 // when comparing an id<P> on lhs with a static type on rhs,
4660 // see if static class implements all of id's protocols, directly or
4661 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004662 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004663 return false;
4664 }
4665 }
4666 // If there are no qualifiers and no interface, we have an 'id'.
4667 return true;
4668 }
Mike Stump11289f42009-09-09 15:08:12 +00004669 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004670 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4671 E = lhsQID->qual_end(); I != E; ++I) {
4672 ObjCProtocolDecl *lhsProto = *I;
4673 bool match = false;
4674
4675 // when comparing an id<P> on lhs with a static type on rhs,
4676 // see if static class implements all of id's protocols, directly or
4677 // through its super class and categories.
4678 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4679 E = rhsOPT->qual_end(); J != E; ++J) {
4680 ObjCProtocolDecl *rhsProto = *J;
4681 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4682 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4683 match = true;
4684 break;
4685 }
4686 }
Mike Stump11289f42009-09-09 15:08:12 +00004687 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004688 // make sure we check the class hierarchy.
4689 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4690 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4691 E = lhsQID->qual_end(); I != E; ++I) {
4692 // when comparing an id<P> on lhs with a static type on rhs,
4693 // see if static class implements all of id's protocols, directly or
4694 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004695 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004696 match = true;
4697 break;
4698 }
4699 }
4700 }
4701 if (!match)
4702 return false;
4703 }
Mike Stump11289f42009-09-09 15:08:12 +00004704
Steve Naroff8e6aee52009-07-23 01:01:38 +00004705 return true;
4706 }
Mike Stump11289f42009-09-09 15:08:12 +00004707
Steve Naroff8e6aee52009-07-23 01:01:38 +00004708 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4709 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4710
Mike Stump11289f42009-09-09 15:08:12 +00004711 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004712 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004713 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004714 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4715 E = lhsOPT->qual_end(); I != E; ++I) {
4716 ObjCProtocolDecl *lhsProto = *I;
4717 bool match = false;
4718
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004719 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004720 // see if static class implements all of id's protocols, directly or
4721 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004722 // First, lhs protocols in the qualifier list must be found, direct
4723 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004724 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4725 E = rhsQID->qual_end(); J != E; ++J) {
4726 ObjCProtocolDecl *rhsProto = *J;
4727 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4728 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4729 match = true;
4730 break;
4731 }
4732 }
4733 if (!match)
4734 return false;
4735 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004736
4737 // Static class's protocols, or its super class or category protocols
4738 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4739 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4740 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4741 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4742 // This is rather dubious but matches gcc's behavior. If lhs has
4743 // no type qualifier and its class has no static protocol(s)
4744 // assume that it is mismatch.
4745 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4746 return false;
4747 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4748 LHSInheritedProtocols.begin(),
4749 E = LHSInheritedProtocols.end(); I != E; ++I) {
4750 bool match = false;
4751 ObjCProtocolDecl *lhsProto = (*I);
4752 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4753 E = rhsQID->qual_end(); J != E; ++J) {
4754 ObjCProtocolDecl *rhsProto = *J;
4755 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4756 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4757 match = true;
4758 break;
4759 }
4760 }
4761 if (!match)
4762 return false;
4763 }
4764 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004765 return true;
4766 }
4767 return false;
4768}
4769
Eli Friedman47f77112008-08-22 00:56:42 +00004770/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004771/// compatible for assignment from RHS to LHS. This handles validation of any
4772/// protocol qualifiers on the LHS or RHS.
4773///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004774bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4775 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004776 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4777 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4778
Steve Naroff1329fa02009-07-15 18:40:39 +00004779 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004780 if (LHS->isObjCUnqualifiedIdOrClass() ||
4781 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004782 return true;
4783
John McCall8b07ec22010-05-15 11:32:37 +00004784 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004785 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4786 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004787 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004788
4789 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4790 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4791 QualType(RHSOPT,0));
4792
John McCall8b07ec22010-05-15 11:32:37 +00004793 // If we have 2 user-defined types, fall into that path.
4794 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004795 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004796
Steve Naroff8e6aee52009-07-23 01:01:38 +00004797 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004798}
4799
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004800/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4801/// for providing type-safty for objective-c pointers used to pass/return
4802/// arguments in block literals. When passed as arguments, passing 'A*' where
4803/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4804/// not OK. For the return type, the opposite is not OK.
4805bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4806 const ObjCObjectPointerType *LHSOPT,
4807 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004808 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004809 return true;
4810
4811 if (LHSOPT->isObjCBuiltinType()) {
4812 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4813 }
4814
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004815 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004816 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4817 QualType(RHSOPT,0),
4818 false);
4819
4820 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4821 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4822 if (LHS && RHS) { // We have 2 user-defined types.
4823 if (LHS != RHS) {
4824 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4825 return false;
4826 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4827 return true;
4828 }
4829 else
4830 return true;
4831 }
4832 return false;
4833}
4834
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004835/// getIntersectionOfProtocols - This routine finds the intersection of set
4836/// of protocols inherited from two distinct objective-c pointer objects.
4837/// It is used to build composite qualifier list of the composite type of
4838/// the conditional expression involving two objective-c pointer objects.
4839static
4840void getIntersectionOfProtocols(ASTContext &Context,
4841 const ObjCObjectPointerType *LHSOPT,
4842 const ObjCObjectPointerType *RHSOPT,
4843 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4844
John McCall8b07ec22010-05-15 11:32:37 +00004845 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4846 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4847 assert(LHS->getInterface() && "LHS must have an interface base");
4848 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004849
4850 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4851 unsigned LHSNumProtocols = LHS->getNumProtocols();
4852 if (LHSNumProtocols > 0)
4853 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4854 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004855 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004856 Context.CollectInheritedProtocols(LHS->getInterface(),
4857 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004858 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4859 LHSInheritedProtocols.end());
4860 }
4861
4862 unsigned RHSNumProtocols = RHS->getNumProtocols();
4863 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004864 ObjCProtocolDecl **RHSProtocols =
4865 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004866 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4867 if (InheritedProtocolSet.count(RHSProtocols[i]))
4868 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4869 }
4870 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004871 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004872 Context.CollectInheritedProtocols(RHS->getInterface(),
4873 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004874 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4875 RHSInheritedProtocols.begin(),
4876 E = RHSInheritedProtocols.end(); I != E; ++I)
4877 if (InheritedProtocolSet.count((*I)))
4878 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004879 }
4880}
4881
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004882/// areCommonBaseCompatible - Returns common base class of the two classes if
4883/// one found. Note that this is O'2 algorithm. But it will be called as the
4884/// last type comparison in a ?-exp of ObjC pointer types before a
4885/// warning is issued. So, its invokation is extremely rare.
4886QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004887 const ObjCObjectPointerType *Lptr,
4888 const ObjCObjectPointerType *Rptr) {
4889 const ObjCObjectType *LHS = Lptr->getObjectType();
4890 const ObjCObjectType *RHS = Rptr->getObjectType();
4891 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4892 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4893 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004894 return QualType();
4895
John McCall8b07ec22010-05-15 11:32:37 +00004896 while ((LDecl = LDecl->getSuperClass())) {
4897 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004898 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004899 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4900 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4901
4902 QualType Result = QualType(LHS, 0);
4903 if (!Protocols.empty())
4904 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4905 Result = getObjCObjectPointerType(Result);
4906 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004907 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004908 }
4909
4910 return QualType();
4911}
4912
John McCall8b07ec22010-05-15 11:32:37 +00004913bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4914 const ObjCObjectType *RHS) {
4915 assert(LHS->getInterface() && "LHS is not an interface type");
4916 assert(RHS->getInterface() && "RHS is not an interface type");
4917
Chris Lattner49af6a42008-04-07 06:51:04 +00004918 // Verify that the base decls are compatible: the RHS must be a subclass of
4919 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004920 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004921 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004922
Chris Lattner49af6a42008-04-07 06:51:04 +00004923 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4924 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004925 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004926 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004927
Chris Lattner49af6a42008-04-07 06:51:04 +00004928 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4929 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004930 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004931 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004932
John McCall8b07ec22010-05-15 11:32:37 +00004933 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4934 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004935 LHSPI != LHSPE; LHSPI++) {
4936 bool RHSImplementsProtocol = false;
4937
4938 // If the RHS doesn't implement the protocol on the left, the types
4939 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004940 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4941 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004942 RHSPI != RHSPE; RHSPI++) {
4943 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004944 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004945 break;
4946 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004947 }
4948 // FIXME: For better diagnostics, consider passing back the protocol name.
4949 if (!RHSImplementsProtocol)
4950 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004951 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004952 // The RHS implements all protocols listed on the LHS.
4953 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004954}
4955
Steve Naroffb7605152009-02-12 17:52:19 +00004956bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4957 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004958 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4959 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004960
Steve Naroff7cae42b2009-07-10 23:34:53 +00004961 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004962 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004963
4964 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4965 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004966}
4967
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004968bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4969 return canAssignObjCInterfaces(
4970 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4971 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4972}
4973
Mike Stump11289f42009-09-09 15:08:12 +00004974/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004975/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004976/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004977/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004978bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4979 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004980 if (getLangOptions().CPlusPlus)
4981 return hasSameType(LHS, RHS);
4982
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004983 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00004984}
4985
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004986bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4987 return !mergeTypes(LHS, RHS, true).isNull();
4988}
4989
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004990/// mergeTransparentUnionType - if T is a transparent union type and a member
4991/// of T is compatible with SubType, return the merged type, else return
4992/// QualType()
4993QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
4994 bool OfBlockPointer,
4995 bool Unqualified) {
4996 if (const RecordType *UT = T->getAsUnionType()) {
4997 RecordDecl *UD = UT->getDecl();
4998 if (UD->hasAttr<TransparentUnionAttr>()) {
4999 for (RecordDecl::field_iterator it = UD->field_begin(),
5000 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005001 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005002 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5003 if (!MT.isNull())
5004 return MT;
5005 }
5006 }
5007 }
5008
5009 return QualType();
5010}
5011
5012/// mergeFunctionArgumentTypes - merge two types which appear as function
5013/// argument types
5014QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5015 bool OfBlockPointer,
5016 bool Unqualified) {
5017 // GNU extension: two types are compatible if they appear as a function
5018 // argument, one of the types is a transparent union type and the other
5019 // type is compatible with a union member
5020 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5021 Unqualified);
5022 if (!lmerge.isNull())
5023 return lmerge;
5024
5025 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5026 Unqualified);
5027 if (!rmerge.isNull())
5028 return rmerge;
5029
5030 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5031}
5032
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005033QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005034 bool OfBlockPointer,
5035 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005036 const FunctionType *lbase = lhs->getAs<FunctionType>();
5037 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005038 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5039 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005040 bool allLTypes = true;
5041 bool allRTypes = true;
5042
5043 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005044 QualType retType;
5045 if (OfBlockPointer)
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005046 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
5047 Unqualified);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005048 else
John McCall8c6b56f2010-12-15 01:06:38 +00005049 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5050 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005051 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005052
5053 if (Unqualified)
5054 retType = retType.getUnqualifiedType();
5055
5056 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5057 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5058 if (Unqualified) {
5059 LRetType = LRetType.getUnqualifiedType();
5060 RRetType = RRetType.getUnqualifiedType();
5061 }
5062
5063 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005064 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005065 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005066 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005067
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005068 // FIXME: double check this
5069 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5070 // rbase->getRegParmAttr() != 0 &&
5071 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005072 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5073 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005074
Douglas Gregor8c940862010-01-18 17:14:39 +00005075 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005076 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005077 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005078
John McCall8c6b56f2010-12-15 01:06:38 +00005079 // Regparm is part of the calling convention.
5080 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5081 return QualType();
5082
5083 // It's noreturn if either type is.
5084 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5085 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5086 if (NoReturn != lbaseInfo.getNoReturn())
5087 allLTypes = false;
5088 if (NoReturn != rbaseInfo.getNoReturn())
5089 allRTypes = false;
5090
5091 FunctionType::ExtInfo einfo(NoReturn,
5092 lbaseInfo.getRegParm(),
5093 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00005094
Eli Friedman47f77112008-08-22 00:56:42 +00005095 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005096 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5097 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005098 unsigned lproto_nargs = lproto->getNumArgs();
5099 unsigned rproto_nargs = rproto->getNumArgs();
5100
5101 // Compatible functions must have the same number of arguments
5102 if (lproto_nargs != rproto_nargs)
5103 return QualType();
5104
5105 // Variadic and non-variadic functions aren't compatible
5106 if (lproto->isVariadic() != rproto->isVariadic())
5107 return QualType();
5108
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005109 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5110 return QualType();
5111
Eli Friedman47f77112008-08-22 00:56:42 +00005112 // Check argument compatibility
5113 llvm::SmallVector<QualType, 10> types;
5114 for (unsigned i = 0; i < lproto_nargs; i++) {
5115 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5116 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005117 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5118 OfBlockPointer,
5119 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005120 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005121
5122 if (Unqualified)
5123 argtype = argtype.getUnqualifiedType();
5124
Eli Friedman47f77112008-08-22 00:56:42 +00005125 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005126 if (Unqualified) {
5127 largtype = largtype.getUnqualifiedType();
5128 rargtype = rargtype.getUnqualifiedType();
5129 }
5130
Chris Lattner465fa322008-10-05 17:34:18 +00005131 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5132 allLTypes = false;
5133 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5134 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005135 }
5136 if (allLTypes) return lhs;
5137 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005138
5139 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5140 EPI.ExtInfo = einfo;
5141 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005142 }
5143
5144 if (lproto) allRTypes = false;
5145 if (rproto) allLTypes = false;
5146
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005147 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005148 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005149 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005150 if (proto->isVariadic()) return QualType();
5151 // Check that the types are compatible with the types that
5152 // would result from default argument promotions (C99 6.7.5.3p15).
5153 // The only types actually affected are promotable integer
5154 // types and floats, which would be passed as a different
5155 // type depending on whether the prototype is visible.
5156 unsigned proto_nargs = proto->getNumArgs();
5157 for (unsigned i = 0; i < proto_nargs; ++i) {
5158 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005159
5160 // Look at the promotion type of enum types, since that is the type used
5161 // to pass enum values.
5162 if (const EnumType *Enum = argTy->getAs<EnumType>())
5163 argTy = Enum->getDecl()->getPromotionType();
5164
Eli Friedman47f77112008-08-22 00:56:42 +00005165 if (argTy->isPromotableIntegerType() ||
5166 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5167 return QualType();
5168 }
5169
5170 if (allLTypes) return lhs;
5171 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005172
5173 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5174 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005175 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005176 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005177 }
5178
5179 if (allLTypes) return lhs;
5180 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005181 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005182}
5183
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005184QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005185 bool OfBlockPointer,
5186 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005187 // C++ [expr]: If an expression initially has the type "reference to T", the
5188 // type is adjusted to "T" prior to any further analysis, the expression
5189 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005190 // expression is an lvalue unless the reference is an rvalue reference and
5191 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005192 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5193 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005194
5195 if (Unqualified) {
5196 LHS = LHS.getUnqualifiedType();
5197 RHS = RHS.getUnqualifiedType();
5198 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005199
Eli Friedman47f77112008-08-22 00:56:42 +00005200 QualType LHSCan = getCanonicalType(LHS),
5201 RHSCan = getCanonicalType(RHS);
5202
5203 // If two types are identical, they are compatible.
5204 if (LHSCan == RHSCan)
5205 return LHS;
5206
John McCall8ccfcb52009-09-24 19:53:00 +00005207 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005208 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5209 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005210 if (LQuals != RQuals) {
5211 // If any of these qualifiers are different, we have a type
5212 // mismatch.
5213 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5214 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5215 return QualType();
5216
5217 // Exactly one GC qualifier difference is allowed: __strong is
5218 // okay if the other type has no GC qualifier but is an Objective
5219 // C object pointer (i.e. implicitly strong by default). We fix
5220 // this by pretending that the unqualified type was actually
5221 // qualified __strong.
5222 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5223 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5224 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5225
5226 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5227 return QualType();
5228
5229 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5230 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5231 }
5232 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5233 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5234 }
Eli Friedman47f77112008-08-22 00:56:42 +00005235 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005236 }
5237
5238 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005239
Eli Friedmandcca6332009-06-01 01:22:52 +00005240 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5241 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005242
Chris Lattnerfd652912008-01-14 05:45:46 +00005243 // We want to consider the two function types to be the same for these
5244 // comparisons, just force one to the other.
5245 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5246 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005247
5248 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005249 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5250 LHSClass = Type::ConstantArray;
5251 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5252 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005253
John McCall8b07ec22010-05-15 11:32:37 +00005254 // ObjCInterfaces are just specialized ObjCObjects.
5255 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5256 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5257
Nate Begemance4d7fc2008-04-18 23:10:10 +00005258 // Canonicalize ExtVector -> Vector.
5259 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5260 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005261
Chris Lattner95554662008-04-07 05:43:21 +00005262 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005263 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005264 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005265 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005266 // Compatibility is based on the underlying type, not the promotion
5267 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005268 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005269 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5270 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005271 }
John McCall9dd450b2009-09-21 23:43:11 +00005272 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005273 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5274 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005275 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005276
Eli Friedman47f77112008-08-22 00:56:42 +00005277 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005278 }
Eli Friedman47f77112008-08-22 00:56:42 +00005279
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005280 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005281 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005282#define TYPE(Class, Base)
5283#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005284#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005285#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5286#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5287#include "clang/AST/TypeNodes.def"
5288 assert(false && "Non-canonical and dependent types shouldn't get here");
5289 return QualType();
5290
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005291 case Type::LValueReference:
5292 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005293 case Type::MemberPointer:
5294 assert(false && "C++ should never be in mergeTypes");
5295 return QualType();
5296
John McCall8b07ec22010-05-15 11:32:37 +00005297 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005298 case Type::IncompleteArray:
5299 case Type::VariableArray:
5300 case Type::FunctionProto:
5301 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005302 assert(false && "Types are eliminated above");
5303 return QualType();
5304
Chris Lattnerfd652912008-01-14 05:45:46 +00005305 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005306 {
5307 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005308 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5309 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005310 if (Unqualified) {
5311 LHSPointee = LHSPointee.getUnqualifiedType();
5312 RHSPointee = RHSPointee.getUnqualifiedType();
5313 }
5314 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5315 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005316 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005317 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005318 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005319 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005320 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005321 return getPointerType(ResultType);
5322 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005323 case Type::BlockPointer:
5324 {
5325 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005326 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5327 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005328 if (Unqualified) {
5329 LHSPointee = LHSPointee.getUnqualifiedType();
5330 RHSPointee = RHSPointee.getUnqualifiedType();
5331 }
5332 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5333 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005334 if (ResultType.isNull()) return QualType();
5335 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5336 return LHS;
5337 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5338 return RHS;
5339 return getBlockPointerType(ResultType);
5340 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005341 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005342 {
5343 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5344 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5345 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5346 return QualType();
5347
5348 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5349 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005350 if (Unqualified) {
5351 LHSElem = LHSElem.getUnqualifiedType();
5352 RHSElem = RHSElem.getUnqualifiedType();
5353 }
5354
5355 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005356 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005357 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5358 return LHS;
5359 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5360 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005361 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5362 ArrayType::ArraySizeModifier(), 0);
5363 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5364 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005365 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5366 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005367 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5368 return LHS;
5369 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5370 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005371 if (LVAT) {
5372 // FIXME: This isn't correct! But tricky to implement because
5373 // the array's size has to be the size of LHS, but the type
5374 // has to be different.
5375 return LHS;
5376 }
5377 if (RVAT) {
5378 // FIXME: This isn't correct! But tricky to implement because
5379 // the array's size has to be the size of RHS, but the type
5380 // has to be different.
5381 return RHS;
5382 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005383 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5384 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005385 return getIncompleteArrayType(ResultType,
5386 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005387 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005388 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005389 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005390 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005391 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005392 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005393 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005394 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005395 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005396 case Type::Complex:
5397 // Distinct complex types are incompatible.
5398 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005399 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005400 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005401 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5402 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005403 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005404 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005405 case Type::ObjCObject: {
5406 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005407 // FIXME: This should be type compatibility, e.g. whether
5408 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005409 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5410 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5411 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005412 return LHS;
5413
Eli Friedman47f77112008-08-22 00:56:42 +00005414 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005415 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005416 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005417 if (OfBlockPointer) {
5418 if (canAssignObjCInterfacesInBlockPointer(
5419 LHS->getAs<ObjCObjectPointerType>(),
5420 RHS->getAs<ObjCObjectPointerType>()))
5421 return LHS;
5422 return QualType();
5423 }
John McCall9dd450b2009-09-21 23:43:11 +00005424 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5425 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005426 return LHS;
5427
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005428 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005429 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005430 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005431
5432 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005433}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005434
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005435/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5436/// 'RHS' attributes and returns the merged version; including for function
5437/// return types.
5438QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5439 QualType LHSCan = getCanonicalType(LHS),
5440 RHSCan = getCanonicalType(RHS);
5441 // If two types are identical, they are compatible.
5442 if (LHSCan == RHSCan)
5443 return LHS;
5444 if (RHSCan->isFunctionType()) {
5445 if (!LHSCan->isFunctionType())
5446 return QualType();
5447 QualType OldReturnType =
5448 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5449 QualType NewReturnType =
5450 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5451 QualType ResReturnType =
5452 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5453 if (ResReturnType.isNull())
5454 return QualType();
5455 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5456 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5457 // In either case, use OldReturnType to build the new function type.
5458 const FunctionType *F = LHS->getAs<FunctionType>();
5459 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005460 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5461 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005462 QualType ResultType
5463 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005464 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005465 return ResultType;
5466 }
5467 }
5468 return QualType();
5469 }
5470
5471 // If the qualifiers are different, the types can still be merged.
5472 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5473 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5474 if (LQuals != RQuals) {
5475 // If any of these qualifiers are different, we have a type mismatch.
5476 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5477 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5478 return QualType();
5479
5480 // Exactly one GC qualifier difference is allowed: __strong is
5481 // okay if the other type has no GC qualifier but is an Objective
5482 // C object pointer (i.e. implicitly strong by default). We fix
5483 // this by pretending that the unqualified type was actually
5484 // qualified __strong.
5485 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5486 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5487 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5488
5489 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5490 return QualType();
5491
5492 if (GC_L == Qualifiers::Strong)
5493 return LHS;
5494 if (GC_R == Qualifiers::Strong)
5495 return RHS;
5496 return QualType();
5497 }
5498
5499 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5500 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5501 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5502 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5503 if (ResQT == LHSBaseQT)
5504 return LHS;
5505 if (ResQT == RHSBaseQT)
5506 return RHS;
5507 }
5508 return QualType();
5509}
5510
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005511//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005512// Integer Predicates
5513//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005514
Jay Foad39c79802011-01-12 09:06:06 +00005515unsigned ASTContext::getIntWidth(QualType T) const {
John McCall56774992009-12-09 09:09:27 +00005516 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005517 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005518 if (T->isBooleanType())
5519 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005520 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005521 return (unsigned)getTypeSize(T);
5522}
5523
5524QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005525 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005526
5527 // Turn <4 x signed int> -> <4 x unsigned int>
5528 if (const VectorType *VTy = T->getAs<VectorType>())
5529 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005530 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005531
5532 // For enums, we return the unsigned version of the base type.
5533 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005534 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005535
5536 const BuiltinType *BTy = T->getAs<BuiltinType>();
5537 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005538 switch (BTy->getKind()) {
5539 case BuiltinType::Char_S:
5540 case BuiltinType::SChar:
5541 return UnsignedCharTy;
5542 case BuiltinType::Short:
5543 return UnsignedShortTy;
5544 case BuiltinType::Int:
5545 return UnsignedIntTy;
5546 case BuiltinType::Long:
5547 return UnsignedLongTy;
5548 case BuiltinType::LongLong:
5549 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005550 case BuiltinType::Int128:
5551 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005552 default:
5553 assert(0 && "Unexpected signed integer type");
5554 return QualType();
5555 }
5556}
5557
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005558ExternalASTSource::~ExternalASTSource() { }
5559
5560void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00005561
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005562ASTMutationListener::~ASTMutationListener() { }
5563
Chris Lattnerecd79c62009-06-14 00:45:47 +00005564
5565//===----------------------------------------------------------------------===//
5566// Builtin Type Computation
5567//===----------------------------------------------------------------------===//
5568
5569/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005570/// pointer over the consumed characters. This returns the resultant type. If
5571/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5572/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5573/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005574///
5575/// RequiresICE is filled in on return to indicate whether the value is required
5576/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005577static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005578 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005579 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005580 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005581 // Modifiers.
5582 int HowLong = 0;
5583 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005584 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005585
Chris Lattnerdc226c22010-10-01 22:42:38 +00005586 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005587 bool Done = false;
5588 while (!Done) {
5589 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005590 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005591 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005592 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005593 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005594 case 'S':
5595 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5596 assert(!Signed && "Can't use 'S' modifier multiple times!");
5597 Signed = true;
5598 break;
5599 case 'U':
5600 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5601 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5602 Unsigned = true;
5603 break;
5604 case 'L':
5605 assert(HowLong <= 2 && "Can't have LLLL modifier");
5606 ++HowLong;
5607 break;
5608 }
5609 }
5610
5611 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005612
Chris Lattnerecd79c62009-06-14 00:45:47 +00005613 // Read the base type.
5614 switch (*Str++) {
5615 default: assert(0 && "Unknown builtin type letter!");
5616 case 'v':
5617 assert(HowLong == 0 && !Signed && !Unsigned &&
5618 "Bad modifiers used with 'v'!");
5619 Type = Context.VoidTy;
5620 break;
5621 case 'f':
5622 assert(HowLong == 0 && !Signed && !Unsigned &&
5623 "Bad modifiers used with 'f'!");
5624 Type = Context.FloatTy;
5625 break;
5626 case 'd':
5627 assert(HowLong < 2 && !Signed && !Unsigned &&
5628 "Bad modifiers used with 'd'!");
5629 if (HowLong)
5630 Type = Context.LongDoubleTy;
5631 else
5632 Type = Context.DoubleTy;
5633 break;
5634 case 's':
5635 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5636 if (Unsigned)
5637 Type = Context.UnsignedShortTy;
5638 else
5639 Type = Context.ShortTy;
5640 break;
5641 case 'i':
5642 if (HowLong == 3)
5643 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5644 else if (HowLong == 2)
5645 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5646 else if (HowLong == 1)
5647 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5648 else
5649 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5650 break;
5651 case 'c':
5652 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5653 if (Signed)
5654 Type = Context.SignedCharTy;
5655 else if (Unsigned)
5656 Type = Context.UnsignedCharTy;
5657 else
5658 Type = Context.CharTy;
5659 break;
5660 case 'b': // boolean
5661 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5662 Type = Context.BoolTy;
5663 break;
5664 case 'z': // size_t.
5665 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5666 Type = Context.getSizeType();
5667 break;
5668 case 'F':
5669 Type = Context.getCFConstantStringType();
5670 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005671 case 'G':
5672 Type = Context.getObjCIdType();
5673 break;
5674 case 'H':
5675 Type = Context.getObjCSelType();
5676 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005677 case 'a':
5678 Type = Context.getBuiltinVaListType();
5679 assert(!Type.isNull() && "builtin va list type not initialized!");
5680 break;
5681 case 'A':
5682 // This is a "reference" to a va_list; however, what exactly
5683 // this means depends on how va_list is defined. There are two
5684 // different kinds of va_list: ones passed by value, and ones
5685 // passed by reference. An example of a by-value va_list is
5686 // x86, where va_list is a char*. An example of by-ref va_list
5687 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5688 // we want this argument to be a char*&; for x86-64, we want
5689 // it to be a __va_list_tag*.
5690 Type = Context.getBuiltinVaListType();
5691 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005692 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005693 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005694 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005695 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005696 break;
5697 case 'V': {
5698 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005699 unsigned NumElements = strtoul(Str, &End, 10);
5700 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005701 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005702
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005703 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5704 RequiresICE, false);
5705 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005706
5707 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005708 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005709 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005710 break;
5711 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005712 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005713 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5714 false);
5715 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005716 Type = Context.getComplexType(ElementType);
5717 break;
5718 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005719 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005720 Type = Context.getFILEType();
5721 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005722 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005723 return QualType();
5724 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005725 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005726 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005727 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005728 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005729 else
5730 Type = Context.getjmp_bufType();
5731
Mike Stump2adb4da2009-07-28 23:47:15 +00005732 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005733 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005734 return QualType();
5735 }
5736 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005737 }
Mike Stump11289f42009-09-09 15:08:12 +00005738
Chris Lattnerdc226c22010-10-01 22:42:38 +00005739 // If there are modifiers and if we're allowed to parse them, go for it.
5740 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005741 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005742 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005743 default: Done = true; --Str; break;
5744 case '*':
5745 case '&': {
5746 // Both pointers and references can have their pointee types
5747 // qualified with an address space.
5748 char *End;
5749 unsigned AddrSpace = strtoul(Str, &End, 10);
5750 if (End != Str && AddrSpace != 0) {
5751 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5752 Str = End;
5753 }
5754 if (c == '*')
5755 Type = Context.getPointerType(Type);
5756 else
5757 Type = Context.getLValueReferenceType(Type);
5758 break;
5759 }
5760 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5761 case 'C':
5762 Type = Type.withConst();
5763 break;
5764 case 'D':
5765 Type = Context.getVolatileType(Type);
5766 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005767 }
5768 }
Chris Lattner84733392010-10-01 07:13:18 +00005769
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005770 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005771 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005772
Chris Lattnerecd79c62009-06-14 00:45:47 +00005773 return Type;
5774}
5775
5776/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005777QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005778 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005779 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005780 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005781
Chris Lattnerecd79c62009-06-14 00:45:47 +00005782 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005783
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005784 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005785 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005786 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5787 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005788 if (Error != GE_None)
5789 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005790
5791 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5792
Chris Lattnerecd79c62009-06-14 00:45:47 +00005793 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005794 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005795 if (Error != GE_None)
5796 return QualType();
5797
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005798 // If this argument is required to be an IntegerConstantExpression and the
5799 // caller cares, fill in the bitmask we return.
5800 if (RequiresICE && IntegerConstantArgs)
5801 *IntegerConstantArgs |= 1 << ArgTypes.size();
5802
Chris Lattnerecd79c62009-06-14 00:45:47 +00005803 // Do array -> pointer decay. The builtin should use the decayed type.
5804 if (Ty->isArrayType())
5805 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005806
Chris Lattnerecd79c62009-06-14 00:45:47 +00005807 ArgTypes.push_back(Ty);
5808 }
5809
5810 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5811 "'.' should only occur at end of builtin type list!");
5812
John McCall991eb4b2010-12-21 00:44:39 +00005813 FunctionType::ExtInfo EI;
5814 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5815
5816 bool Variadic = (TypeStr[0] == '.');
5817
5818 // We really shouldn't be making a no-proto type here, especially in C++.
5819 if (ArgTypes.empty() && Variadic)
5820 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005821
John McCalldb40c7f2010-12-14 08:05:40 +00005822 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005823 EPI.ExtInfo = EI;
5824 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00005825
5826 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005827}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005828
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005829GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5830 GVALinkage External = GVA_StrongExternal;
5831
5832 Linkage L = FD->getLinkage();
5833 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5834 FD->getType()->getLinkage() == UniqueExternalLinkage)
5835 L = UniqueExternalLinkage;
5836
5837 switch (L) {
5838 case NoLinkage:
5839 case InternalLinkage:
5840 case UniqueExternalLinkage:
5841 return GVA_Internal;
5842
5843 case ExternalLinkage:
5844 switch (FD->getTemplateSpecializationKind()) {
5845 case TSK_Undeclared:
5846 case TSK_ExplicitSpecialization:
5847 External = GVA_StrongExternal;
5848 break;
5849
5850 case TSK_ExplicitInstantiationDefinition:
5851 return GVA_ExplicitTemplateInstantiation;
5852
5853 case TSK_ExplicitInstantiationDeclaration:
5854 case TSK_ImplicitInstantiation:
5855 External = GVA_TemplateInstantiation;
5856 break;
5857 }
5858 }
5859
5860 if (!FD->isInlined())
5861 return External;
5862
5863 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5864 // GNU or C99 inline semantics. Determine whether this symbol should be
5865 // externally visible.
5866 if (FD->isInlineDefinitionExternallyVisible())
5867 return External;
5868
5869 // C99 inline semantics, where the symbol is not externally visible.
5870 return GVA_C99Inline;
5871 }
5872
5873 // C++0x [temp.explicit]p9:
5874 // [ Note: The intent is that an inline function that is the subject of
5875 // an explicit instantiation declaration will still be implicitly
5876 // instantiated when used so that the body can be considered for
5877 // inlining, but that no out-of-line copy of the inline function would be
5878 // generated in the translation unit. -- end note ]
5879 if (FD->getTemplateSpecializationKind()
5880 == TSK_ExplicitInstantiationDeclaration)
5881 return GVA_C99Inline;
5882
5883 return GVA_CXXInline;
5884}
5885
5886GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5887 // If this is a static data member, compute the kind of template
5888 // specialization. Otherwise, this variable is not part of a
5889 // template.
5890 TemplateSpecializationKind TSK = TSK_Undeclared;
5891 if (VD->isStaticDataMember())
5892 TSK = VD->getTemplateSpecializationKind();
5893
5894 Linkage L = VD->getLinkage();
5895 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5896 VD->getType()->getLinkage() == UniqueExternalLinkage)
5897 L = UniqueExternalLinkage;
5898
5899 switch (L) {
5900 case NoLinkage:
5901 case InternalLinkage:
5902 case UniqueExternalLinkage:
5903 return GVA_Internal;
5904
5905 case ExternalLinkage:
5906 switch (TSK) {
5907 case TSK_Undeclared:
5908 case TSK_ExplicitSpecialization:
5909 return GVA_StrongExternal;
5910
5911 case TSK_ExplicitInstantiationDeclaration:
5912 llvm_unreachable("Variable should not be instantiated");
5913 // Fall through to treat this like any other instantiation.
5914
5915 case TSK_ExplicitInstantiationDefinition:
5916 return GVA_ExplicitTemplateInstantiation;
5917
5918 case TSK_ImplicitInstantiation:
5919 return GVA_TemplateInstantiation;
5920 }
5921 }
5922
5923 return GVA_StrongExternal;
5924}
5925
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005926bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005927 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5928 if (!VD->isFileVarDecl())
5929 return false;
5930 } else if (!isa<FunctionDecl>(D))
5931 return false;
5932
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005933 // Weak references don't produce any output by themselves.
5934 if (D->hasAttr<WeakRefAttr>())
5935 return false;
5936
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005937 // Aliases and used decls are required.
5938 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5939 return true;
5940
5941 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5942 // Forward declarations aren't required.
5943 if (!FD->isThisDeclarationADefinition())
5944 return false;
5945
5946 // Constructors and destructors are required.
5947 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5948 return true;
5949
5950 // The key function for a class is required.
5951 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5952 const CXXRecordDecl *RD = MD->getParent();
5953 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5954 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5955 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5956 return true;
5957 }
5958 }
5959
5960 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5961
5962 // static, static inline, always_inline, and extern inline functions can
5963 // always be deferred. Normal inline functions can be deferred in C99/C++.
5964 // Implicit template instantiations can also be deferred in C++.
5965 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5966 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5967 return false;
5968 return true;
5969 }
5970
5971 const VarDecl *VD = cast<VarDecl>(D);
5972 assert(VD->isFileVarDecl() && "Expected file scoped var");
5973
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005974 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5975 return false;
5976
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005977 // Structs that have non-trivial constructors or destructors are required.
5978
5979 // FIXME: Handle references.
5980 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5981 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00005982 if (RD->hasDefinition() &&
5983 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005984 return true;
5985 }
5986 }
5987
5988 GVALinkage L = GetGVALinkageForVariable(VD);
5989 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5990 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5991 return false;
5992 }
5993
5994 return true;
5995}
Charles Davis53c59df2010-08-16 03:33:14 +00005996
Charles Davis99202b32010-11-09 18:04:24 +00005997CallingConv ASTContext::getDefaultMethodCallConv() {
5998 // Pass through to the C++ ABI object
5999 return ABI->getDefaultMethodCallConv();
6000}
6001
Jay Foad39c79802011-01-12 09:06:06 +00006002bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006003 // Pass through to the C++ ABI object
6004 return ABI->isNearlyEmpty(RD);
6005}
6006
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006007MangleContext *ASTContext::createMangleContext() {
6008 switch (Target.getCXXABI()) {
6009 case CXXABI_ARM:
6010 case CXXABI_Itanium:
6011 return createItaniumMangleContext(*this, getDiagnostics());
6012 case CXXABI_Microsoft:
6013 return createMicrosoftMangleContext(*this, getDiagnostics());
6014 }
6015 assert(0 && "Unsupported ABI");
6016 return 0;
6017}
6018
Charles Davis53c59df2010-08-16 03:33:14 +00006019CXXABI::~CXXABI() {}