blob: e1e6fd08aa20998372d4d382e1b772d80dacec2e [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Charles Davis53c59df2010-08-16 03:33:14 +000033#include "CXXABI.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000034
Chris Lattnerddc135e2006-11-10 06:34:16 +000035using namespace clang;
36
Douglas Gregor9672f922010-07-03 00:47:00 +000037unsigned ASTContext::NumImplicitDefaultConstructors;
38unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000039unsigned ASTContext::NumImplicitCopyConstructors;
40unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000041unsigned ASTContext::NumImplicitCopyAssignmentOperators;
42unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000043unsigned ASTContext::NumImplicitDestructors;
44unsigned ASTContext::NumImplicitDestructorsDeclared;
45
Steve Naroff0af91202007-04-27 21:51:21 +000046enum FloatingRank {
47 FloatRank, DoubleRank, LongDoubleRank
48};
49
Douglas Gregor7dbfb462010-06-16 21:09:37 +000050void
51ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
52 TemplateTemplateParmDecl *Parm) {
53 ID.AddInteger(Parm->getDepth());
54 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000055 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000056
57 TemplateParameterList *Params = Parm->getTemplateParameters();
58 ID.AddInteger(Params->size());
59 for (TemplateParameterList::const_iterator P = Params->begin(),
60 PEnd = Params->end();
61 P != PEnd; ++P) {
62 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
63 ID.AddInteger(0);
64 ID.AddBoolean(TTP->isParameterPack());
65 continue;
66 }
67
68 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
69 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000070 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000071 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
72 continue;
73 }
74
75 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
76 ID.AddInteger(2);
77 Profile(ID, TTP);
78 }
79}
80
81TemplateTemplateParmDecl *
82ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000083 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000084 // Check if we already have a canonical template template parameter.
85 llvm::FoldingSetNodeID ID;
86 CanonicalTemplateTemplateParm::Profile(ID, TTP);
87 void *InsertPos = 0;
88 CanonicalTemplateTemplateParm *Canonical
89 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
90 if (Canonical)
91 return Canonical->getParam();
92
93 // Build a canonical template parameter list.
94 TemplateParameterList *Params = TTP->getTemplateParameters();
95 llvm::SmallVector<NamedDecl *, 4> CanonParams;
96 CanonParams.reserve(Params->size());
97 for (TemplateParameterList::const_iterator P = Params->begin(),
98 PEnd = Params->end();
99 P != PEnd; ++P) {
100 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
101 CanonParams.push_back(
102 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
103 SourceLocation(), TTP->getDepth(),
104 TTP->getIndex(), 0, false,
105 TTP->isParameterPack()));
106 else if (NonTypeTemplateParmDecl *NTTP
107 = dyn_cast<NonTypeTemplateParmDecl>(*P))
108 CanonParams.push_back(
109 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
110 SourceLocation(), NTTP->getDepth(),
111 NTTP->getPosition(), 0,
112 getCanonicalType(NTTP->getType()),
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000113 NTTP->isParameterPack(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000114 0));
115 else
116 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
117 cast<TemplateTemplateParmDecl>(*P)));
118 }
119
120 TemplateTemplateParmDecl *CanonTTP
121 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
122 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000123 TTP->getPosition(),
124 TTP->isParameterPack(),
125 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000126 TemplateParameterList::Create(*this, SourceLocation(),
127 SourceLocation(),
128 CanonParams.data(),
129 CanonParams.size(),
130 SourceLocation()));
131
132 // Get the new insert position for the node we care about.
133 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
134 assert(Canonical == 0 && "Shouldn't be in the map!");
135 (void)Canonical;
136
137 // Create the canonical template template parameter entry.
138 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
139 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
140 return CanonTTP;
141}
142
Charles Davis53c59df2010-08-16 03:33:14 +0000143CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000144 if (!LangOpts.CPlusPlus) return 0;
145
Charles Davis6bcb07a2010-08-19 02:18:14 +0000146 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000147 case CXXABI_ARM:
148 return CreateARMCXXABI(*this);
149 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000150 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000151 case CXXABI_Microsoft:
152 return CreateMicrosoftCXXABI(*this);
153 }
John McCall86353412010-08-21 22:46:04 +0000154 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000155}
156
Chris Lattner465fa322008-10-05 17:34:18 +0000157ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000158 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000159 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000160 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000161 unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000162 TemplateSpecializationTypes(this_()),
163 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000164 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
165 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000166 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000167 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000168 NullTypeSourceInfo(QualType()),
Charles Davis53c59df2010-08-16 03:33:14 +0000169 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000170 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000171 BuiltinInfo(builtins),
172 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000173 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000174 LastSDM(0, 0),
175 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000176 ObjCIdRedefinitionType = QualType();
177 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000178 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000179 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000180 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000181 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000182}
183
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000184ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000185 // Release the DenseMaps associated with DeclContext objects.
186 // FIXME: Is this the ideal solution?
187 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000188
Douglas Gregor5b11d492010-07-25 17:53:33 +0000189 // Call all of the deallocation functions.
190 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
191 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000192
Douglas Gregor832940b2010-03-02 23:58:15 +0000193 // Release all of the memory associated with overridden C++ methods.
194 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
195 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
196 OM != OMEnd; ++OM)
197 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000198
Ted Kremenek076baeb2010-06-08 23:00:58 +0000199 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000200 // because they can contain DenseMaps.
201 for (llvm::DenseMap<const ObjCContainerDecl*,
202 const ASTRecordLayout*>::iterator
203 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
204 // Increment in loop to prevent using deallocated memory.
205 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
206 R->Destroy(*this);
207
Ted Kremenek076baeb2010-06-08 23:00:58 +0000208 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
209 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
210 // Increment in loop to prevent using deallocated memory.
211 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
212 R->Destroy(*this);
213 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000214
215 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
216 AEnd = DeclAttrs.end();
217 A != AEnd; ++A)
218 A->second->~AttrVec();
219}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000220
Douglas Gregor1a809332010-05-23 18:26:36 +0000221void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
222 Deallocations.push_back(std::make_pair(Callback, Data));
223}
224
Mike Stump11289f42009-09-09 15:08:12 +0000225void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000226ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
227 ExternalSource.reset(Source.take());
228}
229
Chris Lattner4eb445d2007-01-26 01:27:23 +0000230void ASTContext::PrintStats() const {
231 fprintf(stderr, "*** AST Context Stats:\n");
232 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000233
Douglas Gregora30d0462009-05-26 14:40:08 +0000234 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000235#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000236#define ABSTRACT_TYPE(Name, Parent)
237#include "clang/AST/TypeNodes.def"
238 0 // Extra
239 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000240
Chris Lattner4eb445d2007-01-26 01:27:23 +0000241 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
242 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000243 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000244 }
245
Douglas Gregora30d0462009-05-26 14:40:08 +0000246 unsigned Idx = 0;
247 unsigned TotalBytes = 0;
248#define TYPE(Name, Parent) \
249 if (counts[Idx]) \
250 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
251 TotalBytes += counts[Idx] * sizeof(Name##Type); \
252 ++Idx;
253#define ABSTRACT_TYPE(Name, Parent)
254#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000255
Douglas Gregora30d0462009-05-26 14:40:08 +0000256 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000257
Douglas Gregor7454c562010-07-02 20:37:36 +0000258 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000259 fprintf(stderr, " %u/%u implicit default constructors created\n",
260 NumImplicitDefaultConstructorsDeclared,
261 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000262 fprintf(stderr, " %u/%u implicit copy constructors created\n",
263 NumImplicitCopyConstructorsDeclared,
264 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000265 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
266 NumImplicitCopyAssignmentOperatorsDeclared,
267 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000268 fprintf(stderr, " %u/%u implicit destructors created\n",
269 NumImplicitDestructorsDeclared, NumImplicitDestructors);
270
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000271 if (ExternalSource.get()) {
272 fprintf(stderr, "\n");
273 ExternalSource->PrintStats();
274 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000275
Douglas Gregor5b11d492010-07-25 17:53:33 +0000276 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000277}
278
279
John McCall48f2d582009-10-23 23:03:21 +0000280void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000281 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000282 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000283 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000284}
285
Chris Lattner970e54e2006-11-12 00:37:36 +0000286void ASTContext::InitBuiltinTypes() {
287 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000288
Chris Lattner970e54e2006-11-12 00:37:36 +0000289 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000290 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000291
Chris Lattner970e54e2006-11-12 00:37:36 +0000292 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000293 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000294 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000295 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000296 InitBuiltinType(CharTy, BuiltinType::Char_S);
297 else
298 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000299 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000300 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
301 InitBuiltinType(ShortTy, BuiltinType::Short);
302 InitBuiltinType(IntTy, BuiltinType::Int);
303 InitBuiltinType(LongTy, BuiltinType::Long);
304 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattner970e54e2006-11-12 00:37:36 +0000306 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000307 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
308 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
309 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
310 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
311 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000312
Chris Lattner970e54e2006-11-12 00:37:36 +0000313 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000314 InitBuiltinType(FloatTy, BuiltinType::Float);
315 InitBuiltinType(DoubleTy, BuiltinType::Double);
316 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000317
Chris Lattnerf122cef2009-04-30 02:43:43 +0000318 // GNU extension, 128-bit integers.
319 InitBuiltinType(Int128Ty, BuiltinType::Int128);
320 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
321
Chris Lattnerad3467e2010-12-25 23:25:43 +0000322 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
323 if (!LangOpts.ShortWChar)
324 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
325 else // -fshort-wchar makes wchar_t be unsigned.
326 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
327 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000328 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000329
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000330 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
331 InitBuiltinType(Char16Ty, BuiltinType::Char16);
332 else // C99
333 Char16Ty = getFromTargetType(Target.getChar16Type());
334
335 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
336 InitBuiltinType(Char32Ty, BuiltinType::Char32);
337 else // C99
338 Char32Ty = getFromTargetType(Target.getChar32Type());
339
Douglas Gregor4619e432008-12-05 23:32:09 +0000340 // Placeholder type for type-dependent expressions whose type is
341 // completely unknown. No code should ever check a type against
342 // DependentTy and users should never see it; however, it is here to
343 // help diagnose failures to properly check for type-dependent
344 // expressions.
345 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000346
John McCall36e7fe32010-10-12 00:20:44 +0000347 // Placeholder type for functions.
348 InitBuiltinType(OverloadTy, BuiltinType::Overload);
349
Mike Stump11289f42009-09-09 15:08:12 +0000350 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000351 // not yet been deduced.
John McCall36e7fe32010-10-12 00:20:44 +0000352 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000353
Chris Lattner970e54e2006-11-12 00:37:36 +0000354 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000355 FloatComplexTy = getComplexType(FloatTy);
356 DoubleComplexTy = getComplexType(DoubleTy);
357 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000358
Steve Naroff66e9f332007-10-15 14:41:52 +0000359 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000360
Steve Naroff1329fa02009-07-15 18:40:39 +0000361 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
362 ObjCIdTypedefType = QualType();
363 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000364 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000365
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000366 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000367 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
368 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000369 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000370
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000371 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000372
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000373 // void * type
374 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000375
376 // nullptr type (C++0x 2.14.7)
377 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000378}
379
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000380Diagnostic &ASTContext::getDiagnostics() const {
381 return SourceMgr.getDiagnostics();
382}
383
Douglas Gregor561eceb2010-08-30 16:49:28 +0000384AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
385 AttrVec *&Result = DeclAttrs[D];
386 if (!Result) {
387 void *Mem = Allocate(sizeof(AttrVec));
388 Result = new (Mem) AttrVec;
389 }
390
391 return *Result;
392}
393
394/// \brief Erase the attributes corresponding to the given declaration.
395void ASTContext::eraseDeclAttrs(const Decl *D) {
396 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
397 if (Pos != DeclAttrs.end()) {
398 Pos->second->~AttrVec();
399 DeclAttrs.erase(Pos);
400 }
401}
402
403
Douglas Gregor86d142a2009-10-08 07:24:58 +0000404MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000405ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000406 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000407 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000408 = InstantiatedFromStaticDataMember.find(Var);
409 if (Pos == InstantiatedFromStaticDataMember.end())
410 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000411
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000412 return Pos->second;
413}
414
Mike Stump11289f42009-09-09 15:08:12 +0000415void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000416ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000417 TemplateSpecializationKind TSK,
418 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000419 assert(Inst->isStaticDataMember() && "Not a static data member");
420 assert(Tmpl->isStaticDataMember() && "Not a static data member");
421 assert(!InstantiatedFromStaticDataMember[Inst] &&
422 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000423 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000424 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000425}
426
John McCalle61f2ba2009-11-18 02:36:19 +0000427NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000428ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000429 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000430 = InstantiatedFromUsingDecl.find(UUD);
431 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000432 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000433
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000434 return Pos->second;
435}
436
437void
John McCallb96ec562009-12-04 22:46:56 +0000438ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
439 assert((isa<UsingDecl>(Pattern) ||
440 isa<UnresolvedUsingValueDecl>(Pattern) ||
441 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
442 "pattern decl is not a using decl");
443 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
444 InstantiatedFromUsingDecl[Inst] = Pattern;
445}
446
447UsingShadowDecl *
448ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
449 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
450 = InstantiatedFromUsingShadowDecl.find(Inst);
451 if (Pos == InstantiatedFromUsingShadowDecl.end())
452 return 0;
453
454 return Pos->second;
455}
456
457void
458ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
459 UsingShadowDecl *Pattern) {
460 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
461 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000462}
463
Anders Carlsson5da84842009-09-01 04:26:58 +0000464FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
465 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
466 = InstantiatedFromUnnamedFieldDecl.find(Field);
467 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
468 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000469
Anders Carlsson5da84842009-09-01 04:26:58 +0000470 return Pos->second;
471}
472
473void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
474 FieldDecl *Tmpl) {
475 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
476 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
477 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
478 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000479
Anders Carlsson5da84842009-09-01 04:26:58 +0000480 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
481}
482
Douglas Gregor832940b2010-03-02 23:58:15 +0000483ASTContext::overridden_cxx_method_iterator
484ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
485 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
486 = OverriddenMethods.find(Method);
487 if (Pos == OverriddenMethods.end())
488 return 0;
489
490 return Pos->second.begin();
491}
492
493ASTContext::overridden_cxx_method_iterator
494ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
495 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
496 = OverriddenMethods.find(Method);
497 if (Pos == OverriddenMethods.end())
498 return 0;
499
500 return Pos->second.end();
501}
502
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000503unsigned
504ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
505 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
506 = OverriddenMethods.find(Method);
507 if (Pos == OverriddenMethods.end())
508 return 0;
509
510 return Pos->second.size();
511}
512
Douglas Gregor832940b2010-03-02 23:58:15 +0000513void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
514 const CXXMethodDecl *Overridden) {
515 OverriddenMethods[Method].push_back(Overridden);
516}
517
Chris Lattner53cfe802007-07-18 17:52:12 +0000518//===----------------------------------------------------------------------===//
519// Type Sizing and Analysis
520//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000521
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000522/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
523/// scalar floating point type.
524const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000525 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000526 assert(BT && "Not a floating point type!");
527 switch (BT->getKind()) {
528 default: assert(0 && "Not a floating point type!");
529 case BuiltinType::Float: return Target.getFloatFormat();
530 case BuiltinType::Double: return Target.getDoubleFormat();
531 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
532 }
533}
534
Ken Dyck160146e2010-01-27 17:10:57 +0000535/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000536/// specified decl. Note that bitfields do not have a valid alignment, so
537/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000538/// If @p RefAsPointee, references are treated like their underlying type
539/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000540CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000541 unsigned Align = Target.getCharWidth();
542
John McCall94268702010-10-08 18:24:19 +0000543 bool UseAlignAttrOnly = false;
544 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
545 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000546
John McCall94268702010-10-08 18:24:19 +0000547 // __attribute__((aligned)) can increase or decrease alignment
548 // *except* on a struct or struct member, where it only increases
549 // alignment unless 'packed' is also specified.
550 //
551 // It is an error for [[align]] to decrease alignment, so we can
552 // ignore that possibility; Sema should diagnose it.
553 if (isa<FieldDecl>(D)) {
554 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
555 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
556 } else {
557 UseAlignAttrOnly = true;
558 }
559 }
560
561 if (UseAlignAttrOnly) {
562 // ignore type of value
563 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000564 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000565 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000566 if (RefAsPointee)
567 T = RT->getPointeeType();
568 else
569 T = getPointerType(RT->getPointeeType());
570 }
571 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000572 unsigned MinWidth = Target.getLargeArrayMinWidth();
573 unsigned ArrayAlign = Target.getLargeArrayAlign();
574 if (isa<VariableArrayType>(T) && MinWidth != 0)
575 Align = std::max(Align, ArrayAlign);
576 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
577 unsigned Size = getTypeSize(CT);
578 if (MinWidth != 0 && MinWidth <= Size)
579 Align = std::max(Align, ArrayAlign);
580 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000581 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000582 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
583 T = cast<ArrayType>(T)->getElementType();
584
585 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
586 }
Charles Davis3fc51072010-02-23 04:52:00 +0000587 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
588 // In the case of a field in a packed struct, we want the minimum
589 // of the alignment of the field and the alignment of the struct.
590 Align = std::min(Align,
591 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
592 }
Chris Lattner68061312009-01-24 21:53:27 +0000593 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000594
Ken Dyck160146e2010-01-27 17:10:57 +0000595 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000596}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000597
John McCall87fe5d52010-05-20 01:18:31 +0000598std::pair<CharUnits, CharUnits>
599ASTContext::getTypeInfoInChars(const Type *T) {
600 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
601 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
602 CharUnits::fromQuantity(Info.second / getCharWidth()));
603}
604
605std::pair<CharUnits, CharUnits>
606ASTContext::getTypeInfoInChars(QualType T) {
607 return getTypeInfoInChars(T.getTypePtr());
608}
609
Chris Lattner983a8bb2007-07-13 22:13:22 +0000610/// getTypeSize - Return the size of the specified type, in bits. This method
611/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000612///
613/// FIXME: Pointers into different addr spaces could have different sizes and
614/// alignment requirements: getPointerInfo should take an AddrSpace, this
615/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000616std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000617ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000618 uint64_t Width=0;
619 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000620 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000621#define TYPE(Class, Base)
622#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000623#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000624#define DEPENDENT_TYPE(Class, Base) case Type::Class:
625#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000626 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000627 break;
628
Chris Lattner355332d2007-07-13 22:27:08 +0000629 case Type::FunctionNoProto:
630 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000631 // GCC extension: alignof(function) = 32 bits
632 Width = 0;
633 Align = 32;
634 break;
635
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000636 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000637 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000638 Width = 0;
639 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
640 break;
641
Steve Naroff5c131802007-08-30 01:06:46 +0000642 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000643 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000644
Chris Lattner37e05872008-03-05 18:54:05 +0000645 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000646 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000647 Align = EltInfo.second;
648 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000649 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000650 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000651 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000652 const VectorType *VT = cast<VectorType>(T);
653 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
654 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000655 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000656 // If the alignment is not a power of 2, round up to the next power of 2.
657 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000658 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000659 Align = llvm::NextPowerOf2(Align);
660 Width = llvm::RoundUpToAlignment(Width, Align);
661 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000662 break;
663 }
Chris Lattner647fb222007-07-18 18:26:58 +0000664
Chris Lattner7570e9c2008-03-08 08:52:55 +0000665 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000666 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000667 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000668 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000669 // GCC extension: alignof(void) = 8 bits.
670 Width = 0;
671 Align = 8;
672 break;
673
Chris Lattner6a4f7452007-12-19 19:23:28 +0000674 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000675 Width = Target.getBoolWidth();
676 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000677 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000678 case BuiltinType::Char_S:
679 case BuiltinType::Char_U:
680 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000681 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000682 Width = Target.getCharWidth();
683 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000684 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000685 case BuiltinType::WChar_S:
686 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000687 Width = Target.getWCharWidth();
688 Align = Target.getWCharAlign();
689 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000690 case BuiltinType::Char16:
691 Width = Target.getChar16Width();
692 Align = Target.getChar16Align();
693 break;
694 case BuiltinType::Char32:
695 Width = Target.getChar32Width();
696 Align = Target.getChar32Align();
697 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000698 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000699 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000700 Width = Target.getShortWidth();
701 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000702 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000703 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000704 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000705 Width = Target.getIntWidth();
706 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000707 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000708 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000709 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000710 Width = Target.getLongWidth();
711 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000712 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000713 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000714 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000715 Width = Target.getLongLongWidth();
716 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000717 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000718 case BuiltinType::Int128:
719 case BuiltinType::UInt128:
720 Width = 128;
721 Align = 128; // int128_t is 128-bit aligned on all targets.
722 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000723 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000724 Width = Target.getFloatWidth();
725 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000726 break;
727 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000728 Width = Target.getDoubleWidth();
729 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000730 break;
731 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000732 Width = Target.getLongDoubleWidth();
733 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000734 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000735 case BuiltinType::NullPtr:
736 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
737 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000738 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000739 case BuiltinType::ObjCId:
740 case BuiltinType::ObjCClass:
741 case BuiltinType::ObjCSel:
742 Width = Target.getPointerWidth(0);
743 Align = Target.getPointerAlign(0);
744 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000745 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000746 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000747 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000748 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000749 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000750 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000751 case Type::BlockPointer: {
752 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
753 Width = Target.getPointerWidth(AS);
754 Align = Target.getPointerAlign(AS);
755 break;
756 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000757 case Type::LValueReference:
758 case Type::RValueReference: {
759 // alignof and sizeof should never enter this code path here, so we go
760 // the pointer route.
761 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
762 Width = Target.getPointerWidth(AS);
763 Align = Target.getPointerAlign(AS);
764 break;
765 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000766 case Type::Pointer: {
767 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000768 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000769 Align = Target.getPointerAlign(AS);
770 break;
771 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000772 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000773 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000774 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000775 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000776 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000777 Align = PtrDiffInfo.second;
778 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000779 }
Chris Lattner647fb222007-07-18 18:26:58 +0000780 case Type::Complex: {
781 // Complex types have the same alignment as their elements, but twice the
782 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000783 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000784 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000785 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000786 Align = EltInfo.second;
787 break;
788 }
John McCall8b07ec22010-05-15 11:32:37 +0000789 case Type::ObjCObject:
790 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000791 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000792 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000793 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
794 Width = Layout.getSize();
795 Align = Layout.getAlignment();
796 break;
797 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000798 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000799 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000800 const TagType *TT = cast<TagType>(T);
801
802 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000803 Width = 1;
804 Align = 1;
805 break;
806 }
Mike Stump11289f42009-09-09 15:08:12 +0000807
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000808 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000809 return getTypeInfo(ET->getDecl()->getIntegerType());
810
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000811 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000812 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
813 Width = Layout.getSize();
814 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000815 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000816 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000817
Chris Lattner63d2b362009-10-22 05:17:15 +0000818 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000819 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
820 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000821
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000822 case Type::Paren:
823 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
824
Douglas Gregoref462e62009-04-30 17:32:17 +0000825 case Type::Typedef: {
826 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000827 std::pair<uint64_t, unsigned> Info
828 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
829 Align = std::max(Typedef->getMaxAlignment(), Info.second);
830 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000831 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000832 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000833
834 case Type::TypeOfExpr:
835 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
836 .getTypePtr());
837
838 case Type::TypeOf:
839 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
840
Anders Carlsson81df7b82009-06-24 19:06:50 +0000841 case Type::Decltype:
842 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
843 .getTypePtr());
844
Abramo Bagnara6150c882010-05-11 21:36:43 +0000845 case Type::Elaborated:
846 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000847
John McCall81904512011-01-06 01:58:22 +0000848 case Type::Attributed:
849 return getTypeInfo(
850 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
851
Douglas Gregoref462e62009-04-30 17:32:17 +0000852 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000853 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000854 "Cannot request the size of a dependent type");
855 // FIXME: this is likely to be wrong once we support template
856 // aliases, since a template alias could refer to a typedef that
857 // has an __aligned__ attribute on it.
858 return getTypeInfo(getCanonicalType(T));
859 }
Mike Stump11289f42009-09-09 15:08:12 +0000860
Chris Lattner53cfe802007-07-18 17:52:12 +0000861 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000862 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000863}
864
Ken Dyck8c89d592009-12-22 14:23:30 +0000865/// getTypeSizeInChars - Return the size of the specified type, in characters.
866/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000867CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyck40775002010-01-11 17:06:35 +0000868 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000869}
Jay Foad39c79802011-01-12 09:06:06 +0000870CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyck40775002010-01-11 17:06:35 +0000871 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000872}
873
Ken Dycka6046ab2010-01-26 17:25:18 +0000874/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000875/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000876CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyck24d28d62010-01-26 17:22:55 +0000877 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
878}
Jay Foad39c79802011-01-12 09:06:06 +0000879CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyck24d28d62010-01-26 17:22:55 +0000880 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
881}
882
Chris Lattnera3402cd2009-01-27 18:08:34 +0000883/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
884/// type for the current target in bits. This can be different than the ABI
885/// alignment in cases where it is beneficial for performance to overalign
886/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +0000887unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +0000888 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000889
890 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000891 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000892 T = CT->getElementType().getTypePtr();
893 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
894 T->isSpecificBuiltinType(BuiltinType::LongLong))
895 return std::max(ABIAlign, (unsigned)getTypeSize(T));
896
Chris Lattnera3402cd2009-01-27 18:08:34 +0000897 return ABIAlign;
898}
899
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000900/// ShallowCollectObjCIvars -
901/// Collect all ivars, including those synthesized, in the current class.
902///
903void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +0000904 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000905 // FIXME. This need be removed but there are two many places which
906 // assume const-ness of ObjCInterfaceDecl
907 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
908 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
909 Iv= Iv->getNextIvar())
910 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000911}
912
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000913/// DeepCollectObjCIvars -
914/// This routine first collects all declared, but not synthesized, ivars in
915/// super class and then collects all ivars, including those synthesized for
916/// current class. This routine is used for implementation of current class
917/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000918///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000919void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
920 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +0000921 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000922 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
923 DeepCollectObjCIvars(SuperClass, false, Ivars);
924 if (!leafClass) {
925 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
926 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000927 Ivars.push_back(*I);
928 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000929 else
930 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000931}
932
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000933/// CollectInheritedProtocols - Collect all protocols in current class and
934/// those inherited by it.
935void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000936 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000937 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000938 // We can use protocol_iterator here instead of
939 // all_referenced_protocol_iterator since we are walking all categories.
940 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
941 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000942 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000943 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000944 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000945 PE = Proto->protocol_end(); P != PE; ++P) {
946 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000947 CollectInheritedProtocols(*P, Protocols);
948 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000949 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000950
951 // Categories of this Interface.
952 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
953 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
954 CollectInheritedProtocols(CDeclChain, Protocols);
955 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
956 while (SD) {
957 CollectInheritedProtocols(SD, Protocols);
958 SD = SD->getSuperClass();
959 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000960 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000961 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000962 PE = OC->protocol_end(); P != PE; ++P) {
963 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000964 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000965 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
966 PE = Proto->protocol_end(); P != PE; ++P)
967 CollectInheritedProtocols(*P, Protocols);
968 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000969 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000970 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
971 PE = OP->protocol_end(); P != PE; ++P) {
972 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000973 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000974 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
975 PE = Proto->protocol_end(); P != PE; ++P)
976 CollectInheritedProtocols(*P, Protocols);
977 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000978 }
979}
980
Jay Foad39c79802011-01-12 09:06:06 +0000981unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000982 unsigned count = 0;
983 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000984 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
985 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000986 count += CDecl->ivar_size();
987
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000988 // Count ivar defined in this class's implementation. This
989 // includes synthesized ivars.
990 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000991 count += ImplDecl->ivar_size();
992
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000993 return count;
994}
995
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000996/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
997ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
998 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
999 I = ObjCImpls.find(D);
1000 if (I != ObjCImpls.end())
1001 return cast<ObjCImplementationDecl>(I->second);
1002 return 0;
1003}
1004/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1005ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1006 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1007 I = ObjCImpls.find(D);
1008 if (I != ObjCImpls.end())
1009 return cast<ObjCCategoryImplDecl>(I->second);
1010 return 0;
1011}
1012
1013/// \brief Set the implementation of ObjCInterfaceDecl.
1014void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1015 ObjCImplementationDecl *ImplD) {
1016 assert(IFaceD && ImplD && "Passed null params");
1017 ObjCImpls[IFaceD] = ImplD;
1018}
1019/// \brief Set the implementation of ObjCCategoryDecl.
1020void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1021 ObjCCategoryImplDecl *ImplD) {
1022 assert(CatD && ImplD && "Passed null params");
1023 ObjCImpls[CatD] = ImplD;
1024}
1025
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001026/// \brief Get the copy initialization expression of VarDecl,or NULL if
1027/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001028Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001029 assert(VD && "Passed null params");
1030 assert(VD->hasAttr<BlocksAttr>() &&
1031 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001032 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001033 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001034 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1035}
1036
1037/// \brief Set the copy inialization expression of a block var decl.
1038void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1039 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001040 assert(VD->hasAttr<BlocksAttr>() &&
1041 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001042 BlockVarCopyInits[VD] = Init;
1043}
1044
John McCallbcd03502009-12-07 02:54:59 +00001045/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001046///
John McCallbcd03502009-12-07 02:54:59 +00001047/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001048/// the TypeLoc wrappers.
1049///
1050/// \param T the type that will be the basis for type source info. This type
1051/// should refer to how the declarator was written in source code, not to
1052/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001053TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001054 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001055 if (!DataSize)
1056 DataSize = TypeLoc::getFullDataSizeForType(T);
1057 else
1058 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001059 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001060
John McCallbcd03502009-12-07 02:54:59 +00001061 TypeSourceInfo *TInfo =
1062 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1063 new (TInfo) TypeSourceInfo(T);
1064 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001065}
1066
John McCallbcd03502009-12-07 02:54:59 +00001067TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001068 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001069 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001070 DI->getTypeLoc().initialize(L);
1071 return DI;
1072}
1073
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001074const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001075ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001076 return getObjCLayout(D, 0);
1077}
1078
1079const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001080ASTContext::getASTObjCImplementationLayout(
1081 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001082 return getObjCLayout(D->getClassInterface(), D);
1083}
1084
Chris Lattner983a8bb2007-07-13 22:13:22 +00001085//===----------------------------------------------------------------------===//
1086// Type creation/memoization methods
1087//===----------------------------------------------------------------------===//
1088
Jay Foad39c79802011-01-12 09:06:06 +00001089QualType
1090ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) const {
John McCall8ccfcb52009-09-24 19:53:00 +00001091 unsigned Fast = Quals.getFastQualifiers();
1092 Quals.removeFastQualifiers();
1093
1094 // Check if we've already instantiated this type.
1095 llvm::FoldingSetNodeID ID;
1096 ExtQuals::Profile(ID, TypeNode, Quals);
1097 void *InsertPos = 0;
1098 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1099 assert(EQ->getQualifiers() == Quals);
1100 QualType T = QualType(EQ, Fast);
1101 return T;
1102 }
1103
John McCall717d9b02010-12-10 11:01:00 +00001104 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001105 ExtQualNodes.InsertNode(New, InsertPos);
1106 QualType T = QualType(New, Fast);
1107 return T;
1108}
1109
Jay Foad39c79802011-01-12 09:06:06 +00001110QualType
1111ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001112 QualType CanT = getCanonicalType(T);
1113 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001114 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001115
John McCall8ccfcb52009-09-24 19:53:00 +00001116 // If we are composing extended qualifiers together, merge together
1117 // into one ExtQuals node.
1118 QualifierCollector Quals;
1119 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001120
John McCall8ccfcb52009-09-24 19:53:00 +00001121 // If this type already has an address space specified, it cannot get
1122 // another one.
1123 assert(!Quals.hasAddressSpace() &&
1124 "Type cannot be in multiple addr spaces!");
1125 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001126
John McCall8ccfcb52009-09-24 19:53:00 +00001127 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001128}
1129
Chris Lattnerd60183d2009-02-18 22:53:11 +00001130QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001131 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001132 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001133 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001134 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001135
John McCall53fa7142010-12-24 02:08:15 +00001136 if (const PointerType *ptr = T->getAs<PointerType>()) {
1137 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001138 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001139 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1140 return getPointerType(ResultType);
1141 }
1142 }
Mike Stump11289f42009-09-09 15:08:12 +00001143
John McCall8ccfcb52009-09-24 19:53:00 +00001144 // If we are composing extended qualifiers together, merge together
1145 // into one ExtQuals node.
1146 QualifierCollector Quals;
1147 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001148
John McCall8ccfcb52009-09-24 19:53:00 +00001149 // If this type already has an ObjCGC specified, it cannot get
1150 // another one.
1151 assert(!Quals.hasObjCGCAttr() &&
1152 "Type cannot have multiple ObjCGCs!");
1153 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001154
John McCall8ccfcb52009-09-24 19:53:00 +00001155 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001156}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001157
John McCall4f5019e2010-12-19 02:44:49 +00001158const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1159 FunctionType::ExtInfo Info) {
1160 if (T->getExtInfo() == Info)
1161 return T;
1162
1163 QualType Result;
1164 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1165 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1166 } else {
1167 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1168 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1169 EPI.ExtInfo = Info;
1170 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1171 FPT->getNumArgs(), EPI);
1172 }
1173
1174 return cast<FunctionType>(Result.getTypePtr());
1175}
1176
Chris Lattnerc6395932007-06-22 20:56:16 +00001177/// getComplexType - Return the uniqued reference to the type for a complex
1178/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001179QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001180 // Unique pointers, to guarantee there is only one pointer of a particular
1181 // structure.
1182 llvm::FoldingSetNodeID ID;
1183 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001184
Chris Lattnerc6395932007-06-22 20:56:16 +00001185 void *InsertPos = 0;
1186 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1187 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001188
Chris Lattnerc6395932007-06-22 20:56:16 +00001189 // If the pointee type isn't canonical, this won't be a canonical type either,
1190 // so fill in the canonical type field.
1191 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001192 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001193 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001194
Chris Lattnerc6395932007-06-22 20:56:16 +00001195 // Get the new insert position for the node we care about.
1196 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001197 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001198 }
John McCall90d1c2d2009-09-24 23:30:46 +00001199 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001200 Types.push_back(New);
1201 ComplexTypes.InsertNode(New, InsertPos);
1202 return QualType(New, 0);
1203}
1204
Chris Lattner970e54e2006-11-12 00:37:36 +00001205/// getPointerType - Return the uniqued reference to the type for a pointer to
1206/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001207QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001208 // Unique pointers, to guarantee there is only one pointer of a particular
1209 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001210 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001211 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001212
Chris Lattner67521df2007-01-27 01:29:36 +00001213 void *InsertPos = 0;
1214 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001215 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001216
Chris Lattner7ccecb92006-11-12 08:50:50 +00001217 // If the pointee type isn't canonical, this won't be a canonical type either,
1218 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001219 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001220 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001221 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001222
Chris Lattner67521df2007-01-27 01:29:36 +00001223 // Get the new insert position for the node we care about.
1224 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001225 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001226 }
John McCall90d1c2d2009-09-24 23:30:46 +00001227 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001228 Types.push_back(New);
1229 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001230 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001231}
1232
Mike Stump11289f42009-09-09 15:08:12 +00001233/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001234/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001235QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001236 assert(T->isFunctionType() && "block of function types only");
1237 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001238 // structure.
1239 llvm::FoldingSetNodeID ID;
1240 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001241
Steve Naroffec33ed92008-08-27 16:04:49 +00001242 void *InsertPos = 0;
1243 if (BlockPointerType *PT =
1244 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1245 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001246
1247 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001248 // type either so fill in the canonical type field.
1249 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001250 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001251 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001252
Steve Naroffec33ed92008-08-27 16:04:49 +00001253 // Get the new insert position for the node we care about.
1254 BlockPointerType *NewIP =
1255 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001256 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001257 }
John McCall90d1c2d2009-09-24 23:30:46 +00001258 BlockPointerType *New
1259 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001260 Types.push_back(New);
1261 BlockPointerTypes.InsertNode(New, InsertPos);
1262 return QualType(New, 0);
1263}
1264
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001265/// getLValueReferenceType - Return the uniqued reference to the type for an
1266/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001267QualType
1268ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001269 // Unique pointers, to guarantee there is only one pointer of a particular
1270 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001271 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001272 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001273
1274 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001275 if (LValueReferenceType *RT =
1276 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001277 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001278
John McCallfc93cf92009-10-22 22:37:11 +00001279 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1280
Bill Wendling3708c182007-05-27 10:15:43 +00001281 // If the referencee type isn't canonical, this won't be a canonical type
1282 // either, so fill in the canonical type field.
1283 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001284 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1285 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1286 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001287
Bill Wendling3708c182007-05-27 10:15:43 +00001288 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001289 LValueReferenceType *NewIP =
1290 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001291 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001292 }
1293
John McCall90d1c2d2009-09-24 23:30:46 +00001294 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001295 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1296 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001297 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001298 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001299
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001300 return QualType(New, 0);
1301}
1302
1303/// getRValueReferenceType - Return the uniqued reference to the type for an
1304/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001305QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001306 // Unique pointers, to guarantee there is only one pointer of a particular
1307 // structure.
1308 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001309 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001310
1311 void *InsertPos = 0;
1312 if (RValueReferenceType *RT =
1313 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1314 return QualType(RT, 0);
1315
John McCallfc93cf92009-10-22 22:37:11 +00001316 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1317
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001318 // If the referencee type isn't canonical, this won't be a canonical type
1319 // either, so fill in the canonical type field.
1320 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001321 if (InnerRef || !T.isCanonical()) {
1322 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1323 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001324
1325 // Get the new insert position for the node we care about.
1326 RValueReferenceType *NewIP =
1327 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001328 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001329 }
1330
John McCall90d1c2d2009-09-24 23:30:46 +00001331 RValueReferenceType *New
1332 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001333 Types.push_back(New);
1334 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001335 return QualType(New, 0);
1336}
1337
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001338/// getMemberPointerType - Return the uniqued reference to the type for a
1339/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001340QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001341 // Unique pointers, to guarantee there is only one pointer of a particular
1342 // structure.
1343 llvm::FoldingSetNodeID ID;
1344 MemberPointerType::Profile(ID, T, Cls);
1345
1346 void *InsertPos = 0;
1347 if (MemberPointerType *PT =
1348 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1349 return QualType(PT, 0);
1350
1351 // If the pointee or class type isn't canonical, this won't be a canonical
1352 // type either, so fill in the canonical type field.
1353 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001354 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001355 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1356
1357 // Get the new insert position for the node we care about.
1358 MemberPointerType *NewIP =
1359 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001360 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001361 }
John McCall90d1c2d2009-09-24 23:30:46 +00001362 MemberPointerType *New
1363 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001364 Types.push_back(New);
1365 MemberPointerTypes.InsertNode(New, InsertPos);
1366 return QualType(New, 0);
1367}
1368
Mike Stump11289f42009-09-09 15:08:12 +00001369/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001370/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001371QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001372 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001373 ArrayType::ArraySizeModifier ASM,
Jay Foad39c79802011-01-12 09:06:06 +00001374 unsigned EltTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001375 assert((EltTy->isDependentType() ||
1376 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001377 "Constant array of VLAs is illegal!");
1378
Chris Lattnere2df3f92009-05-13 04:12:56 +00001379 // Convert the array size into a canonical width matching the pointer size for
1380 // the target.
1381 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001382 ArySize =
1383 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001384
Chris Lattner23b7eb62007-06-15 23:05:46 +00001385 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001386 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001387
Chris Lattner36f8e652007-01-27 08:31:04 +00001388 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001389 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001390 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001391 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001392
Chris Lattner7ccecb92006-11-12 08:50:50 +00001393 // If the element type isn't canonical, this won't be a canonical type either,
1394 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001395 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001396 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001397 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001398 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001399 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001400 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001401 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001402 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001403 }
Mike Stump11289f42009-09-09 15:08:12 +00001404
John McCall90d1c2d2009-09-24 23:30:46 +00001405 ConstantArrayType *New = new(*this,TypeAlignment)
1406 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001407 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001408 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001409 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001410}
1411
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001412/// getIncompleteArrayType - Returns a unique reference to the type for a
1413/// incomplete array of the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001414QualType ASTContext::getUnknownSizeVariableArrayType(QualType Ty) const {
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001415 QualType ElemTy = getBaseElementType(Ty);
1416 DeclarationName Name;
1417 llvm::SmallVector<QualType, 8> ATypes;
1418 QualType ATy = Ty;
1419 while (const ArrayType *AT = getAsArrayType(ATy)) {
1420 ATypes.push_back(ATy);
1421 ATy = AT->getElementType();
1422 }
1423 for (int i = ATypes.size() - 1; i >= 0; i--) {
1424 if (const VariableArrayType *VAT = getAsVariableArrayType(ATypes[i])) {
1425 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Star,
1426 0, VAT->getBracketsRange());
1427 }
1428 else if (const ConstantArrayType *CAT = getAsConstantArrayType(ATypes[i])) {
1429 llvm::APSInt ConstVal(CAT->getSize());
1430 ElemTy = getConstantArrayType(ElemTy, ConstVal, ArrayType::Normal, 0);
1431 }
1432 else if (getAsIncompleteArrayType(ATypes[i])) {
1433 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Normal,
1434 0, SourceRange());
1435 }
1436 else
1437 assert(false && "DependentArrayType is seen");
1438 }
1439 return ElemTy;
1440}
1441
1442/// getVariableArrayDecayedType - Returns a vla type where known sizes
1443/// are replaced with [*]
Jay Foad39c79802011-01-12 09:06:06 +00001444QualType ASTContext::getVariableArrayDecayedType(QualType Ty) const {
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001445 if (Ty->isPointerType()) {
1446 QualType BaseType = Ty->getAs<PointerType>()->getPointeeType();
1447 if (isa<VariableArrayType>(BaseType)) {
1448 ArrayType *AT = dyn_cast<ArrayType>(BaseType);
1449 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1450 if (VAT->getSizeExpr()) {
1451 Ty = getUnknownSizeVariableArrayType(BaseType);
1452 Ty = getPointerType(Ty);
1453 }
1454 }
1455 }
1456 return Ty;
1457}
1458
1459
Steve Naroffcadebd02007-08-30 18:14:25 +00001460/// getVariableArrayType - Returns a non-unique reference to the type for a
1461/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001462QualType ASTContext::getVariableArrayType(QualType EltTy,
1463 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001464 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001465 unsigned EltTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001466 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001467 // Since we don't unique expressions, it isn't possible to unique VLA's
1468 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001469 QualType CanonType;
1470
1471 if (!EltTy.isCanonical()) {
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001472 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1473 EltTypeQuals, Brackets);
1474 }
1475
John McCall90d1c2d2009-09-24 23:30:46 +00001476 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001477 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001478
1479 VariableArrayTypes.push_back(New);
1480 Types.push_back(New);
1481 return QualType(New, 0);
1482}
1483
Douglas Gregor4619e432008-12-05 23:32:09 +00001484/// getDependentSizedArrayType - Returns a non-unique reference to
1485/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001486/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001487QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1488 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001489 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001490 unsigned EltTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001491 SourceRange Brackets) const {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001492 assert((!NumElts || NumElts->isTypeDependent() ||
1493 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001494 "Size must be type- or value-dependent!");
1495
Douglas Gregorf3f95522009-07-31 00:23:35 +00001496 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001497 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001498 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001499
Douglas Gregorf86c9392010-10-26 00:51:02 +00001500 QualType CanonicalEltTy = getCanonicalType(EltTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001501 if (NumElts) {
1502 // Dependently-sized array types that do not have a specified
1503 // number of elements will have their sizes deduced from an
1504 // initializer.
Douglas Gregorf86c9392010-10-26 00:51:02 +00001505 DependentSizedArrayType::Profile(ID, *this, CanonicalEltTy, ASM,
Douglas Gregorad2956c2009-11-19 18:03:26 +00001506 EltTypeQuals, NumElts);
1507
1508 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1509 }
1510
Douglas Gregorf3f95522009-07-31 00:23:35 +00001511 DependentSizedArrayType *New;
1512 if (Canon) {
1513 // We already have a canonical version of this array type; use it as
1514 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001515 New = new (*this, TypeAlignment)
1516 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1517 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf86c9392010-10-26 00:51:02 +00001518 } else if (CanonicalEltTy == EltTy) {
1519 // This is a canonical type. Record it.
1520 New = new (*this, TypeAlignment)
1521 DependentSizedArrayType(*this, EltTy, QualType(),
1522 NumElts, ASM, EltTypeQuals, Brackets);
1523
1524 if (NumElts) {
1525#ifndef NDEBUG
1526 DependentSizedArrayType *CanonCheck
1527 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1528 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1529 (void)CanonCheck;
1530#endif
1531 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001532 }
Douglas Gregorf86c9392010-10-26 00:51:02 +00001533 } else {
1534 QualType Canon = getDependentSizedArrayType(CanonicalEltTy, NumElts,
1535 ASM, EltTypeQuals,
1536 SourceRange());
1537 New = new (*this, TypeAlignment)
1538 DependentSizedArrayType(*this, EltTy, Canon,
1539 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001540 }
Mike Stump11289f42009-09-09 15:08:12 +00001541
Douglas Gregor4619e432008-12-05 23:32:09 +00001542 Types.push_back(New);
1543 return QualType(New, 0);
1544}
1545
Eli Friedmanbd258282008-02-15 18:16:39 +00001546QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1547 ArrayType::ArraySizeModifier ASM,
Jay Foad39c79802011-01-12 09:06:06 +00001548 unsigned EltTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001549 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001550 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001551
1552 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001553 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001554 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1555 return QualType(ATP, 0);
1556
1557 // If the element type isn't canonical, this won't be a canonical type
1558 // either, so fill in the canonical type field.
1559 QualType Canonical;
1560
John McCallb692a092009-10-22 20:10:53 +00001561 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001562 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001563 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001564
1565 // Get the new insert position for the node we care about.
1566 IncompleteArrayType *NewIP =
1567 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001568 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001569 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001570
John McCall90d1c2d2009-09-24 23:30:46 +00001571 IncompleteArrayType *New = new (*this, TypeAlignment)
1572 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001573
1574 IncompleteArrayTypes.InsertNode(New, InsertPos);
1575 Types.push_back(New);
1576 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001577}
1578
Steve Naroff91fcddb2007-07-18 18:00:27 +00001579/// getVectorType - Return the unique reference to a vector type of
1580/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001581QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001582 VectorType::VectorKind VecKind) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00001583 BuiltinType *BaseType;
Mike Stump11289f42009-09-09 15:08:12 +00001584
Chris Lattnerdc226c22010-10-01 22:42:38 +00001585 BaseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1586 assert(BaseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001587
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001588 // Check if we've already instantiated a vector of this type.
1589 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001590 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001591
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001592 void *InsertPos = 0;
1593 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1594 return QualType(VTP, 0);
1595
1596 // If the element type isn't canonical, this won't be a canonical type either,
1597 // so fill in the canonical type field.
1598 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001599 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001600 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001601
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001602 // Get the new insert position for the node we care about.
1603 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001604 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001605 }
John McCall90d1c2d2009-09-24 23:30:46 +00001606 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001607 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001608 VectorTypes.InsertNode(New, InsertPos);
1609 Types.push_back(New);
1610 return QualType(New, 0);
1611}
1612
Nate Begemance4d7fc2008-04-18 23:10:10 +00001613/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001614/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001615QualType
1616ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001617 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001618
Chris Lattner76a00cf2008-04-06 22:59:24 +00001619 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001620 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001621
Steve Naroff91fcddb2007-07-18 18:00:27 +00001622 // Check if we've already instantiated a vector of this type.
1623 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001624 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001625 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001626 void *InsertPos = 0;
1627 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1628 return QualType(VTP, 0);
1629
1630 // If the element type isn't canonical, this won't be a canonical type either,
1631 // so fill in the canonical type field.
1632 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001633 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001634 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001635
Steve Naroff91fcddb2007-07-18 18:00:27 +00001636 // Get the new insert position for the node we care about.
1637 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001638 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001639 }
John McCall90d1c2d2009-09-24 23:30:46 +00001640 ExtVectorType *New = new (*this, TypeAlignment)
1641 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001642 VectorTypes.InsertNode(New, InsertPos);
1643 Types.push_back(New);
1644 return QualType(New, 0);
1645}
1646
Jay Foad39c79802011-01-12 09:06:06 +00001647QualType
1648ASTContext::getDependentSizedExtVectorType(QualType vecType,
1649 Expr *SizeExpr,
1650 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001651 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001652 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001653 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001654
Douglas Gregor352169a2009-07-31 03:54:25 +00001655 void *InsertPos = 0;
1656 DependentSizedExtVectorType *Canon
1657 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1658 DependentSizedExtVectorType *New;
1659 if (Canon) {
1660 // We already have a canonical version of this array type; use it as
1661 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001662 New = new (*this, TypeAlignment)
1663 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1664 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001665 } else {
1666 QualType CanonVecTy = getCanonicalType(vecType);
1667 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001668 New = new (*this, TypeAlignment)
1669 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1670 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001671
1672 DependentSizedExtVectorType *CanonCheck
1673 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1674 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1675 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001676 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1677 } else {
1678 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1679 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001680 New = new (*this, TypeAlignment)
1681 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001682 }
1683 }
Mike Stump11289f42009-09-09 15:08:12 +00001684
Douglas Gregor758a8692009-06-17 21:51:59 +00001685 Types.push_back(New);
1686 return QualType(New, 0);
1687}
1688
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001689/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001690///
Jay Foad39c79802011-01-12 09:06:06 +00001691QualType
1692ASTContext::getFunctionNoProtoType(QualType ResultTy,
1693 const FunctionType::ExtInfo &Info) const {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001694 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001695 // Unique functions, to guarantee there is only one function of a particular
1696 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001697 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001698 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001699
Chris Lattner47955de2007-01-27 08:37:20 +00001700 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001701 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001702 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001703 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001704
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001705 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001706 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001707 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001708 Canonical =
1709 getFunctionNoProtoType(getCanonicalType(ResultTy),
1710 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001711
Chris Lattner47955de2007-01-27 08:37:20 +00001712 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001713 FunctionNoProtoType *NewIP =
1714 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001715 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001716 }
Mike Stump11289f42009-09-09 15:08:12 +00001717
John McCall90d1c2d2009-09-24 23:30:46 +00001718 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001719 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001720 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001721 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001722 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001723}
1724
1725/// getFunctionType - Return a normal function type with a typed argument
1726/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001727QualType
1728ASTContext::getFunctionType(QualType ResultTy,
1729 const QualType *ArgArray, unsigned NumArgs,
1730 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001731 // Unique functions, to guarantee there is only one function of a particular
1732 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001733 llvm::FoldingSetNodeID ID;
John McCalldb40c7f2010-12-14 08:05:40 +00001734 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001735
1736 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001737 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001738 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001739 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001740
1741 // Determine whether the type being created is already canonical or not.
John McCalldb40c7f2010-12-14 08:05:40 +00001742 bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001743 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001744 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001745 isCanonical = false;
1746
John McCalldb40c7f2010-12-14 08:05:40 +00001747 const CallingConv CallConv = EPI.ExtInfo.getCC();
1748
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001749 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001750 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001751 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001752 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001753 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001754 CanonicalArgs.reserve(NumArgs);
1755 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001756 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001757
John McCalldb40c7f2010-12-14 08:05:40 +00001758 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1759 if (CanonicalEPI.HasExceptionSpec) {
1760 CanonicalEPI.HasExceptionSpec = false;
1761 CanonicalEPI.HasAnyExceptionSpec = false;
1762 CanonicalEPI.NumExceptions = 0;
1763 }
1764 CanonicalEPI.ExtInfo
1765 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1766
Chris Lattner76a00cf2008-04-06 22:59:24 +00001767 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001768 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00001769 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001770
Chris Lattnerfd4de792007-01-27 01:15:32 +00001771 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001772 FunctionProtoType *NewIP =
1773 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001774 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001775 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001776
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001777 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001778 // for two variable size arrays (for parameter and exception types) at the
1779 // end of them.
John McCalldb40c7f2010-12-14 08:05:40 +00001780 size_t Size = sizeof(FunctionProtoType) +
1781 NumArgs * sizeof(QualType) +
1782 EPI.NumExceptions * sizeof(QualType);
1783 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
1784 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, EPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001785 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001786 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001787 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001788}
Chris Lattneref51c202006-11-10 07:17:23 +00001789
John McCalle78aac42010-03-10 03:28:59 +00001790#ifndef NDEBUG
1791static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1792 if (!isa<CXXRecordDecl>(D)) return false;
1793 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1794 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1795 return true;
1796 if (RD->getDescribedClassTemplate() &&
1797 !isa<ClassTemplateSpecializationDecl>(RD))
1798 return true;
1799 return false;
1800}
1801#endif
1802
1803/// getInjectedClassNameType - Return the unique reference to the
1804/// injected class name type for the specified templated declaration.
1805QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00001806 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00001807 assert(NeedsInjectedClassNameType(Decl));
1808 if (Decl->TypeForDecl) {
1809 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001810 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001811 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1812 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1813 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1814 } else {
John McCall2408e322010-04-27 00:57:59 +00001815 Decl->TypeForDecl =
1816 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001817 Types.push_back(Decl->TypeForDecl);
1818 }
1819 return QualType(Decl->TypeForDecl, 0);
1820}
1821
Douglas Gregor83a586e2008-04-13 21:07:44 +00001822/// getTypeDeclType - Return the unique reference to the type for the
1823/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00001824QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001825 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001826 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001827
John McCall81e38502010-02-16 03:57:14 +00001828 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001829 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001830
John McCall96f0b5f2010-03-10 06:48:02 +00001831 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1832 "Template type parameter types are always available.");
1833
John McCall81e38502010-02-16 03:57:14 +00001834 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001835 assert(!Record->getPreviousDeclaration() &&
1836 "struct/union has previous declaration");
1837 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001838 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001839 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001840 assert(!Enum->getPreviousDeclaration() &&
1841 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001842 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001843 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001844 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1845 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001846 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001847 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001848
John McCall96f0b5f2010-03-10 06:48:02 +00001849 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001850 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001851}
1852
Chris Lattner32d920b2007-01-26 02:01:53 +00001853/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001854/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001855QualType
Jay Foad39c79802011-01-12 09:06:06 +00001856ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001857 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001858
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001859 if (Canonical.isNull())
1860 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001861 Decl->TypeForDecl = new(*this, TypeAlignment)
1862 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001863 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001864 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001865}
1866
Jay Foad39c79802011-01-12 09:06:06 +00001867QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001868 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1869
1870 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1871 if (PrevDecl->TypeForDecl)
1872 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1873
1874 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1875 Types.push_back(Decl->TypeForDecl);
1876 return QualType(Decl->TypeForDecl, 0);
1877}
1878
Jay Foad39c79802011-01-12 09:06:06 +00001879QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001880 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1881
1882 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1883 if (PrevDecl->TypeForDecl)
1884 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1885
1886 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1887 Types.push_back(Decl->TypeForDecl);
1888 return QualType(Decl->TypeForDecl, 0);
1889}
1890
John McCall81904512011-01-06 01:58:22 +00001891QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
1892 QualType modifiedType,
1893 QualType equivalentType) {
1894 llvm::FoldingSetNodeID id;
1895 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
1896
1897 void *insertPos = 0;
1898 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
1899 if (type) return QualType(type, 0);
1900
1901 QualType canon = getCanonicalType(equivalentType);
1902 type = new (*this, TypeAlignment)
1903 AttributedType(canon, attrKind, modifiedType, equivalentType);
1904
1905 Types.push_back(type);
1906 AttributedTypes.InsertNode(type, insertPos);
1907
1908 return QualType(type, 0);
1909}
1910
1911
John McCallcebee162009-10-18 09:09:24 +00001912/// \brief Retrieve a substitution-result type.
1913QualType
1914ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00001915 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00001916 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001917 && "replacement types must always be canonical");
1918
1919 llvm::FoldingSetNodeID ID;
1920 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1921 void *InsertPos = 0;
1922 SubstTemplateTypeParmType *SubstParm
1923 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1924
1925 if (!SubstParm) {
1926 SubstParm = new (*this, TypeAlignment)
1927 SubstTemplateTypeParmType(Parm, Replacement);
1928 Types.push_back(SubstParm);
1929 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1930 }
1931
1932 return QualType(SubstParm, 0);
1933}
1934
Douglas Gregorada4b792011-01-14 02:55:32 +00001935/// \brief Retrieve a
1936QualType ASTContext::getSubstTemplateTypeParmPackType(
1937 const TemplateTypeParmType *Parm,
1938 const TemplateArgument &ArgPack) {
1939#ifndef NDEBUG
1940 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1941 PEnd = ArgPack.pack_end();
1942 P != PEnd; ++P) {
1943 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
1944 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
1945 }
1946#endif
1947
1948 llvm::FoldingSetNodeID ID;
1949 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
1950 void *InsertPos = 0;
1951 if (SubstTemplateTypeParmPackType *SubstParm
1952 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
1953 return QualType(SubstParm, 0);
1954
1955 QualType Canon;
1956 if (!Parm->isCanonicalUnqualified()) {
1957 Canon = getCanonicalType(QualType(Parm, 0));
1958 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
1959 ArgPack);
1960 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
1961 }
1962
1963 SubstTemplateTypeParmPackType *SubstParm
1964 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
1965 ArgPack);
1966 Types.push_back(SubstParm);
1967 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1968 return QualType(SubstParm, 0);
1969}
1970
Douglas Gregoreff93e02009-02-05 23:33:38 +00001971/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001972/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001973/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001974QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001975 bool ParameterPack,
Jay Foad39c79802011-01-12 09:06:06 +00001976 IdentifierInfo *Name) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001977 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001978 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001979 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001980 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001981 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1982
1983 if (TypeParm)
1984 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001985
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001986 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001987 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001988 TypeParm = new (*this, TypeAlignment)
1989 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001990
1991 TemplateTypeParmType *TypeCheck
1992 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1993 assert(!TypeCheck && "Template type parameter canonical type broken");
1994 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001995 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001996 TypeParm = new (*this, TypeAlignment)
1997 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001998
1999 Types.push_back(TypeParm);
2000 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2001
2002 return QualType(TypeParm, 0);
2003}
2004
John McCalle78aac42010-03-10 03:28:59 +00002005TypeSourceInfo *
2006ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2007 SourceLocation NameLoc,
2008 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002009 QualType CanonType) const {
John McCalle78aac42010-03-10 03:28:59 +00002010 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2011
2012 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2013 TemplateSpecializationTypeLoc TL
2014 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2015 TL.setTemplateNameLoc(NameLoc);
2016 TL.setLAngleLoc(Args.getLAngleLoc());
2017 TL.setRAngleLoc(Args.getRAngleLoc());
2018 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2019 TL.setArgLocInfo(i, Args[i].getLocInfo());
2020 return DI;
2021}
2022
Mike Stump11289f42009-09-09 15:08:12 +00002023QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002024ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002025 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002026 QualType Canon) const {
John McCall6b51f282009-11-23 01:53:49 +00002027 unsigned NumArgs = Args.size();
2028
John McCall0ad16662009-10-29 08:12:44 +00002029 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2030 ArgVec.reserve(NumArgs);
2031 for (unsigned i = 0; i != NumArgs; ++i)
2032 ArgVec.push_back(Args[i].getArgument());
2033
John McCall2408e322010-04-27 00:57:59 +00002034 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00002035 Canon);
John McCall0ad16662009-10-29 08:12:44 +00002036}
2037
2038QualType
2039ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002040 const TemplateArgument *Args,
2041 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002042 QualType Canon) const {
Douglas Gregor15301382009-07-30 17:40:51 +00002043 if (!Canon.isNull())
2044 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002045 else
2046 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00002047
Douglas Gregora8e02e72009-07-28 23:00:59 +00002048 // Allocate the (non-canonical) template specialization type, but don't
2049 // try to unique it: these types typically have location information that
2050 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002051 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002052 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002053 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002054 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002055 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002056 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002057 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002058
Douglas Gregor8bf42052009-02-09 18:46:07 +00002059 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002060 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002061}
2062
Mike Stump11289f42009-09-09 15:08:12 +00002063QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002064ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2065 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002066 unsigned NumArgs) const {
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002067 // Build the canonical template specialization type.
2068 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2069 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2070 CanonArgs.reserve(NumArgs);
2071 for (unsigned I = 0; I != NumArgs; ++I)
2072 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2073
2074 // Determine whether this canonical template specialization type already
2075 // exists.
2076 llvm::FoldingSetNodeID ID;
2077 TemplateSpecializationType::Profile(ID, CanonTemplate,
2078 CanonArgs.data(), NumArgs, *this);
2079
2080 void *InsertPos = 0;
2081 TemplateSpecializationType *Spec
2082 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2083
2084 if (!Spec) {
2085 // Allocate a new canonical template specialization type.
2086 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2087 sizeof(TemplateArgument) * NumArgs),
2088 TypeAlignment);
2089 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2090 CanonArgs.data(), NumArgs,
2091 QualType());
2092 Types.push_back(Spec);
2093 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2094 }
2095
2096 assert(Spec->isDependentType() &&
2097 "Non-dependent template-id type must have a canonical type");
2098 return QualType(Spec, 0);
2099}
2100
2101QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002102ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2103 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002104 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002105 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002106 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002107
2108 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002109 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002110 if (T)
2111 return QualType(T, 0);
2112
Douglas Gregorc42075a2010-02-04 18:10:26 +00002113 QualType Canon = NamedType;
2114 if (!Canon.isCanonical()) {
2115 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002116 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2117 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002118 (void)CheckT;
2119 }
2120
Abramo Bagnara6150c882010-05-11 21:36:43 +00002121 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002122 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002123 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002124 return QualType(T, 0);
2125}
2126
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002127QualType
Jay Foad39c79802011-01-12 09:06:06 +00002128ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002129 llvm::FoldingSetNodeID ID;
2130 ParenType::Profile(ID, InnerType);
2131
2132 void *InsertPos = 0;
2133 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2134 if (T)
2135 return QualType(T, 0);
2136
2137 QualType Canon = InnerType;
2138 if (!Canon.isCanonical()) {
2139 Canon = getCanonicalType(InnerType);
2140 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2141 assert(!CheckT && "Paren canonical type broken");
2142 (void)CheckT;
2143 }
2144
2145 T = new (*this) ParenType(InnerType, Canon);
2146 Types.push_back(T);
2147 ParenTypes.InsertNode(T, InsertPos);
2148 return QualType(T, 0);
2149}
2150
Douglas Gregor02085352010-03-31 20:19:30 +00002151QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2152 NestedNameSpecifier *NNS,
2153 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002154 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002155 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2156
2157 if (Canon.isNull()) {
2158 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002159 ElaboratedTypeKeyword CanonKeyword = Keyword;
2160 if (Keyword == ETK_None)
2161 CanonKeyword = ETK_Typename;
2162
2163 if (CanonNNS != NNS || CanonKeyword != Keyword)
2164 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002165 }
2166
2167 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002168 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002169
2170 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002171 DependentNameType *T
2172 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002173 if (T)
2174 return QualType(T, 0);
2175
Douglas Gregor02085352010-03-31 20:19:30 +00002176 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002177 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002178 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002179 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002180}
2181
Mike Stump11289f42009-09-09 15:08:12 +00002182QualType
John McCallc392f372010-06-11 00:33:02 +00002183ASTContext::getDependentTemplateSpecializationType(
2184 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002185 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002186 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002187 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002188 // TODO: avoid this copy
2189 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2190 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2191 ArgCopy.push_back(Args[I].getArgument());
2192 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2193 ArgCopy.size(),
2194 ArgCopy.data());
2195}
2196
2197QualType
2198ASTContext::getDependentTemplateSpecializationType(
2199 ElaboratedTypeKeyword Keyword,
2200 NestedNameSpecifier *NNS,
2201 const IdentifierInfo *Name,
2202 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002203 const TemplateArgument *Args) const {
Douglas Gregordce2b622009-04-01 00:28:59 +00002204 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2205
Douglas Gregorc42075a2010-02-04 18:10:26 +00002206 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002207 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2208 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002209
2210 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002211 DependentTemplateSpecializationType *T
2212 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002213 if (T)
2214 return QualType(T, 0);
2215
John McCallc392f372010-06-11 00:33:02 +00002216 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002217
John McCallc392f372010-06-11 00:33:02 +00002218 ElaboratedTypeKeyword CanonKeyword = Keyword;
2219 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2220
2221 bool AnyNonCanonArgs = false;
2222 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2223 for (unsigned I = 0; I != NumArgs; ++I) {
2224 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2225 if (!CanonArgs[I].structurallyEquals(Args[I]))
2226 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002227 }
2228
John McCallc392f372010-06-11 00:33:02 +00002229 QualType Canon;
2230 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2231 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2232 Name, NumArgs,
2233 CanonArgs.data());
2234
2235 // Find the insert position again.
2236 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2237 }
2238
2239 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2240 sizeof(TemplateArgument) * NumArgs),
2241 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002242 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002243 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002244 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002245 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002246 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002247}
2248
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002249QualType ASTContext::getPackExpansionType(QualType Pattern,
2250 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002251 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002252 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002253
2254 assert(Pattern->containsUnexpandedParameterPack() &&
2255 "Pack expansions must expand one or more parameter packs");
2256 void *InsertPos = 0;
2257 PackExpansionType *T
2258 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2259 if (T)
2260 return QualType(T, 0);
2261
2262 QualType Canon;
2263 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002264 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002265
2266 // Find the insert position again.
2267 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2268 }
2269
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002270 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002271 Types.push_back(T);
2272 PackExpansionTypes.InsertNode(T, InsertPos);
2273 return QualType(T, 0);
2274}
2275
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002276/// CmpProtocolNames - Comparison predicate for sorting protocols
2277/// alphabetically.
2278static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2279 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002280 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002281}
2282
John McCall8b07ec22010-05-15 11:32:37 +00002283static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002284 unsigned NumProtocols) {
2285 if (NumProtocols == 0) return true;
2286
2287 for (unsigned i = 1; i != NumProtocols; ++i)
2288 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2289 return false;
2290 return true;
2291}
2292
2293static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002294 unsigned &NumProtocols) {
2295 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002296
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002297 // Sort protocols, keyed by name.
2298 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2299
2300 // Remove duplicates.
2301 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2302 NumProtocols = ProtocolsEnd-Protocols;
2303}
2304
John McCall8b07ec22010-05-15 11:32:37 +00002305QualType ASTContext::getObjCObjectType(QualType BaseType,
2306 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002307 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002308 // If the base type is an interface and there aren't any protocols
2309 // to add, then the interface type will do just fine.
2310 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2311 return BaseType;
2312
2313 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002314 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002315 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002316 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002317 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2318 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002319
John McCall8b07ec22010-05-15 11:32:37 +00002320 // Build the canonical type, which has the canonical base type and
2321 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002322 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002323 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2324 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2325 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002326 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2327 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002328 unsigned UniqueCount = NumProtocols;
2329
John McCallfc93cf92009-10-22 22:37:11 +00002330 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002331 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2332 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002333 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002334 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2335 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002336 }
2337
2338 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002339 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2340 }
2341
2342 unsigned Size = sizeof(ObjCObjectTypeImpl);
2343 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2344 void *Mem = Allocate(Size, TypeAlignment);
2345 ObjCObjectTypeImpl *T =
2346 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2347
2348 Types.push_back(T);
2349 ObjCObjectTypes.InsertNode(T, InsertPos);
2350 return QualType(T, 0);
2351}
2352
2353/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2354/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002355QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002356 llvm::FoldingSetNodeID ID;
2357 ObjCObjectPointerType::Profile(ID, ObjectT);
2358
2359 void *InsertPos = 0;
2360 if (ObjCObjectPointerType *QT =
2361 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2362 return QualType(QT, 0);
2363
2364 // Find the canonical object type.
2365 QualType Canonical;
2366 if (!ObjectT.isCanonical()) {
2367 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2368
2369 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002370 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2371 }
2372
Douglas Gregorf85bee62010-02-08 22:59:26 +00002373 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002374 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2375 ObjCObjectPointerType *QType =
2376 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002377
Steve Narofffb4330f2009-06-17 22:40:22 +00002378 Types.push_back(QType);
2379 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002380 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002381}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002382
Douglas Gregor1c283312010-08-11 12:19:30 +00002383/// getObjCInterfaceType - Return the unique reference to the type for the
2384/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002385QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002386 if (Decl->TypeForDecl)
2387 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002388
Douglas Gregor1c283312010-08-11 12:19:30 +00002389 // FIXME: redeclarations?
2390 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2391 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2392 Decl->TypeForDecl = T;
2393 Types.push_back(T);
2394 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002395}
2396
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002397/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2398/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002399/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002400/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002401/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002402QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002403 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002404 if (tofExpr->isTypeDependent()) {
2405 llvm::FoldingSetNodeID ID;
2406 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002407
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002408 void *InsertPos = 0;
2409 DependentTypeOfExprType *Canon
2410 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2411 if (Canon) {
2412 // We already have a "canonical" version of an identical, dependent
2413 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002414 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002415 QualType((TypeOfExprType*)Canon, 0));
2416 }
2417 else {
2418 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002419 Canon
2420 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002421 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2422 toe = Canon;
2423 }
2424 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002425 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002426 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002427 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002428 Types.push_back(toe);
2429 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002430}
2431
Steve Naroffa773cd52007-08-01 18:02:17 +00002432/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2433/// TypeOfType AST's. The only motivation to unique these nodes would be
2434/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002435/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002436/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002437QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002438 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002439 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002440 Types.push_back(tot);
2441 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002442}
2443
Anders Carlssonad6bd352009-06-24 21:24:56 +00002444/// getDecltypeForExpr - Given an expr, will return the decltype for that
2445/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002446static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002447 if (e->isTypeDependent())
2448 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002449
Anders Carlssonad6bd352009-06-24 21:24:56 +00002450 // If e is an id expression or a class member access, decltype(e) is defined
2451 // as the type of the entity named by e.
2452 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2453 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2454 return VD->getType();
2455 }
2456 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2457 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2458 return FD->getType();
2459 }
2460 // If e is a function call or an invocation of an overloaded operator,
2461 // (parentheses around e are ignored), decltype(e) is defined as the
2462 // return type of that function.
2463 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2464 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002465
Anders Carlssonad6bd352009-06-24 21:24:56 +00002466 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002467
2468 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002469 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002470 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002471 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002472
Anders Carlssonad6bd352009-06-24 21:24:56 +00002473 return T;
2474}
2475
Anders Carlsson81df7b82009-06-24 19:06:50 +00002476/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2477/// DecltypeType AST's. The only motivation to unique these nodes would be
2478/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002479/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002480/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002481QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002482 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002483 if (e->isTypeDependent()) {
2484 llvm::FoldingSetNodeID ID;
2485 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002486
Douglas Gregora21f6c32009-07-30 23:36:40 +00002487 void *InsertPos = 0;
2488 DependentDecltypeType *Canon
2489 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2490 if (Canon) {
2491 // We already have a "canonical" version of an equivalent, dependent
2492 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002493 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002494 QualType((DecltypeType*)Canon, 0));
2495 }
2496 else {
2497 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002498 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002499 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2500 dt = Canon;
2501 }
2502 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002503 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002504 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002505 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002506 Types.push_back(dt);
2507 return QualType(dt, 0);
2508}
2509
Chris Lattnerfb072462007-01-23 05:45:31 +00002510/// getTagDeclType - Return the unique reference to the type for the
2511/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002512QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002513 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002514 // FIXME: What is the design on getTagDeclType when it requires casting
2515 // away const? mutable?
2516 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002517}
2518
Mike Stump11289f42009-09-09 15:08:12 +00002519/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2520/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2521/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002522CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002523 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002524}
Chris Lattnerfb072462007-01-23 05:45:31 +00002525
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002526/// getSignedWCharType - Return the type of "signed wchar_t".
2527/// Used when in C++, as a GCC extension.
2528QualType ASTContext::getSignedWCharType() const {
2529 // FIXME: derive from "Target" ?
2530 return WCharTy;
2531}
2532
2533/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2534/// Used when in C++, as a GCC extension.
2535QualType ASTContext::getUnsignedWCharType() const {
2536 // FIXME: derive from "Target" ?
2537 return UnsignedIntTy;
2538}
2539
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002540/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2541/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2542QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002543 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002544}
2545
Chris Lattnera21ad802008-04-02 05:18:44 +00002546//===----------------------------------------------------------------------===//
2547// Type Operators
2548//===----------------------------------------------------------------------===//
2549
Jay Foad39c79802011-01-12 09:06:06 +00002550CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002551 // Push qualifiers into arrays, and then discard any remaining
2552 // qualifiers.
2553 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002554 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002555 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002556 QualType Result;
2557 if (isa<ArrayType>(Ty)) {
2558 Result = getArrayDecayedType(QualType(Ty,0));
2559 } else if (isa<FunctionType>(Ty)) {
2560 Result = getPointerType(QualType(Ty, 0));
2561 } else {
2562 Result = QualType(Ty, 0);
2563 }
2564
2565 return CanQualType::CreateUnsafe(Result);
2566}
2567
Chris Lattnered0d0792008-04-06 22:41:35 +00002568/// getCanonicalType - Return the canonical (structural) type corresponding to
2569/// the specified potentially non-canonical type. The non-canonical version
2570/// of a type may have many "decorated" versions of types. Decorators can
2571/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2572/// to be free of any of these, allowing two canonical types to be compared
2573/// for exact equality with a simple pointer comparison.
Jay Foad39c79802011-01-12 09:06:06 +00002574CanQualType ASTContext::getCanonicalType(QualType T) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002575 QualifierCollector Quals;
2576 const Type *Ptr = Quals.strip(T);
2577 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002578
John McCall8ccfcb52009-09-24 19:53:00 +00002579 // The canonical internal type will be the canonical type *except*
2580 // that we push type qualifiers down through array types.
2581
2582 // If there are no new qualifiers to push down, stop here.
2583 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002584 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002585
John McCall8ccfcb52009-09-24 19:53:00 +00002586 // If the type qualifiers are on an array type, get the canonical
2587 // type of the array with the qualifiers applied to the element
2588 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002589 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2590 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002591 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002592
Chris Lattner7adf0762008-08-04 07:31:14 +00002593 // Get the canonical version of the element with the extra qualifiers on it.
2594 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002595 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002596 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002597
Chris Lattner7adf0762008-08-04 07:31:14 +00002598 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002599 return CanQualType::CreateUnsafe(
2600 getConstantArrayType(NewEltTy, CAT->getSize(),
2601 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002602 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002603 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002604 return CanQualType::CreateUnsafe(
2605 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002606 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002607
Douglas Gregor4619e432008-12-05 23:32:09 +00002608 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002609 return CanQualType::CreateUnsafe(
2610 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002611 DSAT->getSizeExpr(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002612 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002613 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002614 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002615
Chris Lattner7adf0762008-08-04 07:31:14 +00002616 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002617 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002618 VAT->getSizeExpr(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002619 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002620 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002621 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002622}
2623
Chandler Carruth607f38e2009-12-29 07:16:59 +00002624QualType ASTContext::getUnqualifiedArrayType(QualType T,
2625 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002626 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002627 const ArrayType *AT = getAsArrayType(T);
2628 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002629 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002630 }
2631
Chandler Carruth607f38e2009-12-29 07:16:59 +00002632 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002633 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002634 if (Elt == UnqualElt)
2635 return T;
2636
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002637 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002638 return getConstantArrayType(UnqualElt, CAT->getSize(),
2639 CAT->getSizeModifier(), 0);
2640 }
2641
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002642 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002643 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2644 }
2645
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002646 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2647 return getVariableArrayType(UnqualElt,
John McCallc3007a22010-10-26 07:05:15 +00002648 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002649 VAT->getSizeModifier(),
2650 VAT->getIndexTypeCVRQualifiers(),
2651 VAT->getBracketsRange());
2652 }
2653
2654 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCallc3007a22010-10-26 07:05:15 +00002655 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002656 DSAT->getSizeModifier(), 0,
2657 SourceRange());
2658}
2659
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002660/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2661/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2662/// they point to and return true. If T1 and T2 aren't pointer types
2663/// or pointer-to-member types, or if they are not similar at this
2664/// level, returns false and leaves T1 and T2 unchanged. Top-level
2665/// qualifiers on T1 and T2 are ignored. This function will typically
2666/// be called in a loop that successively "unwraps" pointer and
2667/// pointer-to-member types to compare them at each level.
2668bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2669 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2670 *T2PtrType = T2->getAs<PointerType>();
2671 if (T1PtrType && T2PtrType) {
2672 T1 = T1PtrType->getPointeeType();
2673 T2 = T2PtrType->getPointeeType();
2674 return true;
2675 }
2676
2677 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2678 *T2MPType = T2->getAs<MemberPointerType>();
2679 if (T1MPType && T2MPType &&
2680 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2681 QualType(T2MPType->getClass(), 0))) {
2682 T1 = T1MPType->getPointeeType();
2683 T2 = T2MPType->getPointeeType();
2684 return true;
2685 }
2686
2687 if (getLangOptions().ObjC1) {
2688 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2689 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2690 if (T1OPType && T2OPType) {
2691 T1 = T1OPType->getPointeeType();
2692 T2 = T2OPType->getPointeeType();
2693 return true;
2694 }
2695 }
2696
2697 // FIXME: Block pointers, too?
2698
2699 return false;
2700}
2701
Jay Foad39c79802011-01-12 09:06:06 +00002702DeclarationNameInfo
2703ASTContext::getNameForTemplate(TemplateName Name,
2704 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002705 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002706 // DNInfo work in progress: CHECKME: what about DNLoc?
2707 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2708
John McCall847e2a12009-11-24 18:42:40 +00002709 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002710 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002711 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002712 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2713 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002714 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002715 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2716 // DNInfo work in progress: FIXME: source locations?
2717 DeclarationNameLoc DNLoc;
2718 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2719 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2720 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002721 }
2722 }
2723
John McCalld28ae272009-12-02 08:04:21 +00002724 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2725 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002726 // DNInfo work in progress: CHECKME: what about DNLoc?
2727 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002728}
2729
Jay Foad39c79802011-01-12 09:06:06 +00002730TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002731 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2732 if (TemplateTemplateParmDecl *TTP
2733 = dyn_cast<TemplateTemplateParmDecl>(Template))
2734 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2735
2736 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002737 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002738 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002739
John McCalld28ae272009-12-02 08:04:21 +00002740 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002741
Douglas Gregor6bc50582009-05-07 06:41:52 +00002742 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2743 assert(DTN && "Non-dependent template names must refer to template decls.");
2744 return DTN->CanonicalTemplateName;
2745}
2746
Douglas Gregoradee3e32009-11-11 23:06:43 +00002747bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2748 X = getCanonicalTemplateName(X);
2749 Y = getCanonicalTemplateName(Y);
2750 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2751}
2752
Mike Stump11289f42009-09-09 15:08:12 +00002753TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00002754ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00002755 switch (Arg.getKind()) {
2756 case TemplateArgument::Null:
2757 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002758
Douglas Gregora8e02e72009-07-28 23:00:59 +00002759 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002760 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002761
Douglas Gregora8e02e72009-07-28 23:00:59 +00002762 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002763 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002764
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002765 case TemplateArgument::Template:
2766 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002767
2768 case TemplateArgument::TemplateExpansion:
2769 return TemplateArgument(getCanonicalTemplateName(
2770 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00002771 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002772
Douglas Gregora8e02e72009-07-28 23:00:59 +00002773 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002774 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002775 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002776
Douglas Gregora8e02e72009-07-28 23:00:59 +00002777 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002778 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002779
Douglas Gregora8e02e72009-07-28 23:00:59 +00002780 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00002781 if (Arg.pack_size() == 0)
2782 return Arg;
2783
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002784 TemplateArgument *CanonArgs
2785 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00002786 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002787 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002788 AEnd = Arg.pack_end();
2789 A != AEnd; (void)++A, ++Idx)
2790 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002791
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002792 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00002793 }
2794 }
2795
2796 // Silence GCC warning
2797 assert(false && "Unhandled template argument kind");
2798 return TemplateArgument();
2799}
2800
Douglas Gregor333489b2009-03-27 23:10:48 +00002801NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00002802ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00002803 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002804 return 0;
2805
2806 switch (NNS->getKind()) {
2807 case NestedNameSpecifier::Identifier:
2808 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002809 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002810 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2811 NNS->getAsIdentifier());
2812
2813 case NestedNameSpecifier::Namespace:
2814 // A namespace is canonical; build a nested-name-specifier with
2815 // this namespace and no prefix.
2816 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2817
2818 case NestedNameSpecifier::TypeSpec:
2819 case NestedNameSpecifier::TypeSpecWithTemplate: {
2820 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00002821
2822 // If we have some kind of dependent-named type (e.g., "typename T::type"),
2823 // break it apart into its prefix and identifier, then reconsititute those
2824 // as the canonical nested-name-specifier. This is required to canonicalize
2825 // a dependent nested-name-specifier involving typedefs of dependent-name
2826 // types, e.g.,
2827 // typedef typename T::type T1;
2828 // typedef typename T1::type T2;
2829 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
2830 NestedNameSpecifier *Prefix
2831 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
2832 return NestedNameSpecifier::Create(*this, Prefix,
2833 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
2834 }
2835
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00002836 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00002837 if (const DependentTemplateSpecializationType *DTST
2838 = T->getAs<DependentTemplateSpecializationType>()) {
2839 NestedNameSpecifier *Prefix
2840 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
2841 TemplateName Name
2842 = getDependentTemplateName(Prefix, DTST->getIdentifier());
2843 T = getTemplateSpecializationType(Name,
2844 DTST->getArgs(), DTST->getNumArgs());
2845 T = getCanonicalType(T);
2846 }
2847
2848 return NestedNameSpecifier::Create(*this, 0, false, T.getTypePtr());
Douglas Gregor333489b2009-03-27 23:10:48 +00002849 }
2850
2851 case NestedNameSpecifier::Global:
2852 // The global specifier is canonical and unique.
2853 return NNS;
2854 }
2855
2856 // Required to silence a GCC warning
2857 return 0;
2858}
2859
Chris Lattner7adf0762008-08-04 07:31:14 +00002860
Jay Foad39c79802011-01-12 09:06:06 +00002861const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00002862 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002863 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002864 // Handle the common positive case fast.
2865 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2866 return AT;
2867 }
Mike Stump11289f42009-09-09 15:08:12 +00002868
John McCall8ccfcb52009-09-24 19:53:00 +00002869 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002870 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002871 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002872 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002873
John McCall8ccfcb52009-09-24 19:53:00 +00002874 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002875 // implements C99 6.7.3p8: "If the specification of an array type includes
2876 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002877
Chris Lattner7adf0762008-08-04 07:31:14 +00002878 // If we get here, we either have type qualifiers on the type, or we have
2879 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002880 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002881
John McCall8ccfcb52009-09-24 19:53:00 +00002882 QualifierCollector Qs;
John McCall717d9b02010-12-10 11:01:00 +00002883 const Type *Ty = Qs.strip(T.getDesugaredType(*this));
Mike Stump11289f42009-09-09 15:08:12 +00002884
Chris Lattner7adf0762008-08-04 07:31:14 +00002885 // If we have a simple case, just return now.
2886 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002887 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002888 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002889
Chris Lattner7adf0762008-08-04 07:31:14 +00002890 // Otherwise, we have an array and we have qualifiers on it. Push the
2891 // qualifiers into the array element type and return a new array type.
2892 // Get the canonical version of the element with the extra qualifiers on it.
2893 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002894 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002895
Chris Lattner7adf0762008-08-04 07:31:14 +00002896 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2897 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2898 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002899 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002900 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2901 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2902 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002903 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002904
Mike Stump11289f42009-09-09 15:08:12 +00002905 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002906 = dyn_cast<DependentSizedArrayType>(ATy))
2907 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002908 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002909 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00002910 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002911 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002912 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002913
Chris Lattner7adf0762008-08-04 07:31:14 +00002914 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002915 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002916 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00002917 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002918 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002919 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002920}
2921
Chris Lattnera21ad802008-04-02 05:18:44 +00002922/// getArrayDecayedType - Return the properly qualified result of decaying the
2923/// specified array type to a pointer. This operation is non-trivial when
2924/// handling typedefs etc. The canonical type of "T" must be an array type,
2925/// this returns a pointer to a properly qualified element of the array.
2926///
2927/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00002928QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00002929 // Get the element type with 'getAsArrayType' so that we don't lose any
2930 // typedefs in the element type of the array. This also handles propagation
2931 // of type qualifiers from the array type into the element type if present
2932 // (C99 6.7.3p8).
2933 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2934 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002935
Chris Lattner7adf0762008-08-04 07:31:14 +00002936 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002937
2938 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002939 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002940}
2941
Jay Foad39c79802011-01-12 09:06:06 +00002942QualType ASTContext::getBaseElementType(QualType QT) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002943 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002944 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2945 QT = AT->getElementType();
John McCall717d9b02010-12-10 11:01:00 +00002946 return Qs.apply(*this, QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002947}
2948
Jay Foad39c79802011-01-12 09:06:06 +00002949QualType ASTContext::getBaseElementType(const ArrayType *AT) const {
Anders Carlsson4bf82142009-09-25 01:23:32 +00002950 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002951
Anders Carlsson4bf82142009-09-25 01:23:32 +00002952 if (const ArrayType *AT = getAsArrayType(ElemTy))
2953 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002954
Anders Carlssone0808df2008-12-21 03:44:36 +00002955 return ElemTy;
2956}
2957
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002958/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002959uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002960ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2961 uint64_t ElementCount = 1;
2962 do {
2963 ElementCount *= CA->getSize().getZExtValue();
2964 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2965 } while (CA);
2966 return ElementCount;
2967}
2968
Steve Naroff0af91202007-04-27 21:51:21 +00002969/// getFloatingRank - Return a relative rank for floating point types.
2970/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002971static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002972 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002973 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002974
John McCall9dd450b2009-09-21 23:43:11 +00002975 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2976 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002977 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002978 case BuiltinType::Float: return FloatRank;
2979 case BuiltinType::Double: return DoubleRank;
2980 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002981 }
2982}
2983
Mike Stump11289f42009-09-09 15:08:12 +00002984/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2985/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002986/// 'typeDomain' is a real floating point or complex type.
2987/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002988QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2989 QualType Domain) const {
2990 FloatingRank EltRank = getFloatingRank(Size);
2991 if (Domain->isComplexType()) {
2992 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002993 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002994 case FloatRank: return FloatComplexTy;
2995 case DoubleRank: return DoubleComplexTy;
2996 case LongDoubleRank: return LongDoubleComplexTy;
2997 }
Steve Naroff0af91202007-04-27 21:51:21 +00002998 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002999
3000 assert(Domain->isRealFloatingType() && "Unknown domain!");
3001 switch (EltRank) {
3002 default: assert(0 && "getFloatingRank(): illegal value for rank");
3003 case FloatRank: return FloatTy;
3004 case DoubleRank: return DoubleTy;
3005 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003006 }
Steve Naroffe4718892007-04-27 18:30:00 +00003007}
3008
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003009/// getFloatingTypeOrder - Compare the rank of the two specified floating
3010/// point types, ignoring the domain of the type (i.e. 'double' ==
3011/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003012/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003013int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003014 FloatingRank LHSR = getFloatingRank(LHS);
3015 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003016
Chris Lattnerb90739d2008-04-06 23:38:49 +00003017 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003018 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003019 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003020 return 1;
3021 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003022}
3023
Chris Lattner76a00cf2008-04-06 22:59:24 +00003024/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3025/// routine will assert if passed a built-in type that isn't an integer or enum,
3026/// or if it is not canonicalized.
Jay Foad39c79802011-01-12 09:06:06 +00003027unsigned ASTContext::getIntegerRank(Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003028 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00003029 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003030 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003031
Chris Lattnerad3467e2010-12-25 23:25:43 +00003032 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3033 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003034 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3035
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003036 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3037 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3038
3039 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3040 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3041
Chris Lattner76a00cf2008-04-06 22:59:24 +00003042 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003043 default: assert(0 && "getIntegerRank(): not a built-in integer");
3044 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003045 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003046 case BuiltinType::Char_S:
3047 case BuiltinType::Char_U:
3048 case BuiltinType::SChar:
3049 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003050 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003051 case BuiltinType::Short:
3052 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003053 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003054 case BuiltinType::Int:
3055 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003056 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003057 case BuiltinType::Long:
3058 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003059 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003060 case BuiltinType::LongLong:
3061 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003062 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003063 case BuiltinType::Int128:
3064 case BuiltinType::UInt128:
3065 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003066 }
3067}
3068
Eli Friedman629ffb92009-08-20 04:21:42 +00003069/// \brief Whether this is a promotable bitfield reference according
3070/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3071///
3072/// \returns the type this bit-field will promote to, or NULL if no
3073/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003074QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003075 if (E->isTypeDependent() || E->isValueDependent())
3076 return QualType();
3077
Eli Friedman629ffb92009-08-20 04:21:42 +00003078 FieldDecl *Field = E->getBitField();
3079 if (!Field)
3080 return QualType();
3081
3082 QualType FT = Field->getType();
3083
3084 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3085 uint64_t BitWidth = BitWidthAP.getZExtValue();
3086 uint64_t IntSize = getTypeSize(IntTy);
3087 // GCC extension compatibility: if the bit-field size is less than or equal
3088 // to the size of int, it gets promoted no matter what its type is.
3089 // For instance, unsigned long bf : 4 gets promoted to signed int.
3090 if (BitWidth < IntSize)
3091 return IntTy;
3092
3093 if (BitWidth == IntSize)
3094 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3095
3096 // Types bigger than int are not subject to promotions, and therefore act
3097 // like the base type.
3098 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3099 // is ridiculous.
3100 return QualType();
3101}
3102
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003103/// getPromotedIntegerType - Returns the type that Promotable will
3104/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3105/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003106QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003107 assert(!Promotable.isNull());
3108 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003109 if (const EnumType *ET = Promotable->getAs<EnumType>())
3110 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003111 if (Promotable->isSignedIntegerType())
3112 return IntTy;
3113 uint64_t PromotableSize = getTypeSize(Promotable);
3114 uint64_t IntSize = getTypeSize(IntTy);
3115 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3116 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3117}
3118
Mike Stump11289f42009-09-09 15:08:12 +00003119/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003120/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003121/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003122int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003123 Type *LHSC = getCanonicalType(LHS).getTypePtr();
3124 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003125 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003126
Chris Lattner76a00cf2008-04-06 22:59:24 +00003127 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3128 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003129
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003130 unsigned LHSRank = getIntegerRank(LHSC);
3131 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003132
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003133 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3134 if (LHSRank == RHSRank) return 0;
3135 return LHSRank > RHSRank ? 1 : -1;
3136 }
Mike Stump11289f42009-09-09 15:08:12 +00003137
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003138 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3139 if (LHSUnsigned) {
3140 // If the unsigned [LHS] type is larger, return it.
3141 if (LHSRank >= RHSRank)
3142 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003143
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003144 // If the signed type can represent all values of the unsigned type, it
3145 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003146 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003147 return -1;
3148 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003149
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003150 // If the unsigned [RHS] type is larger, return it.
3151 if (RHSRank >= LHSRank)
3152 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003153
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003154 // If the signed type can represent all values of the unsigned type, it
3155 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003156 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003157 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003158}
Anders Carlsson98f07902007-08-17 05:31:46 +00003159
Anders Carlsson6d417272009-11-14 21:45:58 +00003160static RecordDecl *
Jay Foad39c79802011-01-12 09:06:06 +00003161CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
Anders Carlsson6d417272009-11-14 21:45:58 +00003162 SourceLocation L, IdentifierInfo *Id) {
3163 if (Ctx.getLangOptions().CPlusPlus)
3164 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3165 else
3166 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3167}
3168
Mike Stump11289f42009-09-09 15:08:12 +00003169// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003170QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003171 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003172 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003173 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003174 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003175 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003176
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003177 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003178
Anders Carlsson98f07902007-08-17 05:31:46 +00003179 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003180 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003181 // int flags;
3182 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003183 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003184 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003185 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003186 FieldTypes[3] = LongTy;
3187
Anders Carlsson98f07902007-08-17 05:31:46 +00003188 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003189 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003190 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003191 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003192 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003193 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003194 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003195 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003196 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003197 }
3198
Douglas Gregord5058122010-02-11 01:19:42 +00003199 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003200 }
Mike Stump11289f42009-09-09 15:08:12 +00003201
Anders Carlsson98f07902007-08-17 05:31:46 +00003202 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003203}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003204
Douglas Gregor512b0772009-04-23 22:29:11 +00003205void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003206 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003207 assert(Rec && "Invalid CFConstantStringType");
3208 CFConstantStringTypeDecl = Rec->getDecl();
3209}
3210
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003211// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003212QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003213 if (!NSConstantStringTypeDecl) {
3214 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003215 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003216 &Idents.get("__builtin_NSString"));
3217 NSConstantStringTypeDecl->startDefinition();
3218
3219 QualType FieldTypes[3];
3220
3221 // const int *isa;
3222 FieldTypes[0] = getPointerType(IntTy.withConst());
3223 // const char *str;
3224 FieldTypes[1] = getPointerType(CharTy.withConst());
3225 // unsigned int length;
3226 FieldTypes[2] = UnsignedIntTy;
3227
3228 // Create fields
3229 for (unsigned i = 0; i < 3; ++i) {
3230 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3231 SourceLocation(), 0,
3232 FieldTypes[i], /*TInfo=*/0,
3233 /*BitWidth=*/0,
3234 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003235 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003236 NSConstantStringTypeDecl->addDecl(Field);
3237 }
3238
3239 NSConstantStringTypeDecl->completeDefinition();
3240 }
3241
3242 return getTagDeclType(NSConstantStringTypeDecl);
3243}
3244
3245void ASTContext::setNSConstantStringType(QualType T) {
3246 const RecordType *Rec = T->getAs<RecordType>();
3247 assert(Rec && "Invalid NSConstantStringType");
3248 NSConstantStringTypeDecl = Rec->getDecl();
3249}
3250
Jay Foad39c79802011-01-12 09:06:06 +00003251QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003252 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003253 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003254 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003255 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003256 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003257
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003258 QualType FieldTypes[] = {
3259 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003260 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003261 getPointerType(UnsignedLongTy),
3262 getConstantArrayType(UnsignedLongTy,
3263 llvm::APInt(32, 5), ArrayType::Normal, 0)
3264 };
Mike Stump11289f42009-09-09 15:08:12 +00003265
Douglas Gregor91f84212008-12-11 16:49:14 +00003266 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003267 FieldDecl *Field = FieldDecl::Create(*this,
3268 ObjCFastEnumerationStateTypeDecl,
3269 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003270 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003271 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003272 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003273 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003274 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003275 }
Mike Stump11289f42009-09-09 15:08:12 +00003276
Douglas Gregord5058122010-02-11 01:19:42 +00003277 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003278 }
Mike Stump11289f42009-09-09 15:08:12 +00003279
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003280 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3281}
3282
Jay Foad39c79802011-01-12 09:06:06 +00003283QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003284 if (BlockDescriptorType)
3285 return getTagDeclType(BlockDescriptorType);
3286
3287 RecordDecl *T;
3288 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003289 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003290 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003291 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003292
3293 QualType FieldTypes[] = {
3294 UnsignedLongTy,
3295 UnsignedLongTy,
3296 };
3297
3298 const char *FieldNames[] = {
3299 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003300 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003301 };
3302
3303 for (size_t i = 0; i < 2; ++i) {
3304 FieldDecl *Field = FieldDecl::Create(*this,
3305 T,
3306 SourceLocation(),
3307 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003308 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003309 /*BitWidth=*/0,
3310 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003311 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003312 T->addDecl(Field);
3313 }
3314
Douglas Gregord5058122010-02-11 01:19:42 +00003315 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003316
3317 BlockDescriptorType = T;
3318
3319 return getTagDeclType(BlockDescriptorType);
3320}
3321
3322void ASTContext::setBlockDescriptorType(QualType T) {
3323 const RecordType *Rec = T->getAs<RecordType>();
3324 assert(Rec && "Invalid BlockDescriptorType");
3325 BlockDescriptorType = Rec->getDecl();
3326}
3327
Jay Foad39c79802011-01-12 09:06:06 +00003328QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003329 if (BlockDescriptorExtendedType)
3330 return getTagDeclType(BlockDescriptorExtendedType);
3331
3332 RecordDecl *T;
3333 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003334 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003335 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003336 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003337
3338 QualType FieldTypes[] = {
3339 UnsignedLongTy,
3340 UnsignedLongTy,
3341 getPointerType(VoidPtrTy),
3342 getPointerType(VoidPtrTy)
3343 };
3344
3345 const char *FieldNames[] = {
3346 "reserved",
3347 "Size",
3348 "CopyFuncPtr",
3349 "DestroyFuncPtr"
3350 };
3351
3352 for (size_t i = 0; i < 4; ++i) {
3353 FieldDecl *Field = FieldDecl::Create(*this,
3354 T,
3355 SourceLocation(),
3356 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003357 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003358 /*BitWidth=*/0,
3359 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003360 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003361 T->addDecl(Field);
3362 }
3363
Douglas Gregord5058122010-02-11 01:19:42 +00003364 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003365
3366 BlockDescriptorExtendedType = T;
3367
3368 return getTagDeclType(BlockDescriptorExtendedType);
3369}
3370
3371void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3372 const RecordType *Rec = T->getAs<RecordType>();
3373 assert(Rec && "Invalid BlockDescriptorType");
3374 BlockDescriptorExtendedType = Rec->getDecl();
3375}
3376
Jay Foad39c79802011-01-12 09:06:06 +00003377bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003378 if (Ty->isBlockPointerType())
3379 return true;
3380 if (isObjCNSObjectType(Ty))
3381 return true;
3382 if (Ty->isObjCObjectPointerType())
3383 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003384 if (getLangOptions().CPlusPlus) {
3385 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3386 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3387 return RD->hasConstCopyConstructor(*this);
3388
3389 }
3390 }
Mike Stump94967902009-10-21 18:16:27 +00003391 return false;
3392}
3393
Jay Foad39c79802011-01-12 09:06:06 +00003394QualType
3395ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003396 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003397 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003398 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003399 // unsigned int __flags;
3400 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003401 // void *__copy_helper; // as needed
3402 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003403 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003404 // } *
3405
Mike Stump94967902009-10-21 18:16:27 +00003406 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3407
3408 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003409 llvm::SmallString<36> Name;
3410 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3411 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003412 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003413 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003414 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003415 T->startDefinition();
3416 QualType Int32Ty = IntTy;
3417 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3418 QualType FieldTypes[] = {
3419 getPointerType(VoidPtrTy),
3420 getPointerType(getTagDeclType(T)),
3421 Int32Ty,
3422 Int32Ty,
3423 getPointerType(VoidPtrTy),
3424 getPointerType(VoidPtrTy),
3425 Ty
3426 };
3427
Daniel Dunbar56df9772010-08-17 22:39:59 +00003428 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003429 "__isa",
3430 "__forwarding",
3431 "__flags",
3432 "__size",
3433 "__copy_helper",
3434 "__destroy_helper",
3435 DeclName,
3436 };
3437
3438 for (size_t i = 0; i < 7; ++i) {
3439 if (!HasCopyAndDispose && i >=4 && i <= 5)
3440 continue;
3441 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3442 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003443 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003444 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003445 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003446 T->addDecl(Field);
3447 }
3448
Douglas Gregord5058122010-02-11 01:19:42 +00003449 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003450
3451 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003452}
3453
3454
3455QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003456 bool BlockHasCopyDispose,
Jay Foad39c79802011-01-12 09:06:06 +00003457 llvm::SmallVectorImpl<const Expr *> &Layout) const {
John McCall87fe5d52010-05-20 01:18:31 +00003458
Mike Stumpd0153282009-10-20 02:12:22 +00003459 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003460 llvm::SmallString<36> Name;
3461 llvm::raw_svector_ostream(Name) << "__block_literal_"
3462 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003463 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003464 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003465 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003466 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003467 QualType FieldTypes[] = {
3468 getPointerType(VoidPtrTy),
3469 IntTy,
3470 IntTy,
3471 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003472 (BlockHasCopyDispose ?
3473 getPointerType(getBlockDescriptorExtendedType()) :
3474 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003475 };
3476
3477 const char *FieldNames[] = {
3478 "__isa",
3479 "__flags",
3480 "__reserved",
3481 "__FuncPtr",
3482 "__descriptor"
3483 };
3484
3485 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003486 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003487 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003488 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003489 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003490 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003491 T->addDecl(Field);
3492 }
3493
John McCall87fe5d52010-05-20 01:18:31 +00003494 for (unsigned i = 0; i < Layout.size(); ++i) {
3495 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003496
John McCall87fe5d52010-05-20 01:18:31 +00003497 QualType FieldType = E->getType();
3498 IdentifierInfo *FieldName = 0;
3499 if (isa<CXXThisExpr>(E)) {
3500 FieldName = &Idents.get("this");
3501 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3502 const ValueDecl *D = BDRE->getDecl();
3503 FieldName = D->getIdentifier();
3504 if (BDRE->isByRef())
Daniel Dunbar56df9772010-08-17 22:39:59 +00003505 FieldType = BuildByRefType(D->getName(), FieldType);
John McCall87fe5d52010-05-20 01:18:31 +00003506 } else {
3507 // Padding.
3508 assert(isa<ConstantArrayType>(FieldType) &&
3509 isa<DeclRefExpr>(E) &&
3510 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3511 "doesn't match characteristics of padding decl");
3512 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003513
3514 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003515 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003516 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003517 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003518 T->addDecl(Field);
3519 }
3520
Douglas Gregord5058122010-02-11 01:19:42 +00003521 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003522
3523 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003524}
3525
Douglas Gregor512b0772009-04-23 22:29:11 +00003526void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003527 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003528 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3529 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3530}
3531
Anders Carlsson18acd442007-10-29 06:33:42 +00003532// This returns true if a type has been typedefed to BOOL:
3533// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003534static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003535 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003536 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3537 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003538
Anders Carlssond8499822007-10-29 05:01:08 +00003539 return false;
3540}
3541
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003542/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003543/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003544CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003545 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003546
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003547 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003548 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003549 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003550 // Treat arrays as pointers, since that's how they're passed in.
3551 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003552 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003553 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003554}
3555
3556static inline
3557std::string charUnitsToString(const CharUnits &CU) {
3558 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003559}
3560
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003561/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003562/// declaration.
3563void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
Jay Foad39c79802011-01-12 09:06:06 +00003564 std::string& S) const {
David Chisnall950a9512009-11-17 19:33:30 +00003565 const BlockDecl *Decl = Expr->getBlockDecl();
3566 QualType BlockTy =
3567 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3568 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003569 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003570 // Compute size of all parameters.
3571 // Start with computing size of a pointer in number of bytes.
3572 // FIXME: There might(should) be a better way of doing this computation!
3573 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003574 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3575 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003576 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003577 E = Decl->param_end(); PI != E; ++PI) {
3578 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003579 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003580 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003581 ParmOffset += sz;
3582 }
3583 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003584 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003585 // Block pointer and offset.
3586 S += "@?0";
3587 ParmOffset = PtrSize;
3588
3589 // Argument types.
3590 ParmOffset = PtrSize;
3591 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3592 Decl->param_end(); PI != E; ++PI) {
3593 ParmVarDecl *PVDecl = *PI;
3594 QualType PType = PVDecl->getOriginalType();
3595 if (const ArrayType *AT =
3596 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3597 // Use array's original type only if it has known number of
3598 // elements.
3599 if (!isa<ConstantArrayType>(AT))
3600 PType = PVDecl->getType();
3601 } else if (PType->isFunctionType())
3602 PType = PVDecl->getType();
3603 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003604 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003605 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003606 }
3607}
3608
David Chisnall50e4eba2010-12-30 14:05:53 +00003609void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3610 std::string& S) {
3611 // Encode result type.
3612 getObjCEncodingForType(Decl->getResultType(), S);
3613 CharUnits ParmOffset;
3614 // Compute size of all parameters.
3615 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3616 E = Decl->param_end(); PI != E; ++PI) {
3617 QualType PType = (*PI)->getType();
3618 CharUnits sz = getObjCEncodingTypeSize(PType);
3619 assert (sz.isPositive() &&
3620 "getObjCEncodingForMethodDecl - Incomplete param type");
3621 ParmOffset += sz;
3622 }
3623 S += charUnitsToString(ParmOffset);
3624 ParmOffset = CharUnits::Zero();
3625
3626 // Argument types.
3627 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3628 E = Decl->param_end(); PI != E; ++PI) {
3629 ParmVarDecl *PVDecl = *PI;
3630 QualType PType = PVDecl->getOriginalType();
3631 if (const ArrayType *AT =
3632 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3633 // Use array's original type only if it has known number of
3634 // elements.
3635 if (!isa<ConstantArrayType>(AT))
3636 PType = PVDecl->getType();
3637 } else if (PType->isFunctionType())
3638 PType = PVDecl->getType();
3639 getObjCEncodingForType(PType, S);
3640 S += charUnitsToString(ParmOffset);
3641 ParmOffset += getObjCEncodingTypeSize(PType);
3642 }
3643}
3644
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003645/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003646/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003647void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003648 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003649 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003650 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003651 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003652 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003653 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003654 // Compute size of all parameters.
3655 // Start with computing size of a pointer in number of bytes.
3656 // FIXME: There might(should) be a better way of doing this computation!
3657 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003658 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003659 // The first two arguments (self and _cmd) are pointers; account for
3660 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003661 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003662 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003663 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003664 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003665 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003666 assert (sz.isPositive() &&
3667 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003668 ParmOffset += sz;
3669 }
Ken Dyck40775002010-01-11 17:06:35 +00003670 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003671 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003672 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003673
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003674 // Argument types.
3675 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003676 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003677 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003678 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003679 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003680 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003681 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3682 // Use array's original type only if it has known number of
3683 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003684 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003685 PType = PVDecl->getType();
3686 } else if (PType->isFunctionType())
3687 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003688 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003689 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003690 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003691 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003692 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003693 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003694 }
3695}
3696
Daniel Dunbar4932b362008-08-28 04:38:10 +00003697/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003698/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003699/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3700/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003701/// Property attributes are stored as a comma-delimited C string. The simple
3702/// attributes readonly and bycopy are encoded as single characters. The
3703/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3704/// encoded as single characters, followed by an identifier. Property types
3705/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003706/// these attributes are defined by the following enumeration:
3707/// @code
3708/// enum PropertyAttributes {
3709/// kPropertyReadOnly = 'R', // property is read-only.
3710/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3711/// kPropertyByref = '&', // property is a reference to the value last assigned
3712/// kPropertyDynamic = 'D', // property is dynamic
3713/// kPropertyGetter = 'G', // followed by getter selector name
3714/// kPropertySetter = 'S', // followed by setter selector name
3715/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3716/// kPropertyType = 't' // followed by old-style type encoding.
3717/// kPropertyWeak = 'W' // 'weak' property
3718/// kPropertyStrong = 'P' // property GC'able
3719/// kPropertyNonAtomic = 'N' // property non-atomic
3720/// };
3721/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003722void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003723 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003724 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003725 // Collect information from the property implementation decl(s).
3726 bool Dynamic = false;
3727 ObjCPropertyImplDecl *SynthesizePID = 0;
3728
3729 // FIXME: Duplicated code due to poor abstraction.
3730 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003731 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003732 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3733 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003734 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003735 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003736 ObjCPropertyImplDecl *PID = *i;
3737 if (PID->getPropertyDecl() == PD) {
3738 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3739 Dynamic = true;
3740 } else {
3741 SynthesizePID = PID;
3742 }
3743 }
3744 }
3745 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003746 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003747 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003748 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003749 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003750 ObjCPropertyImplDecl *PID = *i;
3751 if (PID->getPropertyDecl() == PD) {
3752 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3753 Dynamic = true;
3754 } else {
3755 SynthesizePID = PID;
3756 }
3757 }
Mike Stump11289f42009-09-09 15:08:12 +00003758 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003759 }
3760 }
3761
3762 // FIXME: This is not very efficient.
3763 S = "T";
3764
3765 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003766 // GCC has some special rules regarding encoding of properties which
3767 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003768 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003769 true /* outermost type */,
3770 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003771
3772 if (PD->isReadOnly()) {
3773 S += ",R";
3774 } else {
3775 switch (PD->getSetterKind()) {
3776 case ObjCPropertyDecl::Assign: break;
3777 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003778 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003779 }
3780 }
3781
3782 // It really isn't clear at all what this means, since properties
3783 // are "dynamic by default".
3784 if (Dynamic)
3785 S += ",D";
3786
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003787 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3788 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003789
Daniel Dunbar4932b362008-08-28 04:38:10 +00003790 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3791 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003792 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003793 }
3794
3795 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3796 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003797 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003798 }
3799
3800 if (SynthesizePID) {
3801 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3802 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003803 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003804 }
3805
3806 // FIXME: OBJCGC: weak & strong
3807}
3808
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003809/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003810/// Another legacy compatibility encoding: 32-bit longs are encoded as
3811/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003812/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3813///
3814void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003815 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003816 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00003817 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003818 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003819 else
Jay Foad39c79802011-01-12 09:06:06 +00003820 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003821 PointeeTy = IntTy;
3822 }
3823 }
3824}
3825
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003826void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00003827 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003828 // We follow the behavior of gcc, expanding structures which are
3829 // directly pointed to, and expanding embedded structures. Note that
3830 // these rules are sufficient to prevent recursive encoding of the
3831 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003832 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003833 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003834}
3835
David Chisnallb190a2c2010-06-04 01:10:52 +00003836static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3837 switch (T->getAs<BuiltinType>()->getKind()) {
3838 default: assert(0 && "Unhandled builtin type kind");
3839 case BuiltinType::Void: return 'v';
3840 case BuiltinType::Bool: return 'B';
3841 case BuiltinType::Char_U:
3842 case BuiltinType::UChar: return 'C';
3843 case BuiltinType::UShort: return 'S';
3844 case BuiltinType::UInt: return 'I';
3845 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00003846 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003847 case BuiltinType::UInt128: return 'T';
3848 case BuiltinType::ULongLong: return 'Q';
3849 case BuiltinType::Char_S:
3850 case BuiltinType::SChar: return 'c';
3851 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00003852 case BuiltinType::WChar_S:
3853 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00003854 case BuiltinType::Int: return 'i';
3855 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00003856 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003857 case BuiltinType::LongLong: return 'q';
3858 case BuiltinType::Int128: return 't';
3859 case BuiltinType::Float: return 'f';
3860 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00003861 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00003862 }
3863}
3864
Jay Foad39c79802011-01-12 09:06:06 +00003865static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003866 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003867 const Expr *E = FD->getBitWidth();
3868 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003869 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003870 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3871 // The GNU runtime requires more information; bitfields are encoded as b,
3872 // then the offset (in bits) of the first element, then the type of the
3873 // bitfield, then the size in bits. For example, in this structure:
3874 //
3875 // struct
3876 // {
3877 // int integer;
3878 // int flags:2;
3879 // };
3880 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3881 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3882 // information is not especially sensible, but we're stuck with it for
3883 // compatibility with GCC, although providing it breaks anything that
3884 // actually uses runtime introspection and wants to work on both runtimes...
3885 if (!Ctx->getLangOptions().NeXTRuntime) {
3886 const RecordDecl *RD = FD->getParent();
3887 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3888 // FIXME: This same linear search is also used in ExprConstant - it might
3889 // be better if the FieldDecl stored its offset. We'd be increasing the
3890 // size of the object slightly, but saving some time every time it is used.
3891 unsigned i = 0;
3892 for (RecordDecl::field_iterator Field = RD->field_begin(),
3893 FieldEnd = RD->field_end();
3894 Field != FieldEnd; (void)++Field, ++i) {
3895 if (*Field == FD)
3896 break;
3897 }
3898 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00003899 if (T->isEnumeralType())
3900 S += 'i';
3901 else
Jay Foad39c79802011-01-12 09:06:06 +00003902 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00003903 }
3904 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003905 S += llvm::utostr(N);
3906}
3907
Daniel Dunbar07d07852009-10-18 21:17:35 +00003908// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003909void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3910 bool ExpandPointedToStructures,
3911 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003912 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003913 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00003914 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00003915 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003916 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003917 return EncodeBitField(this, S, T, FD);
3918 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003919 return;
3920 }
Mike Stump11289f42009-09-09 15:08:12 +00003921
John McCall9dd450b2009-09-21 23:43:11 +00003922 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003923 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003924 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003925 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003926 return;
3927 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003928
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003929 // encoding for pointer or r3eference types.
3930 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003931 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003932 if (PT->isObjCSelType()) {
3933 S += ':';
3934 return;
3935 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003936 PointeeTy = PT->getPointeeType();
3937 }
3938 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3939 PointeeTy = RT->getPointeeType();
3940 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003941 bool isReadOnly = false;
3942 // For historical/compatibility reasons, the read-only qualifier of the
3943 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3944 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003945 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003946 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003947 if (OutermostType && T.isConstQualified()) {
3948 isReadOnly = true;
3949 S += 'r';
3950 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003951 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003952 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003953 while (P->getAs<PointerType>())
3954 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003955 if (P.isConstQualified()) {
3956 isReadOnly = true;
3957 S += 'r';
3958 }
3959 }
3960 if (isReadOnly) {
3961 // Another legacy compatibility encoding. Some ObjC qualifier and type
3962 // combinations need to be rearranged.
3963 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003964 if (llvm::StringRef(S).endswith("nr"))
3965 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003966 }
Mike Stump11289f42009-09-09 15:08:12 +00003967
Anders Carlssond8499822007-10-29 05:01:08 +00003968 if (PointeeTy->isCharType()) {
3969 // char pointer types should be encoded as '*' unless it is a
3970 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003971 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003972 S += '*';
3973 return;
3974 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003975 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003976 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3977 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3978 S += '#';
3979 return;
3980 }
3981 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3982 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3983 S += '@';
3984 return;
3985 }
3986 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003987 }
Anders Carlssond8499822007-10-29 05:01:08 +00003988 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003989 getLegacyIntegralTypeEncoding(PointeeTy);
3990
Mike Stump11289f42009-09-09 15:08:12 +00003991 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003992 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003993 return;
3994 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003995
Chris Lattnere7cabb92009-07-13 00:10:46 +00003996 if (const ArrayType *AT =
3997 // Ignore type qualifiers etc.
3998 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003999 if (isa<IncompleteArrayType>(AT)) {
4000 // Incomplete arrays are encoded as a pointer to the array element.
4001 S += '^';
4002
Mike Stump11289f42009-09-09 15:08:12 +00004003 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004004 false, ExpandStructures, FD);
4005 } else {
4006 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004007
Anders Carlssond05f44b2009-02-22 01:38:57 +00004008 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4009 S += llvm::utostr(CAT->getSize().getZExtValue());
4010 else {
4011 //Variable length arrays are encoded as a regular array with 0 elements.
4012 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4013 S += '0';
4014 }
Mike Stump11289f42009-09-09 15:08:12 +00004015
4016 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004017 false, ExpandStructures, FD);
4018 S += ']';
4019 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004020 return;
4021 }
Mike Stump11289f42009-09-09 15:08:12 +00004022
John McCall9dd450b2009-09-21 23:43:11 +00004023 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004024 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004025 return;
4026 }
Mike Stump11289f42009-09-09 15:08:12 +00004027
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004028 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004029 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004030 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004031 // Anonymous structures print as '?'
4032 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4033 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004034 if (ClassTemplateSpecializationDecl *Spec
4035 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4036 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4037 std::string TemplateArgsStr
4038 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004039 TemplateArgs.data(),
4040 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004041 (*this).PrintingPolicy);
4042
4043 S += TemplateArgsStr;
4044 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004045 } else {
4046 S += '?';
4047 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004048 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004049 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004050 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4051 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004052 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004053 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004054 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004055 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004056 S += '"';
4057 }
Mike Stump11289f42009-09-09 15:08:12 +00004058
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004059 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004060 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004061 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004062 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004063 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004064 QualType qt = Field->getType();
4065 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004066 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004067 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004068 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004069 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004070 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004071 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004072 return;
4073 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004074
Chris Lattnere7cabb92009-07-13 00:10:46 +00004075 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004076 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004077 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004078 else
4079 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004080 return;
4081 }
Mike Stump11289f42009-09-09 15:08:12 +00004082
Chris Lattnere7cabb92009-07-13 00:10:46 +00004083 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004084 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004085 return;
4086 }
Mike Stump11289f42009-09-09 15:08:12 +00004087
John McCall8b07ec22010-05-15 11:32:37 +00004088 // Ignore protocol qualifiers when mangling at this level.
4089 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4090 T = OT->getBaseType();
4091
John McCall8ccfcb52009-09-24 19:53:00 +00004092 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004093 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004094 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004095 S += '{';
4096 const IdentifierInfo *II = OI->getIdentifier();
4097 S += II->getName();
4098 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004099 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4100 DeepCollectObjCIvars(OI, true, Ivars);
4101 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4102 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4103 if (Field->isBitField())
4104 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004105 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004106 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004107 }
4108 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004109 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004110 }
Mike Stump11289f42009-09-09 15:08:12 +00004111
John McCall9dd450b2009-09-21 23:43:11 +00004112 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004113 if (OPT->isObjCIdType()) {
4114 S += '@';
4115 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004116 }
Mike Stump11289f42009-09-09 15:08:12 +00004117
Steve Narofff0c86112009-10-28 22:03:49 +00004118 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4119 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4120 // Since this is a binary compatibility issue, need to consult with runtime
4121 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004122 S += '#';
4123 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004124 }
Mike Stump11289f42009-09-09 15:08:12 +00004125
Chris Lattnere7cabb92009-07-13 00:10:46 +00004126 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004127 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004128 ExpandPointedToStructures,
4129 ExpandStructures, FD);
4130 if (FD || EncodingProperty) {
4131 // Note that we do extended encoding of protocol qualifer list
4132 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004133 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004134 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4135 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004136 S += '<';
4137 S += (*I)->getNameAsString();
4138 S += '>';
4139 }
4140 S += '"';
4141 }
4142 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004143 }
Mike Stump11289f42009-09-09 15:08:12 +00004144
Chris Lattnere7cabb92009-07-13 00:10:46 +00004145 QualType PointeeTy = OPT->getPointeeType();
4146 if (!EncodingProperty &&
4147 isa<TypedefType>(PointeeTy.getTypePtr())) {
4148 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004149 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004150 // {...};
4151 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004152 getObjCEncodingForTypeImpl(PointeeTy, S,
4153 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004154 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004155 return;
4156 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004157
4158 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004159 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004160 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004161 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004162 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4163 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004164 S += '<';
4165 S += (*I)->getNameAsString();
4166 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004167 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004168 S += '"';
4169 }
4170 return;
4171 }
Mike Stump11289f42009-09-09 15:08:12 +00004172
John McCalla9e6e8d2010-05-17 23:56:34 +00004173 // gcc just blithely ignores member pointers.
4174 // TODO: maybe there should be a mangling for these
4175 if (T->getAs<MemberPointerType>())
4176 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004177
4178 if (T->isVectorType()) {
4179 // This matches gcc's encoding, even though technically it is
4180 // insufficient.
4181 // FIXME. We should do a better job than gcc.
4182 return;
4183 }
4184
Chris Lattnere7cabb92009-07-13 00:10:46 +00004185 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004186}
4187
Mike Stump11289f42009-09-09 15:08:12 +00004188void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004189 std::string& S) const {
4190 if (QT & Decl::OBJC_TQ_In)
4191 S += 'n';
4192 if (QT & Decl::OBJC_TQ_Inout)
4193 S += 'N';
4194 if (QT & Decl::OBJC_TQ_Out)
4195 S += 'o';
4196 if (QT & Decl::OBJC_TQ_Bycopy)
4197 S += 'O';
4198 if (QT & Decl::OBJC_TQ_Byref)
4199 S += 'R';
4200 if (QT & Decl::OBJC_TQ_Oneway)
4201 S += 'V';
4202}
4203
Chris Lattnere7cabb92009-07-13 00:10:46 +00004204void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004205 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004206
Anders Carlsson87c149b2007-10-11 01:00:40 +00004207 BuiltinVaListType = T;
4208}
4209
Chris Lattnere7cabb92009-07-13 00:10:46 +00004210void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004211 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004212}
4213
Chris Lattnere7cabb92009-07-13 00:10:46 +00004214void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004215 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004216}
4217
Chris Lattnere7cabb92009-07-13 00:10:46 +00004218void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004219 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004220}
4221
Chris Lattnere7cabb92009-07-13 00:10:46 +00004222void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004223 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004224}
4225
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004226void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004227 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004228 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004229
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004230 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004231}
4232
John McCalld28ae272009-12-02 08:04:21 +00004233/// \brief Retrieve the template name that corresponds to a non-empty
4234/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004235TemplateName
4236ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4237 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004238 unsigned size = End - Begin;
4239 assert(size > 1 && "set is not overloaded!");
4240
4241 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4242 size * sizeof(FunctionTemplateDecl*));
4243 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4244
4245 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004246 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004247 NamedDecl *D = *I;
4248 assert(isa<FunctionTemplateDecl>(D) ||
4249 (isa<UsingShadowDecl>(D) &&
4250 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4251 *Storage++ = D;
4252 }
4253
4254 return TemplateName(OT);
4255}
4256
Douglas Gregordc572a32009-03-30 22:58:21 +00004257/// \brief Retrieve the template name that represents a qualified
4258/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004259TemplateName
4260ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4261 bool TemplateKeyword,
4262 TemplateDecl *Template) const {
Douglas Gregorc42075a2010-02-04 18:10:26 +00004263 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004264 llvm::FoldingSetNodeID ID;
4265 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4266
4267 void *InsertPos = 0;
4268 QualifiedTemplateName *QTN =
4269 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4270 if (!QTN) {
4271 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4272 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4273 }
4274
4275 return TemplateName(QTN);
4276}
4277
4278/// \brief Retrieve the template name that represents a dependent
4279/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004280TemplateName
4281ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4282 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004283 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004284 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004285
4286 llvm::FoldingSetNodeID ID;
4287 DependentTemplateName::Profile(ID, NNS, Name);
4288
4289 void *InsertPos = 0;
4290 DependentTemplateName *QTN =
4291 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4292
4293 if (QTN)
4294 return TemplateName(QTN);
4295
4296 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4297 if (CanonNNS == NNS) {
4298 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4299 } else {
4300 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4301 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004302 DependentTemplateName *CheckQTN =
4303 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4304 assert(!CheckQTN && "Dependent type name canonicalization broken");
4305 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004306 }
4307
4308 DependentTemplateNames.InsertNode(QTN, InsertPos);
4309 return TemplateName(QTN);
4310}
4311
Douglas Gregor71395fa2009-11-04 00:56:37 +00004312/// \brief Retrieve the template name that represents a dependent
4313/// template name such as \c MetaFun::template operator+.
4314TemplateName
4315ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004316 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004317 assert((!NNS || NNS->isDependent()) &&
4318 "Nested name specifier must be dependent");
4319
4320 llvm::FoldingSetNodeID ID;
4321 DependentTemplateName::Profile(ID, NNS, Operator);
4322
4323 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004324 DependentTemplateName *QTN
4325 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004326
4327 if (QTN)
4328 return TemplateName(QTN);
4329
4330 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4331 if (CanonNNS == NNS) {
4332 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4333 } else {
4334 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4335 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004336
4337 DependentTemplateName *CheckQTN
4338 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4339 assert(!CheckQTN && "Dependent template name canonicalization broken");
4340 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004341 }
4342
4343 DependentTemplateNames.InsertNode(QTN, InsertPos);
4344 return TemplateName(QTN);
4345}
4346
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004347/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004348/// TargetInfo, produce the corresponding type. The unsigned @p Type
4349/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004350CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004351 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004352 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004353 case TargetInfo::SignedShort: return ShortTy;
4354 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4355 case TargetInfo::SignedInt: return IntTy;
4356 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4357 case TargetInfo::SignedLong: return LongTy;
4358 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4359 case TargetInfo::SignedLongLong: return LongLongTy;
4360 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4361 }
4362
4363 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004364 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004365}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004366
4367//===----------------------------------------------------------------------===//
4368// Type Predicates.
4369//===----------------------------------------------------------------------===//
4370
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004371/// isObjCNSObjectType - Return true if this is an NSObject object using
4372/// NSObject attribute on a c-style pointer type.
4373/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004374/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004375///
4376bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4377 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4378 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004379 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004380 return true;
4381 }
Mike Stump11289f42009-09-09 15:08:12 +00004382 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004383}
4384
Fariborz Jahanian96207692009-02-18 21:49:28 +00004385/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4386/// garbage collection attribute.
4387///
John McCall553d45a2011-01-12 00:34:59 +00004388Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4389 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4390 return Qualifiers::GCNone;
4391
4392 assert(getLangOptions().ObjC1);
4393 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4394
4395 // Default behaviour under objective-C's gc is for ObjC pointers
4396 // (or pointers to them) be treated as though they were declared
4397 // as __strong.
4398 if (GCAttrs == Qualifiers::GCNone) {
4399 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4400 return Qualifiers::Strong;
4401 else if (Ty->isPointerType())
4402 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4403 } else {
4404 // It's not valid to set GC attributes on anything that isn't a
4405 // pointer.
4406#ifndef NDEBUG
4407 QualType CT = Ty->getCanonicalTypeInternal();
4408 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4409 CT = AT->getElementType();
4410 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4411#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004412 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004413 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004414}
4415
Chris Lattner49af6a42008-04-07 06:51:04 +00004416//===----------------------------------------------------------------------===//
4417// Type Compatibility Testing
4418//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004419
Mike Stump11289f42009-09-09 15:08:12 +00004420/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004421/// compatible.
4422static bool areCompatVectorTypes(const VectorType *LHS,
4423 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004424 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004425 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004426 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004427}
4428
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004429bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4430 QualType SecondVec) {
4431 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4432 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4433
4434 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4435 return true;
4436
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004437 // Treat Neon vector types and most AltiVec vector types as if they are the
4438 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004439 const VectorType *First = FirstVec->getAs<VectorType>();
4440 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004441 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004442 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004443 First->getVectorKind() != VectorType::AltiVecPixel &&
4444 First->getVectorKind() != VectorType::AltiVecBool &&
4445 Second->getVectorKind() != VectorType::AltiVecPixel &&
4446 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004447 return true;
4448
4449 return false;
4450}
4451
Steve Naroff8e6aee52009-07-23 01:01:38 +00004452//===----------------------------------------------------------------------===//
4453// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4454//===----------------------------------------------------------------------===//
4455
4456/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4457/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004458bool
4459ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4460 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004461 if (lProto == rProto)
4462 return true;
4463 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4464 E = rProto->protocol_end(); PI != E; ++PI)
4465 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4466 return true;
4467 return false;
4468}
4469
Steve Naroff8e6aee52009-07-23 01:01:38 +00004470/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4471/// return true if lhs's protocols conform to rhs's protocol; false
4472/// otherwise.
4473bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4474 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4475 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4476 return false;
4477}
4478
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004479/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4480/// Class<p1, ...>.
4481bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4482 QualType rhs) {
4483 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4484 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4485 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4486
4487 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4488 E = lhsQID->qual_end(); I != E; ++I) {
4489 bool match = false;
4490 ObjCProtocolDecl *lhsProto = *I;
4491 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4492 E = rhsOPT->qual_end(); J != E; ++J) {
4493 ObjCProtocolDecl *rhsProto = *J;
4494 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4495 match = true;
4496 break;
4497 }
4498 }
4499 if (!match)
4500 return false;
4501 }
4502 return true;
4503}
4504
Steve Naroff8e6aee52009-07-23 01:01:38 +00004505/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4506/// ObjCQualifiedIDType.
4507bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4508 bool compare) {
4509 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004510 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004511 lhs->isObjCIdType() || lhs->isObjCClassType())
4512 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004513 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004514 rhs->isObjCIdType() || rhs->isObjCClassType())
4515 return true;
4516
4517 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004518 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004519
Steve Naroff8e6aee52009-07-23 01:01:38 +00004520 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004521
Steve Naroff8e6aee52009-07-23 01:01:38 +00004522 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004523 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004524 // make sure we check the class hierarchy.
4525 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4526 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4527 E = lhsQID->qual_end(); I != E; ++I) {
4528 // when comparing an id<P> on lhs with a static type on rhs,
4529 // see if static class implements all of id's protocols, directly or
4530 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004531 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004532 return false;
4533 }
4534 }
4535 // If there are no qualifiers and no interface, we have an 'id'.
4536 return true;
4537 }
Mike Stump11289f42009-09-09 15:08:12 +00004538 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004539 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4540 E = lhsQID->qual_end(); I != E; ++I) {
4541 ObjCProtocolDecl *lhsProto = *I;
4542 bool match = false;
4543
4544 // when comparing an id<P> on lhs with a static type on rhs,
4545 // see if static class implements all of id's protocols, directly or
4546 // through its super class and categories.
4547 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4548 E = rhsOPT->qual_end(); J != E; ++J) {
4549 ObjCProtocolDecl *rhsProto = *J;
4550 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4551 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4552 match = true;
4553 break;
4554 }
4555 }
Mike Stump11289f42009-09-09 15:08:12 +00004556 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004557 // make sure we check the class hierarchy.
4558 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4559 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4560 E = lhsQID->qual_end(); I != E; ++I) {
4561 // when comparing an id<P> on lhs with a static type on rhs,
4562 // see if static class implements all of id's protocols, directly or
4563 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004564 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004565 match = true;
4566 break;
4567 }
4568 }
4569 }
4570 if (!match)
4571 return false;
4572 }
Mike Stump11289f42009-09-09 15:08:12 +00004573
Steve Naroff8e6aee52009-07-23 01:01:38 +00004574 return true;
4575 }
Mike Stump11289f42009-09-09 15:08:12 +00004576
Steve Naroff8e6aee52009-07-23 01:01:38 +00004577 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4578 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4579
Mike Stump11289f42009-09-09 15:08:12 +00004580 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004581 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004582 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004583 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4584 E = lhsOPT->qual_end(); I != E; ++I) {
4585 ObjCProtocolDecl *lhsProto = *I;
4586 bool match = false;
4587
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004588 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004589 // see if static class implements all of id's protocols, directly or
4590 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004591 // First, lhs protocols in the qualifier list must be found, direct
4592 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004593 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4594 E = rhsQID->qual_end(); J != E; ++J) {
4595 ObjCProtocolDecl *rhsProto = *J;
4596 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4597 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4598 match = true;
4599 break;
4600 }
4601 }
4602 if (!match)
4603 return false;
4604 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004605
4606 // Static class's protocols, or its super class or category protocols
4607 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4608 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4609 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4610 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4611 // This is rather dubious but matches gcc's behavior. If lhs has
4612 // no type qualifier and its class has no static protocol(s)
4613 // assume that it is mismatch.
4614 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4615 return false;
4616 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4617 LHSInheritedProtocols.begin(),
4618 E = LHSInheritedProtocols.end(); I != E; ++I) {
4619 bool match = false;
4620 ObjCProtocolDecl *lhsProto = (*I);
4621 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4622 E = rhsQID->qual_end(); J != E; ++J) {
4623 ObjCProtocolDecl *rhsProto = *J;
4624 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4625 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4626 match = true;
4627 break;
4628 }
4629 }
4630 if (!match)
4631 return false;
4632 }
4633 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004634 return true;
4635 }
4636 return false;
4637}
4638
Eli Friedman47f77112008-08-22 00:56:42 +00004639/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004640/// compatible for assignment from RHS to LHS. This handles validation of any
4641/// protocol qualifiers on the LHS or RHS.
4642///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004643bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4644 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004645 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4646 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4647
Steve Naroff1329fa02009-07-15 18:40:39 +00004648 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004649 if (LHS->isObjCUnqualifiedIdOrClass() ||
4650 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004651 return true;
4652
John McCall8b07ec22010-05-15 11:32:37 +00004653 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004654 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4655 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004656 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004657
4658 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4659 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4660 QualType(RHSOPT,0));
4661
John McCall8b07ec22010-05-15 11:32:37 +00004662 // If we have 2 user-defined types, fall into that path.
4663 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004664 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004665
Steve Naroff8e6aee52009-07-23 01:01:38 +00004666 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004667}
4668
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004669/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4670/// for providing type-safty for objective-c pointers used to pass/return
4671/// arguments in block literals. When passed as arguments, passing 'A*' where
4672/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4673/// not OK. For the return type, the opposite is not OK.
4674bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4675 const ObjCObjectPointerType *LHSOPT,
4676 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004677 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004678 return true;
4679
4680 if (LHSOPT->isObjCBuiltinType()) {
4681 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4682 }
4683
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004684 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004685 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4686 QualType(RHSOPT,0),
4687 false);
4688
4689 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4690 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4691 if (LHS && RHS) { // We have 2 user-defined types.
4692 if (LHS != RHS) {
4693 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4694 return false;
4695 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4696 return true;
4697 }
4698 else
4699 return true;
4700 }
4701 return false;
4702}
4703
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004704/// getIntersectionOfProtocols - This routine finds the intersection of set
4705/// of protocols inherited from two distinct objective-c pointer objects.
4706/// It is used to build composite qualifier list of the composite type of
4707/// the conditional expression involving two objective-c pointer objects.
4708static
4709void getIntersectionOfProtocols(ASTContext &Context,
4710 const ObjCObjectPointerType *LHSOPT,
4711 const ObjCObjectPointerType *RHSOPT,
4712 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4713
John McCall8b07ec22010-05-15 11:32:37 +00004714 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4715 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4716 assert(LHS->getInterface() && "LHS must have an interface base");
4717 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004718
4719 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4720 unsigned LHSNumProtocols = LHS->getNumProtocols();
4721 if (LHSNumProtocols > 0)
4722 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4723 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004724 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004725 Context.CollectInheritedProtocols(LHS->getInterface(),
4726 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004727 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4728 LHSInheritedProtocols.end());
4729 }
4730
4731 unsigned RHSNumProtocols = RHS->getNumProtocols();
4732 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004733 ObjCProtocolDecl **RHSProtocols =
4734 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004735 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4736 if (InheritedProtocolSet.count(RHSProtocols[i]))
4737 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4738 }
4739 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004740 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004741 Context.CollectInheritedProtocols(RHS->getInterface(),
4742 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004743 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4744 RHSInheritedProtocols.begin(),
4745 E = RHSInheritedProtocols.end(); I != E; ++I)
4746 if (InheritedProtocolSet.count((*I)))
4747 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004748 }
4749}
4750
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004751/// areCommonBaseCompatible - Returns common base class of the two classes if
4752/// one found. Note that this is O'2 algorithm. But it will be called as the
4753/// last type comparison in a ?-exp of ObjC pointer types before a
4754/// warning is issued. So, its invokation is extremely rare.
4755QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004756 const ObjCObjectPointerType *Lptr,
4757 const ObjCObjectPointerType *Rptr) {
4758 const ObjCObjectType *LHS = Lptr->getObjectType();
4759 const ObjCObjectType *RHS = Rptr->getObjectType();
4760 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4761 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4762 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004763 return QualType();
4764
John McCall8b07ec22010-05-15 11:32:37 +00004765 while ((LDecl = LDecl->getSuperClass())) {
4766 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004767 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004768 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4769 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4770
4771 QualType Result = QualType(LHS, 0);
4772 if (!Protocols.empty())
4773 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4774 Result = getObjCObjectPointerType(Result);
4775 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004776 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004777 }
4778
4779 return QualType();
4780}
4781
John McCall8b07ec22010-05-15 11:32:37 +00004782bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4783 const ObjCObjectType *RHS) {
4784 assert(LHS->getInterface() && "LHS is not an interface type");
4785 assert(RHS->getInterface() && "RHS is not an interface type");
4786
Chris Lattner49af6a42008-04-07 06:51:04 +00004787 // Verify that the base decls are compatible: the RHS must be a subclass of
4788 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004789 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004790 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004791
Chris Lattner49af6a42008-04-07 06:51:04 +00004792 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4793 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004794 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004795 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004796
Chris Lattner49af6a42008-04-07 06:51:04 +00004797 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4798 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004799 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004800 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004801
John McCall8b07ec22010-05-15 11:32:37 +00004802 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4803 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004804 LHSPI != LHSPE; LHSPI++) {
4805 bool RHSImplementsProtocol = false;
4806
4807 // If the RHS doesn't implement the protocol on the left, the types
4808 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004809 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4810 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004811 RHSPI != RHSPE; RHSPI++) {
4812 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004813 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004814 break;
4815 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004816 }
4817 // FIXME: For better diagnostics, consider passing back the protocol name.
4818 if (!RHSImplementsProtocol)
4819 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004820 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004821 // The RHS implements all protocols listed on the LHS.
4822 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004823}
4824
Steve Naroffb7605152009-02-12 17:52:19 +00004825bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4826 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004827 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4828 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004829
Steve Naroff7cae42b2009-07-10 23:34:53 +00004830 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004831 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004832
4833 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4834 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004835}
4836
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004837bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4838 return canAssignObjCInterfaces(
4839 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4840 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4841}
4842
Mike Stump11289f42009-09-09 15:08:12 +00004843/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004844/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004845/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004846/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004847bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4848 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004849 if (getLangOptions().CPlusPlus)
4850 return hasSameType(LHS, RHS);
4851
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004852 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00004853}
4854
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004855bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4856 return !mergeTypes(LHS, RHS, true).isNull();
4857}
4858
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004859/// mergeTransparentUnionType - if T is a transparent union type and a member
4860/// of T is compatible with SubType, return the merged type, else return
4861/// QualType()
4862QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
4863 bool OfBlockPointer,
4864 bool Unqualified) {
4865 if (const RecordType *UT = T->getAsUnionType()) {
4866 RecordDecl *UD = UT->getDecl();
4867 if (UD->hasAttr<TransparentUnionAttr>()) {
4868 for (RecordDecl::field_iterator it = UD->field_begin(),
4869 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00004870 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004871 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
4872 if (!MT.isNull())
4873 return MT;
4874 }
4875 }
4876 }
4877
4878 return QualType();
4879}
4880
4881/// mergeFunctionArgumentTypes - merge two types which appear as function
4882/// argument types
4883QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
4884 bool OfBlockPointer,
4885 bool Unqualified) {
4886 // GNU extension: two types are compatible if they appear as a function
4887 // argument, one of the types is a transparent union type and the other
4888 // type is compatible with a union member
4889 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
4890 Unqualified);
4891 if (!lmerge.isNull())
4892 return lmerge;
4893
4894 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
4895 Unqualified);
4896 if (!rmerge.isNull())
4897 return rmerge;
4898
4899 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
4900}
4901
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004902QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004903 bool OfBlockPointer,
4904 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00004905 const FunctionType *lbase = lhs->getAs<FunctionType>();
4906 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004907 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4908 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004909 bool allLTypes = true;
4910 bool allRTypes = true;
4911
4912 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004913 QualType retType;
4914 if (OfBlockPointer)
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004915 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4916 Unqualified);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004917 else
John McCall8c6b56f2010-12-15 01:06:38 +00004918 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
4919 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004920 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004921
4922 if (Unqualified)
4923 retType = retType.getUnqualifiedType();
4924
4925 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4926 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4927 if (Unqualified) {
4928 LRetType = LRetType.getUnqualifiedType();
4929 RRetType = RRetType.getUnqualifiedType();
4930 }
4931
4932 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004933 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004934 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004935 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00004936
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004937 // FIXME: double check this
4938 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4939 // rbase->getRegParmAttr() != 0 &&
4940 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004941 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4942 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00004943
Douglas Gregor8c940862010-01-18 17:14:39 +00004944 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00004945 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00004946 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004947
John McCall8c6b56f2010-12-15 01:06:38 +00004948 // Regparm is part of the calling convention.
4949 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
4950 return QualType();
4951
4952 // It's noreturn if either type is.
4953 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
4954 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4955 if (NoReturn != lbaseInfo.getNoReturn())
4956 allLTypes = false;
4957 if (NoReturn != rbaseInfo.getNoReturn())
4958 allRTypes = false;
4959
4960 FunctionType::ExtInfo einfo(NoReturn,
4961 lbaseInfo.getRegParm(),
4962 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00004963
Eli Friedman47f77112008-08-22 00:56:42 +00004964 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004965 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4966 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004967 unsigned lproto_nargs = lproto->getNumArgs();
4968 unsigned rproto_nargs = rproto->getNumArgs();
4969
4970 // Compatible functions must have the same number of arguments
4971 if (lproto_nargs != rproto_nargs)
4972 return QualType();
4973
4974 // Variadic and non-variadic functions aren't compatible
4975 if (lproto->isVariadic() != rproto->isVariadic())
4976 return QualType();
4977
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004978 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4979 return QualType();
4980
Eli Friedman47f77112008-08-22 00:56:42 +00004981 // Check argument compatibility
4982 llvm::SmallVector<QualType, 10> types;
4983 for (unsigned i = 0; i < lproto_nargs; i++) {
4984 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4985 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004986 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
4987 OfBlockPointer,
4988 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004989 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004990
4991 if (Unqualified)
4992 argtype = argtype.getUnqualifiedType();
4993
Eli Friedman47f77112008-08-22 00:56:42 +00004994 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004995 if (Unqualified) {
4996 largtype = largtype.getUnqualifiedType();
4997 rargtype = rargtype.getUnqualifiedType();
4998 }
4999
Chris Lattner465fa322008-10-05 17:34:18 +00005000 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5001 allLTypes = false;
5002 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5003 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005004 }
5005 if (allLTypes) return lhs;
5006 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005007
5008 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5009 EPI.ExtInfo = einfo;
5010 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005011 }
5012
5013 if (lproto) allRTypes = false;
5014 if (rproto) allLTypes = false;
5015
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005016 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005017 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005018 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005019 if (proto->isVariadic()) return QualType();
5020 // Check that the types are compatible with the types that
5021 // would result from default argument promotions (C99 6.7.5.3p15).
5022 // The only types actually affected are promotable integer
5023 // types and floats, which would be passed as a different
5024 // type depending on whether the prototype is visible.
5025 unsigned proto_nargs = proto->getNumArgs();
5026 for (unsigned i = 0; i < proto_nargs; ++i) {
5027 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005028
5029 // Look at the promotion type of enum types, since that is the type used
5030 // to pass enum values.
5031 if (const EnumType *Enum = argTy->getAs<EnumType>())
5032 argTy = Enum->getDecl()->getPromotionType();
5033
Eli Friedman47f77112008-08-22 00:56:42 +00005034 if (argTy->isPromotableIntegerType() ||
5035 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5036 return QualType();
5037 }
5038
5039 if (allLTypes) return lhs;
5040 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005041
5042 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5043 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005044 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005045 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005046 }
5047
5048 if (allLTypes) return lhs;
5049 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005050 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005051}
5052
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005053QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005054 bool OfBlockPointer,
5055 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005056 // C++ [expr]: If an expression initially has the type "reference to T", the
5057 // type is adjusted to "T" prior to any further analysis, the expression
5058 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005059 // expression is an lvalue unless the reference is an rvalue reference and
5060 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005061 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5062 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005063
5064 if (Unqualified) {
5065 LHS = LHS.getUnqualifiedType();
5066 RHS = RHS.getUnqualifiedType();
5067 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005068
Eli Friedman47f77112008-08-22 00:56:42 +00005069 QualType LHSCan = getCanonicalType(LHS),
5070 RHSCan = getCanonicalType(RHS);
5071
5072 // If two types are identical, they are compatible.
5073 if (LHSCan == RHSCan)
5074 return LHS;
5075
John McCall8ccfcb52009-09-24 19:53:00 +00005076 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005077 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5078 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005079 if (LQuals != RQuals) {
5080 // If any of these qualifiers are different, we have a type
5081 // mismatch.
5082 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5083 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5084 return QualType();
5085
5086 // Exactly one GC qualifier difference is allowed: __strong is
5087 // okay if the other type has no GC qualifier but is an Objective
5088 // C object pointer (i.e. implicitly strong by default). We fix
5089 // this by pretending that the unqualified type was actually
5090 // qualified __strong.
5091 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5092 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5093 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5094
5095 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5096 return QualType();
5097
5098 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5099 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5100 }
5101 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5102 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5103 }
Eli Friedman47f77112008-08-22 00:56:42 +00005104 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005105 }
5106
5107 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005108
Eli Friedmandcca6332009-06-01 01:22:52 +00005109 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5110 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005111
Chris Lattnerfd652912008-01-14 05:45:46 +00005112 // We want to consider the two function types to be the same for these
5113 // comparisons, just force one to the other.
5114 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5115 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005116
5117 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005118 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5119 LHSClass = Type::ConstantArray;
5120 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5121 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005122
John McCall8b07ec22010-05-15 11:32:37 +00005123 // ObjCInterfaces are just specialized ObjCObjects.
5124 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5125 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5126
Nate Begemance4d7fc2008-04-18 23:10:10 +00005127 // Canonicalize ExtVector -> Vector.
5128 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5129 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005130
Chris Lattner95554662008-04-07 05:43:21 +00005131 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005132 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005133 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005134 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005135 // Compatibility is based on the underlying type, not the promotion
5136 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005137 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005138 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5139 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005140 }
John McCall9dd450b2009-09-21 23:43:11 +00005141 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005142 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5143 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005144 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005145
Eli Friedman47f77112008-08-22 00:56:42 +00005146 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005147 }
Eli Friedman47f77112008-08-22 00:56:42 +00005148
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005149 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005150 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005151#define TYPE(Class, Base)
5152#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005153#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005154#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5155#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5156#include "clang/AST/TypeNodes.def"
5157 assert(false && "Non-canonical and dependent types shouldn't get here");
5158 return QualType();
5159
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005160 case Type::LValueReference:
5161 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005162 case Type::MemberPointer:
5163 assert(false && "C++ should never be in mergeTypes");
5164 return QualType();
5165
John McCall8b07ec22010-05-15 11:32:37 +00005166 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005167 case Type::IncompleteArray:
5168 case Type::VariableArray:
5169 case Type::FunctionProto:
5170 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005171 assert(false && "Types are eliminated above");
5172 return QualType();
5173
Chris Lattnerfd652912008-01-14 05:45:46 +00005174 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005175 {
5176 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005177 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5178 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005179 if (Unqualified) {
5180 LHSPointee = LHSPointee.getUnqualifiedType();
5181 RHSPointee = RHSPointee.getUnqualifiedType();
5182 }
5183 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5184 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005185 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005186 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005187 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005188 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005189 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005190 return getPointerType(ResultType);
5191 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005192 case Type::BlockPointer:
5193 {
5194 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005195 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5196 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005197 if (Unqualified) {
5198 LHSPointee = LHSPointee.getUnqualifiedType();
5199 RHSPointee = RHSPointee.getUnqualifiedType();
5200 }
5201 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5202 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005203 if (ResultType.isNull()) return QualType();
5204 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5205 return LHS;
5206 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5207 return RHS;
5208 return getBlockPointerType(ResultType);
5209 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005210 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005211 {
5212 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5213 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5214 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5215 return QualType();
5216
5217 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5218 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005219 if (Unqualified) {
5220 LHSElem = LHSElem.getUnqualifiedType();
5221 RHSElem = RHSElem.getUnqualifiedType();
5222 }
5223
5224 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005225 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005226 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5227 return LHS;
5228 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5229 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005230 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5231 ArrayType::ArraySizeModifier(), 0);
5232 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5233 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005234 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5235 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005236 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5237 return LHS;
5238 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5239 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005240 if (LVAT) {
5241 // FIXME: This isn't correct! But tricky to implement because
5242 // the array's size has to be the size of LHS, but the type
5243 // has to be different.
5244 return LHS;
5245 }
5246 if (RVAT) {
5247 // FIXME: This isn't correct! But tricky to implement because
5248 // the array's size has to be the size of RHS, but the type
5249 // has to be different.
5250 return RHS;
5251 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005252 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5253 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005254 return getIncompleteArrayType(ResultType,
5255 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005256 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005257 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005258 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005259 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005260 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005261 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005262 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005263 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005264 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005265 case Type::Complex:
5266 // Distinct complex types are incompatible.
5267 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005268 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005269 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005270 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5271 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005272 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005273 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005274 case Type::ObjCObject: {
5275 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005276 // FIXME: This should be type compatibility, e.g. whether
5277 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005278 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5279 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5280 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005281 return LHS;
5282
Eli Friedman47f77112008-08-22 00:56:42 +00005283 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005284 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005285 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005286 if (OfBlockPointer) {
5287 if (canAssignObjCInterfacesInBlockPointer(
5288 LHS->getAs<ObjCObjectPointerType>(),
5289 RHS->getAs<ObjCObjectPointerType>()))
5290 return LHS;
5291 return QualType();
5292 }
John McCall9dd450b2009-09-21 23:43:11 +00005293 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5294 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005295 return LHS;
5296
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005297 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005298 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005299 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005300
5301 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005302}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005303
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005304/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5305/// 'RHS' attributes and returns the merged version; including for function
5306/// return types.
5307QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5308 QualType LHSCan = getCanonicalType(LHS),
5309 RHSCan = getCanonicalType(RHS);
5310 // If two types are identical, they are compatible.
5311 if (LHSCan == RHSCan)
5312 return LHS;
5313 if (RHSCan->isFunctionType()) {
5314 if (!LHSCan->isFunctionType())
5315 return QualType();
5316 QualType OldReturnType =
5317 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5318 QualType NewReturnType =
5319 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5320 QualType ResReturnType =
5321 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5322 if (ResReturnType.isNull())
5323 return QualType();
5324 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5325 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5326 // In either case, use OldReturnType to build the new function type.
5327 const FunctionType *F = LHS->getAs<FunctionType>();
5328 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005329 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5330 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005331 QualType ResultType
5332 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005333 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005334 return ResultType;
5335 }
5336 }
5337 return QualType();
5338 }
5339
5340 // If the qualifiers are different, the types can still be merged.
5341 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5342 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5343 if (LQuals != RQuals) {
5344 // If any of these qualifiers are different, we have a type mismatch.
5345 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5346 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5347 return QualType();
5348
5349 // Exactly one GC qualifier difference is allowed: __strong is
5350 // okay if the other type has no GC qualifier but is an Objective
5351 // C object pointer (i.e. implicitly strong by default). We fix
5352 // this by pretending that the unqualified type was actually
5353 // qualified __strong.
5354 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5355 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5356 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5357
5358 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5359 return QualType();
5360
5361 if (GC_L == Qualifiers::Strong)
5362 return LHS;
5363 if (GC_R == Qualifiers::Strong)
5364 return RHS;
5365 return QualType();
5366 }
5367
5368 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5369 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5370 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5371 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5372 if (ResQT == LHSBaseQT)
5373 return LHS;
5374 if (ResQT == RHSBaseQT)
5375 return RHS;
5376 }
5377 return QualType();
5378}
5379
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005380//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005381// Integer Predicates
5382//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005383
Jay Foad39c79802011-01-12 09:06:06 +00005384unsigned ASTContext::getIntWidth(QualType T) const {
John McCall56774992009-12-09 09:09:27 +00005385 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005386 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005387 if (T->isBooleanType())
5388 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005389 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005390 return (unsigned)getTypeSize(T);
5391}
5392
5393QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005394 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005395
5396 // Turn <4 x signed int> -> <4 x unsigned int>
5397 if (const VectorType *VTy = T->getAs<VectorType>())
5398 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005399 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005400
5401 // For enums, we return the unsigned version of the base type.
5402 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005403 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005404
5405 const BuiltinType *BTy = T->getAs<BuiltinType>();
5406 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005407 switch (BTy->getKind()) {
5408 case BuiltinType::Char_S:
5409 case BuiltinType::SChar:
5410 return UnsignedCharTy;
5411 case BuiltinType::Short:
5412 return UnsignedShortTy;
5413 case BuiltinType::Int:
5414 return UnsignedIntTy;
5415 case BuiltinType::Long:
5416 return UnsignedLongTy;
5417 case BuiltinType::LongLong:
5418 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005419 case BuiltinType::Int128:
5420 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005421 default:
5422 assert(0 && "Unexpected signed integer type");
5423 return QualType();
5424 }
5425}
5426
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005427ExternalASTSource::~ExternalASTSource() { }
5428
5429void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00005430
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005431ASTMutationListener::~ASTMutationListener() { }
5432
Chris Lattnerecd79c62009-06-14 00:45:47 +00005433
5434//===----------------------------------------------------------------------===//
5435// Builtin Type Computation
5436//===----------------------------------------------------------------------===//
5437
5438/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005439/// pointer over the consumed characters. This returns the resultant type. If
5440/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5441/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5442/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005443///
5444/// RequiresICE is filled in on return to indicate whether the value is required
5445/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005446static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005447 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005448 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005449 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005450 // Modifiers.
5451 int HowLong = 0;
5452 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005453 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005454
Chris Lattnerdc226c22010-10-01 22:42:38 +00005455 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005456 bool Done = false;
5457 while (!Done) {
5458 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005459 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005460 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005461 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005462 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005463 case 'S':
5464 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5465 assert(!Signed && "Can't use 'S' modifier multiple times!");
5466 Signed = true;
5467 break;
5468 case 'U':
5469 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5470 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5471 Unsigned = true;
5472 break;
5473 case 'L':
5474 assert(HowLong <= 2 && "Can't have LLLL modifier");
5475 ++HowLong;
5476 break;
5477 }
5478 }
5479
5480 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005481
Chris Lattnerecd79c62009-06-14 00:45:47 +00005482 // Read the base type.
5483 switch (*Str++) {
5484 default: assert(0 && "Unknown builtin type letter!");
5485 case 'v':
5486 assert(HowLong == 0 && !Signed && !Unsigned &&
5487 "Bad modifiers used with 'v'!");
5488 Type = Context.VoidTy;
5489 break;
5490 case 'f':
5491 assert(HowLong == 0 && !Signed && !Unsigned &&
5492 "Bad modifiers used with 'f'!");
5493 Type = Context.FloatTy;
5494 break;
5495 case 'd':
5496 assert(HowLong < 2 && !Signed && !Unsigned &&
5497 "Bad modifiers used with 'd'!");
5498 if (HowLong)
5499 Type = Context.LongDoubleTy;
5500 else
5501 Type = Context.DoubleTy;
5502 break;
5503 case 's':
5504 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5505 if (Unsigned)
5506 Type = Context.UnsignedShortTy;
5507 else
5508 Type = Context.ShortTy;
5509 break;
5510 case 'i':
5511 if (HowLong == 3)
5512 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5513 else if (HowLong == 2)
5514 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5515 else if (HowLong == 1)
5516 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5517 else
5518 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5519 break;
5520 case 'c':
5521 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5522 if (Signed)
5523 Type = Context.SignedCharTy;
5524 else if (Unsigned)
5525 Type = Context.UnsignedCharTy;
5526 else
5527 Type = Context.CharTy;
5528 break;
5529 case 'b': // boolean
5530 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5531 Type = Context.BoolTy;
5532 break;
5533 case 'z': // size_t.
5534 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5535 Type = Context.getSizeType();
5536 break;
5537 case 'F':
5538 Type = Context.getCFConstantStringType();
5539 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005540 case 'G':
5541 Type = Context.getObjCIdType();
5542 break;
5543 case 'H':
5544 Type = Context.getObjCSelType();
5545 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005546 case 'a':
5547 Type = Context.getBuiltinVaListType();
5548 assert(!Type.isNull() && "builtin va list type not initialized!");
5549 break;
5550 case 'A':
5551 // This is a "reference" to a va_list; however, what exactly
5552 // this means depends on how va_list is defined. There are two
5553 // different kinds of va_list: ones passed by value, and ones
5554 // passed by reference. An example of a by-value va_list is
5555 // x86, where va_list is a char*. An example of by-ref va_list
5556 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5557 // we want this argument to be a char*&; for x86-64, we want
5558 // it to be a __va_list_tag*.
5559 Type = Context.getBuiltinVaListType();
5560 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005561 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005562 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005563 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005564 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005565 break;
5566 case 'V': {
5567 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005568 unsigned NumElements = strtoul(Str, &End, 10);
5569 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005570 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005571
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005572 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5573 RequiresICE, false);
5574 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005575
5576 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005577 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005578 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005579 break;
5580 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005581 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005582 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5583 false);
5584 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005585 Type = Context.getComplexType(ElementType);
5586 break;
5587 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005588 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005589 Type = Context.getFILEType();
5590 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005591 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005592 return QualType();
5593 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005594 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005595 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005596 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005597 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005598 else
5599 Type = Context.getjmp_bufType();
5600
Mike Stump2adb4da2009-07-28 23:47:15 +00005601 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005602 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005603 return QualType();
5604 }
5605 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005606 }
Mike Stump11289f42009-09-09 15:08:12 +00005607
Chris Lattnerdc226c22010-10-01 22:42:38 +00005608 // If there are modifiers and if we're allowed to parse them, go for it.
5609 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005610 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005611 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005612 default: Done = true; --Str; break;
5613 case '*':
5614 case '&': {
5615 // Both pointers and references can have their pointee types
5616 // qualified with an address space.
5617 char *End;
5618 unsigned AddrSpace = strtoul(Str, &End, 10);
5619 if (End != Str && AddrSpace != 0) {
5620 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5621 Str = End;
5622 }
5623 if (c == '*')
5624 Type = Context.getPointerType(Type);
5625 else
5626 Type = Context.getLValueReferenceType(Type);
5627 break;
5628 }
5629 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5630 case 'C':
5631 Type = Type.withConst();
5632 break;
5633 case 'D':
5634 Type = Context.getVolatileType(Type);
5635 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005636 }
5637 }
Chris Lattner84733392010-10-01 07:13:18 +00005638
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005639 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005640 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005641
Chris Lattnerecd79c62009-06-14 00:45:47 +00005642 return Type;
5643}
5644
5645/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005646QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005647 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005648 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005649 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005650
Chris Lattnerecd79c62009-06-14 00:45:47 +00005651 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005652
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005653 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005654 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005655 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5656 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005657 if (Error != GE_None)
5658 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005659
5660 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5661
Chris Lattnerecd79c62009-06-14 00:45:47 +00005662 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005663 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005664 if (Error != GE_None)
5665 return QualType();
5666
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005667 // If this argument is required to be an IntegerConstantExpression and the
5668 // caller cares, fill in the bitmask we return.
5669 if (RequiresICE && IntegerConstantArgs)
5670 *IntegerConstantArgs |= 1 << ArgTypes.size();
5671
Chris Lattnerecd79c62009-06-14 00:45:47 +00005672 // Do array -> pointer decay. The builtin should use the decayed type.
5673 if (Ty->isArrayType())
5674 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005675
Chris Lattnerecd79c62009-06-14 00:45:47 +00005676 ArgTypes.push_back(Ty);
5677 }
5678
5679 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5680 "'.' should only occur at end of builtin type list!");
5681
John McCall991eb4b2010-12-21 00:44:39 +00005682 FunctionType::ExtInfo EI;
5683 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5684
5685 bool Variadic = (TypeStr[0] == '.');
5686
5687 // We really shouldn't be making a no-proto type here, especially in C++.
5688 if (ArgTypes.empty() && Variadic)
5689 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005690
John McCalldb40c7f2010-12-14 08:05:40 +00005691 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005692 EPI.ExtInfo = EI;
5693 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00005694
5695 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005696}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005697
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005698GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5699 GVALinkage External = GVA_StrongExternal;
5700
5701 Linkage L = FD->getLinkage();
5702 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5703 FD->getType()->getLinkage() == UniqueExternalLinkage)
5704 L = UniqueExternalLinkage;
5705
5706 switch (L) {
5707 case NoLinkage:
5708 case InternalLinkage:
5709 case UniqueExternalLinkage:
5710 return GVA_Internal;
5711
5712 case ExternalLinkage:
5713 switch (FD->getTemplateSpecializationKind()) {
5714 case TSK_Undeclared:
5715 case TSK_ExplicitSpecialization:
5716 External = GVA_StrongExternal;
5717 break;
5718
5719 case TSK_ExplicitInstantiationDefinition:
5720 return GVA_ExplicitTemplateInstantiation;
5721
5722 case TSK_ExplicitInstantiationDeclaration:
5723 case TSK_ImplicitInstantiation:
5724 External = GVA_TemplateInstantiation;
5725 break;
5726 }
5727 }
5728
5729 if (!FD->isInlined())
5730 return External;
5731
5732 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5733 // GNU or C99 inline semantics. Determine whether this symbol should be
5734 // externally visible.
5735 if (FD->isInlineDefinitionExternallyVisible())
5736 return External;
5737
5738 // C99 inline semantics, where the symbol is not externally visible.
5739 return GVA_C99Inline;
5740 }
5741
5742 // C++0x [temp.explicit]p9:
5743 // [ Note: The intent is that an inline function that is the subject of
5744 // an explicit instantiation declaration will still be implicitly
5745 // instantiated when used so that the body can be considered for
5746 // inlining, but that no out-of-line copy of the inline function would be
5747 // generated in the translation unit. -- end note ]
5748 if (FD->getTemplateSpecializationKind()
5749 == TSK_ExplicitInstantiationDeclaration)
5750 return GVA_C99Inline;
5751
5752 return GVA_CXXInline;
5753}
5754
5755GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5756 // If this is a static data member, compute the kind of template
5757 // specialization. Otherwise, this variable is not part of a
5758 // template.
5759 TemplateSpecializationKind TSK = TSK_Undeclared;
5760 if (VD->isStaticDataMember())
5761 TSK = VD->getTemplateSpecializationKind();
5762
5763 Linkage L = VD->getLinkage();
5764 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5765 VD->getType()->getLinkage() == UniqueExternalLinkage)
5766 L = UniqueExternalLinkage;
5767
5768 switch (L) {
5769 case NoLinkage:
5770 case InternalLinkage:
5771 case UniqueExternalLinkage:
5772 return GVA_Internal;
5773
5774 case ExternalLinkage:
5775 switch (TSK) {
5776 case TSK_Undeclared:
5777 case TSK_ExplicitSpecialization:
5778 return GVA_StrongExternal;
5779
5780 case TSK_ExplicitInstantiationDeclaration:
5781 llvm_unreachable("Variable should not be instantiated");
5782 // Fall through to treat this like any other instantiation.
5783
5784 case TSK_ExplicitInstantiationDefinition:
5785 return GVA_ExplicitTemplateInstantiation;
5786
5787 case TSK_ImplicitInstantiation:
5788 return GVA_TemplateInstantiation;
5789 }
5790 }
5791
5792 return GVA_StrongExternal;
5793}
5794
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005795bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005796 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5797 if (!VD->isFileVarDecl())
5798 return false;
5799 } else if (!isa<FunctionDecl>(D))
5800 return false;
5801
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005802 // Weak references don't produce any output by themselves.
5803 if (D->hasAttr<WeakRefAttr>())
5804 return false;
5805
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005806 // Aliases and used decls are required.
5807 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5808 return true;
5809
5810 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5811 // Forward declarations aren't required.
5812 if (!FD->isThisDeclarationADefinition())
5813 return false;
5814
5815 // Constructors and destructors are required.
5816 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5817 return true;
5818
5819 // The key function for a class is required.
5820 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5821 const CXXRecordDecl *RD = MD->getParent();
5822 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5823 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5824 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5825 return true;
5826 }
5827 }
5828
5829 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5830
5831 // static, static inline, always_inline, and extern inline functions can
5832 // always be deferred. Normal inline functions can be deferred in C99/C++.
5833 // Implicit template instantiations can also be deferred in C++.
5834 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5835 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5836 return false;
5837 return true;
5838 }
5839
5840 const VarDecl *VD = cast<VarDecl>(D);
5841 assert(VD->isFileVarDecl() && "Expected file scoped var");
5842
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005843 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5844 return false;
5845
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005846 // Structs that have non-trivial constructors or destructors are required.
5847
5848 // FIXME: Handle references.
5849 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5850 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00005851 if (RD->hasDefinition() &&
5852 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005853 return true;
5854 }
5855 }
5856
5857 GVALinkage L = GetGVALinkageForVariable(VD);
5858 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5859 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5860 return false;
5861 }
5862
5863 return true;
5864}
Charles Davis53c59df2010-08-16 03:33:14 +00005865
Charles Davis99202b32010-11-09 18:04:24 +00005866CallingConv ASTContext::getDefaultMethodCallConv() {
5867 // Pass through to the C++ ABI object
5868 return ABI->getDefaultMethodCallConv();
5869}
5870
Jay Foad39c79802011-01-12 09:06:06 +00005871bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00005872 // Pass through to the C++ ABI object
5873 return ABI->isNearlyEmpty(RD);
5874}
5875
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00005876MangleContext *ASTContext::createMangleContext() {
5877 switch (Target.getCXXABI()) {
5878 case CXXABI_ARM:
5879 case CXXABI_Itanium:
5880 return createItaniumMangleContext(*this, getDiagnostics());
5881 case CXXABI_Microsoft:
5882 return createMicrosoftMangleContext(*this, getDiagnostics());
5883 }
5884 assert(0 && "Unsupported ABI");
5885 return 0;
5886}
5887
Charles Davis53c59df2010-08-16 03:33:14 +00005888CXXABI::~CXXABI() {}