blob: 2e1a8c2d4bb3cbd526fa9678183aed04375d64e2 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Charles Davis53c59df2010-08-16 03:33:14 +000033#include "CXXABI.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000034
Chris Lattnerddc135e2006-11-10 06:34:16 +000035using namespace clang;
36
Douglas Gregor9672f922010-07-03 00:47:00 +000037unsigned ASTContext::NumImplicitDefaultConstructors;
38unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000039unsigned ASTContext::NumImplicitCopyConstructors;
40unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000041unsigned ASTContext::NumImplicitCopyAssignmentOperators;
42unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000043unsigned ASTContext::NumImplicitDestructors;
44unsigned ASTContext::NumImplicitDestructorsDeclared;
45
Steve Naroff0af91202007-04-27 21:51:21 +000046enum FloatingRank {
47 FloatRank, DoubleRank, LongDoubleRank
48};
49
Douglas Gregor7dbfb462010-06-16 21:09:37 +000050void
51ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
52 TemplateTemplateParmDecl *Parm) {
53 ID.AddInteger(Parm->getDepth());
54 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000055 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000056
57 TemplateParameterList *Params = Parm->getTemplateParameters();
58 ID.AddInteger(Params->size());
59 for (TemplateParameterList::const_iterator P = Params->begin(),
60 PEnd = Params->end();
61 P != PEnd; ++P) {
62 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
63 ID.AddInteger(0);
64 ID.AddBoolean(TTP->isParameterPack());
65 continue;
66 }
67
68 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
69 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000070 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000071 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
72 continue;
73 }
74
75 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
76 ID.AddInteger(2);
77 Profile(ID, TTP);
78 }
79}
80
81TemplateTemplateParmDecl *
82ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000083 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000084 // Check if we already have a canonical template template parameter.
85 llvm::FoldingSetNodeID ID;
86 CanonicalTemplateTemplateParm::Profile(ID, TTP);
87 void *InsertPos = 0;
88 CanonicalTemplateTemplateParm *Canonical
89 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
90 if (Canonical)
91 return Canonical->getParam();
92
93 // Build a canonical template parameter list.
94 TemplateParameterList *Params = TTP->getTemplateParameters();
95 llvm::SmallVector<NamedDecl *, 4> CanonParams;
96 CanonParams.reserve(Params->size());
97 for (TemplateParameterList::const_iterator P = Params->begin(),
98 PEnd = Params->end();
99 P != PEnd; ++P) {
100 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
101 CanonParams.push_back(
102 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
103 SourceLocation(), TTP->getDepth(),
104 TTP->getIndex(), 0, false,
105 TTP->isParameterPack()));
106 else if (NonTypeTemplateParmDecl *NTTP
107 = dyn_cast<NonTypeTemplateParmDecl>(*P))
108 CanonParams.push_back(
109 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
110 SourceLocation(), NTTP->getDepth(),
111 NTTP->getPosition(), 0,
112 getCanonicalType(NTTP->getType()),
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000113 NTTP->isParameterPack(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000114 0));
115 else
116 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
117 cast<TemplateTemplateParmDecl>(*P)));
118 }
119
120 TemplateTemplateParmDecl *CanonTTP
121 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
122 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000123 TTP->getPosition(),
124 TTP->isParameterPack(),
125 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000126 TemplateParameterList::Create(*this, SourceLocation(),
127 SourceLocation(),
128 CanonParams.data(),
129 CanonParams.size(),
130 SourceLocation()));
131
132 // Get the new insert position for the node we care about.
133 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
134 assert(Canonical == 0 && "Shouldn't be in the map!");
135 (void)Canonical;
136
137 // Create the canonical template template parameter entry.
138 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
139 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
140 return CanonTTP;
141}
142
Charles Davis53c59df2010-08-16 03:33:14 +0000143CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000144 if (!LangOpts.CPlusPlus) return 0;
145
Charles Davis6bcb07a2010-08-19 02:18:14 +0000146 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000147 case CXXABI_ARM:
148 return CreateARMCXXABI(*this);
149 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000150 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000151 case CXXABI_Microsoft:
152 return CreateMicrosoftCXXABI(*this);
153 }
John McCall86353412010-08-21 22:46:04 +0000154 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000155}
156
Chris Lattner465fa322008-10-05 17:34:18 +0000157ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000158 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000159 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000160 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000161 unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000162 TemplateSpecializationTypes(this_()),
163 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000164 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
165 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000166 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000167 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000168 NullTypeSourceInfo(QualType()),
Charles Davis53c59df2010-08-16 03:33:14 +0000169 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000170 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000171 BuiltinInfo(builtins),
172 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000173 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000174 LastSDM(0, 0),
175 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000176 ObjCIdRedefinitionType = QualType();
177 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000178 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000179 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000180 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000181 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000182}
183
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000184ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000185 // Release the DenseMaps associated with DeclContext objects.
186 // FIXME: Is this the ideal solution?
187 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000188
Douglas Gregor5b11d492010-07-25 17:53:33 +0000189 // Call all of the deallocation functions.
190 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
191 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000192
Douglas Gregor832940b2010-03-02 23:58:15 +0000193 // Release all of the memory associated with overridden C++ methods.
194 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
195 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
196 OM != OMEnd; ++OM)
197 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000198
Ted Kremenek076baeb2010-06-08 23:00:58 +0000199 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000200 // because they can contain DenseMaps.
201 for (llvm::DenseMap<const ObjCContainerDecl*,
202 const ASTRecordLayout*>::iterator
203 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
204 // Increment in loop to prevent using deallocated memory.
205 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
206 R->Destroy(*this);
207
Ted Kremenek076baeb2010-06-08 23:00:58 +0000208 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
209 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
210 // Increment in loop to prevent using deallocated memory.
211 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
212 R->Destroy(*this);
213 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000214
215 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
216 AEnd = DeclAttrs.end();
217 A != AEnd; ++A)
218 A->second->~AttrVec();
219}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000220
Douglas Gregor1a809332010-05-23 18:26:36 +0000221void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
222 Deallocations.push_back(std::make_pair(Callback, Data));
223}
224
Mike Stump11289f42009-09-09 15:08:12 +0000225void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000226ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
227 ExternalSource.reset(Source.take());
228}
229
Chris Lattner4eb445d2007-01-26 01:27:23 +0000230void ASTContext::PrintStats() const {
231 fprintf(stderr, "*** AST Context Stats:\n");
232 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000233
Douglas Gregora30d0462009-05-26 14:40:08 +0000234 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000235#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000236#define ABSTRACT_TYPE(Name, Parent)
237#include "clang/AST/TypeNodes.def"
238 0 // Extra
239 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000240
Chris Lattner4eb445d2007-01-26 01:27:23 +0000241 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
242 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000243 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000244 }
245
Douglas Gregora30d0462009-05-26 14:40:08 +0000246 unsigned Idx = 0;
247 unsigned TotalBytes = 0;
248#define TYPE(Name, Parent) \
249 if (counts[Idx]) \
250 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
251 TotalBytes += counts[Idx] * sizeof(Name##Type); \
252 ++Idx;
253#define ABSTRACT_TYPE(Name, Parent)
254#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000255
Douglas Gregora30d0462009-05-26 14:40:08 +0000256 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000257
Douglas Gregor7454c562010-07-02 20:37:36 +0000258 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000259 fprintf(stderr, " %u/%u implicit default constructors created\n",
260 NumImplicitDefaultConstructorsDeclared,
261 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000262 fprintf(stderr, " %u/%u implicit copy constructors created\n",
263 NumImplicitCopyConstructorsDeclared,
264 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000265 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
266 NumImplicitCopyAssignmentOperatorsDeclared,
267 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000268 fprintf(stderr, " %u/%u implicit destructors created\n",
269 NumImplicitDestructorsDeclared, NumImplicitDestructors);
270
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000271 if (ExternalSource.get()) {
272 fprintf(stderr, "\n");
273 ExternalSource->PrintStats();
274 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000275
Douglas Gregor5b11d492010-07-25 17:53:33 +0000276 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000277}
278
279
John McCall48f2d582009-10-23 23:03:21 +0000280void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000281 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000282 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000283 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000284}
285
Chris Lattner970e54e2006-11-12 00:37:36 +0000286void ASTContext::InitBuiltinTypes() {
287 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000288
Chris Lattner970e54e2006-11-12 00:37:36 +0000289 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000290 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000291
Chris Lattner970e54e2006-11-12 00:37:36 +0000292 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000293 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000294 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000295 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000296 InitBuiltinType(CharTy, BuiltinType::Char_S);
297 else
298 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000299 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000300 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
301 InitBuiltinType(ShortTy, BuiltinType::Short);
302 InitBuiltinType(IntTy, BuiltinType::Int);
303 InitBuiltinType(LongTy, BuiltinType::Long);
304 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattner970e54e2006-11-12 00:37:36 +0000306 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000307 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
308 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
309 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
310 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
311 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000312
Chris Lattner970e54e2006-11-12 00:37:36 +0000313 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000314 InitBuiltinType(FloatTy, BuiltinType::Float);
315 InitBuiltinType(DoubleTy, BuiltinType::Double);
316 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000317
Chris Lattnerf122cef2009-04-30 02:43:43 +0000318 // GNU extension, 128-bit integers.
319 InitBuiltinType(Int128Ty, BuiltinType::Int128);
320 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
321
Chris Lattnerad3467e2010-12-25 23:25:43 +0000322 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
323 if (!LangOpts.ShortWChar)
324 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
325 else // -fshort-wchar makes wchar_t be unsigned.
326 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
327 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000328 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000329
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000330 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
331 InitBuiltinType(Char16Ty, BuiltinType::Char16);
332 else // C99
333 Char16Ty = getFromTargetType(Target.getChar16Type());
334
335 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
336 InitBuiltinType(Char32Ty, BuiltinType::Char32);
337 else // C99
338 Char32Ty = getFromTargetType(Target.getChar32Type());
339
Douglas Gregor4619e432008-12-05 23:32:09 +0000340 // Placeholder type for type-dependent expressions whose type is
341 // completely unknown. No code should ever check a type against
342 // DependentTy and users should never see it; however, it is here to
343 // help diagnose failures to properly check for type-dependent
344 // expressions.
345 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000346
John McCall36e7fe32010-10-12 00:20:44 +0000347 // Placeholder type for functions.
348 InitBuiltinType(OverloadTy, BuiltinType::Overload);
349
Mike Stump11289f42009-09-09 15:08:12 +0000350 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000351 // not yet been deduced.
John McCall36e7fe32010-10-12 00:20:44 +0000352 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000353
Chris Lattner970e54e2006-11-12 00:37:36 +0000354 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000355 FloatComplexTy = getComplexType(FloatTy);
356 DoubleComplexTy = getComplexType(DoubleTy);
357 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000358
Steve Naroff66e9f332007-10-15 14:41:52 +0000359 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000360
Steve Naroff1329fa02009-07-15 18:40:39 +0000361 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
362 ObjCIdTypedefType = QualType();
363 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000364 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000365
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000366 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000367 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
368 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000369 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000370
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000371 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000372
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000373 // void * type
374 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000375
376 // nullptr type (C++0x 2.14.7)
377 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000378}
379
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000380Diagnostic &ASTContext::getDiagnostics() const {
381 return SourceMgr.getDiagnostics();
382}
383
Douglas Gregor561eceb2010-08-30 16:49:28 +0000384AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
385 AttrVec *&Result = DeclAttrs[D];
386 if (!Result) {
387 void *Mem = Allocate(sizeof(AttrVec));
388 Result = new (Mem) AttrVec;
389 }
390
391 return *Result;
392}
393
394/// \brief Erase the attributes corresponding to the given declaration.
395void ASTContext::eraseDeclAttrs(const Decl *D) {
396 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
397 if (Pos != DeclAttrs.end()) {
398 Pos->second->~AttrVec();
399 DeclAttrs.erase(Pos);
400 }
401}
402
403
Douglas Gregor86d142a2009-10-08 07:24:58 +0000404MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000405ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000406 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000407 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000408 = InstantiatedFromStaticDataMember.find(Var);
409 if (Pos == InstantiatedFromStaticDataMember.end())
410 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000411
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000412 return Pos->second;
413}
414
Mike Stump11289f42009-09-09 15:08:12 +0000415void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000416ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000417 TemplateSpecializationKind TSK,
418 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000419 assert(Inst->isStaticDataMember() && "Not a static data member");
420 assert(Tmpl->isStaticDataMember() && "Not a static data member");
421 assert(!InstantiatedFromStaticDataMember[Inst] &&
422 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000423 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000424 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000425}
426
John McCalle61f2ba2009-11-18 02:36:19 +0000427NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000428ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000429 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000430 = InstantiatedFromUsingDecl.find(UUD);
431 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000432 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000433
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000434 return Pos->second;
435}
436
437void
John McCallb96ec562009-12-04 22:46:56 +0000438ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
439 assert((isa<UsingDecl>(Pattern) ||
440 isa<UnresolvedUsingValueDecl>(Pattern) ||
441 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
442 "pattern decl is not a using decl");
443 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
444 InstantiatedFromUsingDecl[Inst] = Pattern;
445}
446
447UsingShadowDecl *
448ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
449 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
450 = InstantiatedFromUsingShadowDecl.find(Inst);
451 if (Pos == InstantiatedFromUsingShadowDecl.end())
452 return 0;
453
454 return Pos->second;
455}
456
457void
458ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
459 UsingShadowDecl *Pattern) {
460 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
461 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000462}
463
Anders Carlsson5da84842009-09-01 04:26:58 +0000464FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
465 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
466 = InstantiatedFromUnnamedFieldDecl.find(Field);
467 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
468 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000469
Anders Carlsson5da84842009-09-01 04:26:58 +0000470 return Pos->second;
471}
472
473void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
474 FieldDecl *Tmpl) {
475 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
476 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
477 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
478 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000479
Anders Carlsson5da84842009-09-01 04:26:58 +0000480 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
481}
482
Douglas Gregor832940b2010-03-02 23:58:15 +0000483ASTContext::overridden_cxx_method_iterator
484ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
485 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
486 = OverriddenMethods.find(Method);
487 if (Pos == OverriddenMethods.end())
488 return 0;
489
490 return Pos->second.begin();
491}
492
493ASTContext::overridden_cxx_method_iterator
494ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
495 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
496 = OverriddenMethods.find(Method);
497 if (Pos == OverriddenMethods.end())
498 return 0;
499
500 return Pos->second.end();
501}
502
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000503unsigned
504ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
505 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
506 = OverriddenMethods.find(Method);
507 if (Pos == OverriddenMethods.end())
508 return 0;
509
510 return Pos->second.size();
511}
512
Douglas Gregor832940b2010-03-02 23:58:15 +0000513void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
514 const CXXMethodDecl *Overridden) {
515 OverriddenMethods[Method].push_back(Overridden);
516}
517
Chris Lattner53cfe802007-07-18 17:52:12 +0000518//===----------------------------------------------------------------------===//
519// Type Sizing and Analysis
520//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000521
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000522/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
523/// scalar floating point type.
524const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000525 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000526 assert(BT && "Not a floating point type!");
527 switch (BT->getKind()) {
528 default: assert(0 && "Not a floating point type!");
529 case BuiltinType::Float: return Target.getFloatFormat();
530 case BuiltinType::Double: return Target.getDoubleFormat();
531 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
532 }
533}
534
Ken Dyck160146e2010-01-27 17:10:57 +0000535/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000536/// specified decl. Note that bitfields do not have a valid alignment, so
537/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000538/// If @p RefAsPointee, references are treated like their underlying type
539/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000540CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000541 unsigned Align = Target.getCharWidth();
542
John McCall94268702010-10-08 18:24:19 +0000543 bool UseAlignAttrOnly = false;
544 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
545 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000546
John McCall94268702010-10-08 18:24:19 +0000547 // __attribute__((aligned)) can increase or decrease alignment
548 // *except* on a struct or struct member, where it only increases
549 // alignment unless 'packed' is also specified.
550 //
551 // It is an error for [[align]] to decrease alignment, so we can
552 // ignore that possibility; Sema should diagnose it.
553 if (isa<FieldDecl>(D)) {
554 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
555 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
556 } else {
557 UseAlignAttrOnly = true;
558 }
559 }
560
561 if (UseAlignAttrOnly) {
562 // ignore type of value
563 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000564 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000565 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000566 if (RefAsPointee)
567 T = RT->getPointeeType();
568 else
569 T = getPointerType(RT->getPointeeType());
570 }
571 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000572 unsigned MinWidth = Target.getLargeArrayMinWidth();
573 unsigned ArrayAlign = Target.getLargeArrayAlign();
574 if (isa<VariableArrayType>(T) && MinWidth != 0)
575 Align = std::max(Align, ArrayAlign);
576 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
577 unsigned Size = getTypeSize(CT);
578 if (MinWidth != 0 && MinWidth <= Size)
579 Align = std::max(Align, ArrayAlign);
580 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000581 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000582 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
583 T = cast<ArrayType>(T)->getElementType();
584
585 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
586 }
Charles Davis3fc51072010-02-23 04:52:00 +0000587 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
588 // In the case of a field in a packed struct, we want the minimum
589 // of the alignment of the field and the alignment of the struct.
590 Align = std::min(Align,
591 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
592 }
Chris Lattner68061312009-01-24 21:53:27 +0000593 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000594
Ken Dyckcc56c542011-01-15 18:38:59 +0000595 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000596}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000597
John McCall87fe5d52010-05-20 01:18:31 +0000598std::pair<CharUnits, CharUnits>
599ASTContext::getTypeInfoInChars(const Type *T) {
600 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000601 return std::make_pair(toCharUnitsFromBits(Info.first),
602 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000603}
604
605std::pair<CharUnits, CharUnits>
606ASTContext::getTypeInfoInChars(QualType T) {
607 return getTypeInfoInChars(T.getTypePtr());
608}
609
Chris Lattner983a8bb2007-07-13 22:13:22 +0000610/// getTypeSize - Return the size of the specified type, in bits. This method
611/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000612///
613/// FIXME: Pointers into different addr spaces could have different sizes and
614/// alignment requirements: getPointerInfo should take an AddrSpace, this
615/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000616std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000617ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000618 uint64_t Width=0;
619 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000620 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000621#define TYPE(Class, Base)
622#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000623#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000624#define DEPENDENT_TYPE(Class, Base) case Type::Class:
625#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000626 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000627 break;
628
Chris Lattner355332d2007-07-13 22:27:08 +0000629 case Type::FunctionNoProto:
630 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000631 // GCC extension: alignof(function) = 32 bits
632 Width = 0;
633 Align = 32;
634 break;
635
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000636 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000637 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000638 Width = 0;
639 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
640 break;
641
Steve Naroff5c131802007-08-30 01:06:46 +0000642 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000643 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000644
Chris Lattner37e05872008-03-05 18:54:05 +0000645 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000646 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000647 Align = EltInfo.second;
648 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000649 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000650 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000651 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000652 const VectorType *VT = cast<VectorType>(T);
653 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
654 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000655 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000656 // If the alignment is not a power of 2, round up to the next power of 2.
657 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000658 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000659 Align = llvm::NextPowerOf2(Align);
660 Width = llvm::RoundUpToAlignment(Width, Align);
661 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000662 break;
663 }
Chris Lattner647fb222007-07-18 18:26:58 +0000664
Chris Lattner7570e9c2008-03-08 08:52:55 +0000665 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000666 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000667 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000668 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000669 // GCC extension: alignof(void) = 8 bits.
670 Width = 0;
671 Align = 8;
672 break;
673
Chris Lattner6a4f7452007-12-19 19:23:28 +0000674 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000675 Width = Target.getBoolWidth();
676 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000677 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000678 case BuiltinType::Char_S:
679 case BuiltinType::Char_U:
680 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000681 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000682 Width = Target.getCharWidth();
683 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000684 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000685 case BuiltinType::WChar_S:
686 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000687 Width = Target.getWCharWidth();
688 Align = Target.getWCharAlign();
689 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000690 case BuiltinType::Char16:
691 Width = Target.getChar16Width();
692 Align = Target.getChar16Align();
693 break;
694 case BuiltinType::Char32:
695 Width = Target.getChar32Width();
696 Align = Target.getChar32Align();
697 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000698 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000699 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000700 Width = Target.getShortWidth();
701 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000702 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000703 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000704 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000705 Width = Target.getIntWidth();
706 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000707 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000708 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000709 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000710 Width = Target.getLongWidth();
711 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000712 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000713 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000714 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000715 Width = Target.getLongLongWidth();
716 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000717 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000718 case BuiltinType::Int128:
719 case BuiltinType::UInt128:
720 Width = 128;
721 Align = 128; // int128_t is 128-bit aligned on all targets.
722 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000723 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000724 Width = Target.getFloatWidth();
725 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000726 break;
727 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000728 Width = Target.getDoubleWidth();
729 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000730 break;
731 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000732 Width = Target.getLongDoubleWidth();
733 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000734 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000735 case BuiltinType::NullPtr:
736 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
737 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000738 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000739 case BuiltinType::ObjCId:
740 case BuiltinType::ObjCClass:
741 case BuiltinType::ObjCSel:
742 Width = Target.getPointerWidth(0);
743 Align = Target.getPointerAlign(0);
744 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000745 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000746 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000747 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000748 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000749 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000750 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000751 case Type::BlockPointer: {
752 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
753 Width = Target.getPointerWidth(AS);
754 Align = Target.getPointerAlign(AS);
755 break;
756 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000757 case Type::LValueReference:
758 case Type::RValueReference: {
759 // alignof and sizeof should never enter this code path here, so we go
760 // the pointer route.
761 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
762 Width = Target.getPointerWidth(AS);
763 Align = Target.getPointerAlign(AS);
764 break;
765 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000766 case Type::Pointer: {
767 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000768 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000769 Align = Target.getPointerAlign(AS);
770 break;
771 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000772 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000773 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000774 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000775 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000776 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000777 Align = PtrDiffInfo.second;
778 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000779 }
Chris Lattner647fb222007-07-18 18:26:58 +0000780 case Type::Complex: {
781 // Complex types have the same alignment as their elements, but twice the
782 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000783 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000784 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000785 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000786 Align = EltInfo.second;
787 break;
788 }
John McCall8b07ec22010-05-15 11:32:37 +0000789 case Type::ObjCObject:
790 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000791 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000792 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000793 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
794 Width = Layout.getSize();
795 Align = Layout.getAlignment();
796 break;
797 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000798 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000799 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000800 const TagType *TT = cast<TagType>(T);
801
802 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000803 Width = 1;
804 Align = 1;
805 break;
806 }
Mike Stump11289f42009-09-09 15:08:12 +0000807
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000808 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000809 return getTypeInfo(ET->getDecl()->getIntegerType());
810
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000811 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000812 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
813 Width = Layout.getSize();
814 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000815 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000816 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000817
Chris Lattner63d2b362009-10-22 05:17:15 +0000818 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000819 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
820 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000821
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000822 case Type::Paren:
823 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
824
Douglas Gregoref462e62009-04-30 17:32:17 +0000825 case Type::Typedef: {
826 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000827 std::pair<uint64_t, unsigned> Info
828 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
829 Align = std::max(Typedef->getMaxAlignment(), Info.second);
830 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000831 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000832 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000833
834 case Type::TypeOfExpr:
835 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
836 .getTypePtr());
837
838 case Type::TypeOf:
839 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
840
Anders Carlsson81df7b82009-06-24 19:06:50 +0000841 case Type::Decltype:
842 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
843 .getTypePtr());
844
Abramo Bagnara6150c882010-05-11 21:36:43 +0000845 case Type::Elaborated:
846 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000847
John McCall81904512011-01-06 01:58:22 +0000848 case Type::Attributed:
849 return getTypeInfo(
850 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
851
Douglas Gregoref462e62009-04-30 17:32:17 +0000852 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000853 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000854 "Cannot request the size of a dependent type");
855 // FIXME: this is likely to be wrong once we support template
856 // aliases, since a template alias could refer to a typedef that
857 // has an __aligned__ attribute on it.
858 return getTypeInfo(getCanonicalType(T));
859 }
Mike Stump11289f42009-09-09 15:08:12 +0000860
Chris Lattner53cfe802007-07-18 17:52:12 +0000861 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000862 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000863}
864
Ken Dyckcc56c542011-01-15 18:38:59 +0000865/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
866CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
867 return CharUnits::fromQuantity(BitSize / getCharWidth());
868}
869
Ken Dyck8c89d592009-12-22 14:23:30 +0000870/// getTypeSizeInChars - Return the size of the specified type, in characters.
871/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000872CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000873 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000874}
Jay Foad39c79802011-01-12 09:06:06 +0000875CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000876 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000877}
878
Ken Dycka6046ab2010-01-26 17:25:18 +0000879/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000880/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000881CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000882 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000883}
Jay Foad39c79802011-01-12 09:06:06 +0000884CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000885 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000886}
887
Chris Lattnera3402cd2009-01-27 18:08:34 +0000888/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
889/// type for the current target in bits. This can be different than the ABI
890/// alignment in cases where it is beneficial for performance to overalign
891/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +0000892unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +0000893 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000894
895 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000896 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000897 T = CT->getElementType().getTypePtr();
898 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
899 T->isSpecificBuiltinType(BuiltinType::LongLong))
900 return std::max(ABIAlign, (unsigned)getTypeSize(T));
901
Chris Lattnera3402cd2009-01-27 18:08:34 +0000902 return ABIAlign;
903}
904
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000905/// ShallowCollectObjCIvars -
906/// Collect all ivars, including those synthesized, in the current class.
907///
908void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +0000909 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000910 // FIXME. This need be removed but there are two many places which
911 // assume const-ness of ObjCInterfaceDecl
912 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
913 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
914 Iv= Iv->getNextIvar())
915 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000916}
917
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000918/// DeepCollectObjCIvars -
919/// This routine first collects all declared, but not synthesized, ivars in
920/// super class and then collects all ivars, including those synthesized for
921/// current class. This routine is used for implementation of current class
922/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000923///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000924void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
925 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +0000926 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000927 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
928 DeepCollectObjCIvars(SuperClass, false, Ivars);
929 if (!leafClass) {
930 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
931 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000932 Ivars.push_back(*I);
933 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000934 else
935 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000936}
937
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000938/// CollectInheritedProtocols - Collect all protocols in current class and
939/// those inherited by it.
940void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000941 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000942 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000943 // We can use protocol_iterator here instead of
944 // all_referenced_protocol_iterator since we are walking all categories.
945 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
946 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000947 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000948 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000949 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000950 PE = Proto->protocol_end(); P != PE; ++P) {
951 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000952 CollectInheritedProtocols(*P, Protocols);
953 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000954 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000955
956 // Categories of this Interface.
957 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
958 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
959 CollectInheritedProtocols(CDeclChain, Protocols);
960 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
961 while (SD) {
962 CollectInheritedProtocols(SD, Protocols);
963 SD = SD->getSuperClass();
964 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000965 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000966 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000967 PE = OC->protocol_end(); P != PE; ++P) {
968 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000969 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000970 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
971 PE = Proto->protocol_end(); P != PE; ++P)
972 CollectInheritedProtocols(*P, Protocols);
973 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000974 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000975 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
976 PE = OP->protocol_end(); P != PE; ++P) {
977 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000978 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000979 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
980 PE = Proto->protocol_end(); P != PE; ++P)
981 CollectInheritedProtocols(*P, Protocols);
982 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000983 }
984}
985
Jay Foad39c79802011-01-12 09:06:06 +0000986unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000987 unsigned count = 0;
988 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000989 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
990 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000991 count += CDecl->ivar_size();
992
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000993 // Count ivar defined in this class's implementation. This
994 // includes synthesized ivars.
995 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000996 count += ImplDecl->ivar_size();
997
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000998 return count;
999}
1000
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001001/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1002ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1003 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1004 I = ObjCImpls.find(D);
1005 if (I != ObjCImpls.end())
1006 return cast<ObjCImplementationDecl>(I->second);
1007 return 0;
1008}
1009/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1010ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1011 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1012 I = ObjCImpls.find(D);
1013 if (I != ObjCImpls.end())
1014 return cast<ObjCCategoryImplDecl>(I->second);
1015 return 0;
1016}
1017
1018/// \brief Set the implementation of ObjCInterfaceDecl.
1019void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1020 ObjCImplementationDecl *ImplD) {
1021 assert(IFaceD && ImplD && "Passed null params");
1022 ObjCImpls[IFaceD] = ImplD;
1023}
1024/// \brief Set the implementation of ObjCCategoryDecl.
1025void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1026 ObjCCategoryImplDecl *ImplD) {
1027 assert(CatD && ImplD && "Passed null params");
1028 ObjCImpls[CatD] = ImplD;
1029}
1030
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001031/// \brief Get the copy initialization expression of VarDecl,or NULL if
1032/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001033Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001034 assert(VD && "Passed null params");
1035 assert(VD->hasAttr<BlocksAttr>() &&
1036 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001037 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001038 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001039 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1040}
1041
1042/// \brief Set the copy inialization expression of a block var decl.
1043void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1044 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001045 assert(VD->hasAttr<BlocksAttr>() &&
1046 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001047 BlockVarCopyInits[VD] = Init;
1048}
1049
John McCallbcd03502009-12-07 02:54:59 +00001050/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001051///
John McCallbcd03502009-12-07 02:54:59 +00001052/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001053/// the TypeLoc wrappers.
1054///
1055/// \param T the type that will be the basis for type source info. This type
1056/// should refer to how the declarator was written in source code, not to
1057/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001058TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001059 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001060 if (!DataSize)
1061 DataSize = TypeLoc::getFullDataSizeForType(T);
1062 else
1063 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001064 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001065
John McCallbcd03502009-12-07 02:54:59 +00001066 TypeSourceInfo *TInfo =
1067 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1068 new (TInfo) TypeSourceInfo(T);
1069 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001070}
1071
John McCallbcd03502009-12-07 02:54:59 +00001072TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001073 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001074 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001075 DI->getTypeLoc().initialize(L);
1076 return DI;
1077}
1078
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001079const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001080ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001081 return getObjCLayout(D, 0);
1082}
1083
1084const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001085ASTContext::getASTObjCImplementationLayout(
1086 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001087 return getObjCLayout(D->getClassInterface(), D);
1088}
1089
Chris Lattner983a8bb2007-07-13 22:13:22 +00001090//===----------------------------------------------------------------------===//
1091// Type creation/memoization methods
1092//===----------------------------------------------------------------------===//
1093
Jay Foad39c79802011-01-12 09:06:06 +00001094QualType
1095ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) const {
John McCall8ccfcb52009-09-24 19:53:00 +00001096 unsigned Fast = Quals.getFastQualifiers();
1097 Quals.removeFastQualifiers();
1098
1099 // Check if we've already instantiated this type.
1100 llvm::FoldingSetNodeID ID;
1101 ExtQuals::Profile(ID, TypeNode, Quals);
1102 void *InsertPos = 0;
1103 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1104 assert(EQ->getQualifiers() == Quals);
1105 QualType T = QualType(EQ, Fast);
1106 return T;
1107 }
1108
John McCall717d9b02010-12-10 11:01:00 +00001109 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001110 ExtQualNodes.InsertNode(New, InsertPos);
1111 QualType T = QualType(New, Fast);
1112 return T;
1113}
1114
Jay Foad39c79802011-01-12 09:06:06 +00001115QualType
1116ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001117 QualType CanT = getCanonicalType(T);
1118 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001119 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001120
John McCall8ccfcb52009-09-24 19:53:00 +00001121 // If we are composing extended qualifiers together, merge together
1122 // into one ExtQuals node.
1123 QualifierCollector Quals;
1124 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001125
John McCall8ccfcb52009-09-24 19:53:00 +00001126 // If this type already has an address space specified, it cannot get
1127 // another one.
1128 assert(!Quals.hasAddressSpace() &&
1129 "Type cannot be in multiple addr spaces!");
1130 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001131
John McCall8ccfcb52009-09-24 19:53:00 +00001132 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001133}
1134
Chris Lattnerd60183d2009-02-18 22:53:11 +00001135QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001136 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001137 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001138 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001139 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001140
John McCall53fa7142010-12-24 02:08:15 +00001141 if (const PointerType *ptr = T->getAs<PointerType>()) {
1142 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001143 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001144 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1145 return getPointerType(ResultType);
1146 }
1147 }
Mike Stump11289f42009-09-09 15:08:12 +00001148
John McCall8ccfcb52009-09-24 19:53:00 +00001149 // If we are composing extended qualifiers together, merge together
1150 // into one ExtQuals node.
1151 QualifierCollector Quals;
1152 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001153
John McCall8ccfcb52009-09-24 19:53:00 +00001154 // If this type already has an ObjCGC specified, it cannot get
1155 // another one.
1156 assert(!Quals.hasObjCGCAttr() &&
1157 "Type cannot have multiple ObjCGCs!");
1158 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001159
John McCall8ccfcb52009-09-24 19:53:00 +00001160 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001161}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001162
John McCall4f5019e2010-12-19 02:44:49 +00001163const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1164 FunctionType::ExtInfo Info) {
1165 if (T->getExtInfo() == Info)
1166 return T;
1167
1168 QualType Result;
1169 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1170 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1171 } else {
1172 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1173 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1174 EPI.ExtInfo = Info;
1175 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1176 FPT->getNumArgs(), EPI);
1177 }
1178
1179 return cast<FunctionType>(Result.getTypePtr());
1180}
1181
Chris Lattnerc6395932007-06-22 20:56:16 +00001182/// getComplexType - Return the uniqued reference to the type for a complex
1183/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001184QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001185 // Unique pointers, to guarantee there is only one pointer of a particular
1186 // structure.
1187 llvm::FoldingSetNodeID ID;
1188 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001189
Chris Lattnerc6395932007-06-22 20:56:16 +00001190 void *InsertPos = 0;
1191 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1192 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001193
Chris Lattnerc6395932007-06-22 20:56:16 +00001194 // If the pointee type isn't canonical, this won't be a canonical type either,
1195 // so fill in the canonical type field.
1196 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001197 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001198 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001199
Chris Lattnerc6395932007-06-22 20:56:16 +00001200 // Get the new insert position for the node we care about.
1201 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001202 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001203 }
John McCall90d1c2d2009-09-24 23:30:46 +00001204 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001205 Types.push_back(New);
1206 ComplexTypes.InsertNode(New, InsertPos);
1207 return QualType(New, 0);
1208}
1209
Chris Lattner970e54e2006-11-12 00:37:36 +00001210/// getPointerType - Return the uniqued reference to the type for a pointer to
1211/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001212QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001213 // Unique pointers, to guarantee there is only one pointer of a particular
1214 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001215 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001216 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001217
Chris Lattner67521df2007-01-27 01:29:36 +00001218 void *InsertPos = 0;
1219 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001220 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001221
Chris Lattner7ccecb92006-11-12 08:50:50 +00001222 // If the pointee type isn't canonical, this won't be a canonical type either,
1223 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001224 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001225 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001226 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001227
Chris Lattner67521df2007-01-27 01:29:36 +00001228 // Get the new insert position for the node we care about.
1229 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001230 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001231 }
John McCall90d1c2d2009-09-24 23:30:46 +00001232 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001233 Types.push_back(New);
1234 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001235 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001236}
1237
Mike Stump11289f42009-09-09 15:08:12 +00001238/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001239/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001240QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001241 assert(T->isFunctionType() && "block of function types only");
1242 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001243 // structure.
1244 llvm::FoldingSetNodeID ID;
1245 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001246
Steve Naroffec33ed92008-08-27 16:04:49 +00001247 void *InsertPos = 0;
1248 if (BlockPointerType *PT =
1249 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1250 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001251
1252 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001253 // type either so fill in the canonical type field.
1254 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001255 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001256 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001257
Steve Naroffec33ed92008-08-27 16:04:49 +00001258 // Get the new insert position for the node we care about.
1259 BlockPointerType *NewIP =
1260 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001261 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001262 }
John McCall90d1c2d2009-09-24 23:30:46 +00001263 BlockPointerType *New
1264 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001265 Types.push_back(New);
1266 BlockPointerTypes.InsertNode(New, InsertPos);
1267 return QualType(New, 0);
1268}
1269
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001270/// getLValueReferenceType - Return the uniqued reference to the type for an
1271/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001272QualType
1273ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001274 // Unique pointers, to guarantee there is only one pointer of a particular
1275 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001276 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001277 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001278
1279 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001280 if (LValueReferenceType *RT =
1281 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001282 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001283
John McCallfc93cf92009-10-22 22:37:11 +00001284 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1285
Bill Wendling3708c182007-05-27 10:15:43 +00001286 // If the referencee type isn't canonical, this won't be a canonical type
1287 // either, so fill in the canonical type field.
1288 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001289 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1290 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1291 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001292
Bill Wendling3708c182007-05-27 10:15:43 +00001293 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001294 LValueReferenceType *NewIP =
1295 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001296 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001297 }
1298
John McCall90d1c2d2009-09-24 23:30:46 +00001299 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001300 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1301 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001302 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001303 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001304
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001305 return QualType(New, 0);
1306}
1307
1308/// getRValueReferenceType - Return the uniqued reference to the type for an
1309/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001310QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001311 // Unique pointers, to guarantee there is only one pointer of a particular
1312 // structure.
1313 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001314 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001315
1316 void *InsertPos = 0;
1317 if (RValueReferenceType *RT =
1318 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1319 return QualType(RT, 0);
1320
John McCallfc93cf92009-10-22 22:37:11 +00001321 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1322
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001323 // If the referencee type isn't canonical, this won't be a canonical type
1324 // either, so fill in the canonical type field.
1325 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001326 if (InnerRef || !T.isCanonical()) {
1327 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1328 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001329
1330 // Get the new insert position for the node we care about.
1331 RValueReferenceType *NewIP =
1332 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001333 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001334 }
1335
John McCall90d1c2d2009-09-24 23:30:46 +00001336 RValueReferenceType *New
1337 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001338 Types.push_back(New);
1339 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001340 return QualType(New, 0);
1341}
1342
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001343/// getMemberPointerType - Return the uniqued reference to the type for a
1344/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001345QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001346 // Unique pointers, to guarantee there is only one pointer of a particular
1347 // structure.
1348 llvm::FoldingSetNodeID ID;
1349 MemberPointerType::Profile(ID, T, Cls);
1350
1351 void *InsertPos = 0;
1352 if (MemberPointerType *PT =
1353 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1354 return QualType(PT, 0);
1355
1356 // If the pointee or class type isn't canonical, this won't be a canonical
1357 // type either, so fill in the canonical type field.
1358 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001359 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001360 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1361
1362 // Get the new insert position for the node we care about.
1363 MemberPointerType *NewIP =
1364 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001365 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001366 }
John McCall90d1c2d2009-09-24 23:30:46 +00001367 MemberPointerType *New
1368 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001369 Types.push_back(New);
1370 MemberPointerTypes.InsertNode(New, InsertPos);
1371 return QualType(New, 0);
1372}
1373
Mike Stump11289f42009-09-09 15:08:12 +00001374/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001375/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001376QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001377 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001378 ArrayType::ArraySizeModifier ASM,
Jay Foad39c79802011-01-12 09:06:06 +00001379 unsigned EltTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001380 assert((EltTy->isDependentType() ||
1381 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001382 "Constant array of VLAs is illegal!");
1383
Chris Lattnere2df3f92009-05-13 04:12:56 +00001384 // Convert the array size into a canonical width matching the pointer size for
1385 // the target.
1386 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001387 ArySize =
1388 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001389
Chris Lattner23b7eb62007-06-15 23:05:46 +00001390 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001391 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001392
Chris Lattner36f8e652007-01-27 08:31:04 +00001393 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001394 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001395 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001396 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001397
Chris Lattner7ccecb92006-11-12 08:50:50 +00001398 // If the element type isn't canonical, this won't be a canonical type either,
1399 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001400 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001401 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001402 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001403 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001404 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001405 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001406 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001407 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001408 }
Mike Stump11289f42009-09-09 15:08:12 +00001409
John McCall90d1c2d2009-09-24 23:30:46 +00001410 ConstantArrayType *New = new(*this,TypeAlignment)
1411 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001412 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001413 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001414 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001415}
1416
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001417/// getIncompleteArrayType - Returns a unique reference to the type for a
1418/// incomplete array of the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001419QualType ASTContext::getUnknownSizeVariableArrayType(QualType Ty) const {
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001420 QualType ElemTy = getBaseElementType(Ty);
1421 DeclarationName Name;
1422 llvm::SmallVector<QualType, 8> ATypes;
1423 QualType ATy = Ty;
1424 while (const ArrayType *AT = getAsArrayType(ATy)) {
1425 ATypes.push_back(ATy);
1426 ATy = AT->getElementType();
1427 }
1428 for (int i = ATypes.size() - 1; i >= 0; i--) {
1429 if (const VariableArrayType *VAT = getAsVariableArrayType(ATypes[i])) {
1430 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Star,
1431 0, VAT->getBracketsRange());
1432 }
1433 else if (const ConstantArrayType *CAT = getAsConstantArrayType(ATypes[i])) {
1434 llvm::APSInt ConstVal(CAT->getSize());
1435 ElemTy = getConstantArrayType(ElemTy, ConstVal, ArrayType::Normal, 0);
1436 }
1437 else if (getAsIncompleteArrayType(ATypes[i])) {
1438 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Normal,
1439 0, SourceRange());
1440 }
1441 else
1442 assert(false && "DependentArrayType is seen");
1443 }
1444 return ElemTy;
1445}
1446
1447/// getVariableArrayDecayedType - Returns a vla type where known sizes
1448/// are replaced with [*]
Jay Foad39c79802011-01-12 09:06:06 +00001449QualType ASTContext::getVariableArrayDecayedType(QualType Ty) const {
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001450 if (Ty->isPointerType()) {
1451 QualType BaseType = Ty->getAs<PointerType>()->getPointeeType();
1452 if (isa<VariableArrayType>(BaseType)) {
1453 ArrayType *AT = dyn_cast<ArrayType>(BaseType);
1454 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1455 if (VAT->getSizeExpr()) {
1456 Ty = getUnknownSizeVariableArrayType(BaseType);
1457 Ty = getPointerType(Ty);
1458 }
1459 }
1460 }
1461 return Ty;
1462}
1463
1464
Steve Naroffcadebd02007-08-30 18:14:25 +00001465/// getVariableArrayType - Returns a non-unique reference to the type for a
1466/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001467QualType ASTContext::getVariableArrayType(QualType EltTy,
1468 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001469 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001470 unsigned EltTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001471 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001472 // Since we don't unique expressions, it isn't possible to unique VLA's
1473 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001474 QualType CanonType;
1475
1476 if (!EltTy.isCanonical()) {
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001477 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1478 EltTypeQuals, Brackets);
1479 }
1480
John McCall90d1c2d2009-09-24 23:30:46 +00001481 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001482 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001483
1484 VariableArrayTypes.push_back(New);
1485 Types.push_back(New);
1486 return QualType(New, 0);
1487}
1488
Douglas Gregor4619e432008-12-05 23:32:09 +00001489/// getDependentSizedArrayType - Returns a non-unique reference to
1490/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001491/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001492QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1493 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001494 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001495 unsigned EltTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001496 SourceRange Brackets) const {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001497 assert((!NumElts || NumElts->isTypeDependent() ||
1498 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001499 "Size must be type- or value-dependent!");
1500
Douglas Gregorf3f95522009-07-31 00:23:35 +00001501 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001502 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001503 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001504
Douglas Gregorf86c9392010-10-26 00:51:02 +00001505 QualType CanonicalEltTy = getCanonicalType(EltTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001506 if (NumElts) {
1507 // Dependently-sized array types that do not have a specified
1508 // number of elements will have their sizes deduced from an
1509 // initializer.
Douglas Gregorf86c9392010-10-26 00:51:02 +00001510 DependentSizedArrayType::Profile(ID, *this, CanonicalEltTy, ASM,
Douglas Gregorad2956c2009-11-19 18:03:26 +00001511 EltTypeQuals, NumElts);
1512
1513 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1514 }
1515
Douglas Gregorf3f95522009-07-31 00:23:35 +00001516 DependentSizedArrayType *New;
1517 if (Canon) {
1518 // We already have a canonical version of this array type; use it as
1519 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001520 New = new (*this, TypeAlignment)
1521 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1522 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf86c9392010-10-26 00:51:02 +00001523 } else if (CanonicalEltTy == EltTy) {
1524 // This is a canonical type. Record it.
1525 New = new (*this, TypeAlignment)
1526 DependentSizedArrayType(*this, EltTy, QualType(),
1527 NumElts, ASM, EltTypeQuals, Brackets);
1528
1529 if (NumElts) {
1530#ifndef NDEBUG
1531 DependentSizedArrayType *CanonCheck
1532 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1533 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1534 (void)CanonCheck;
1535#endif
1536 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001537 }
Douglas Gregorf86c9392010-10-26 00:51:02 +00001538 } else {
1539 QualType Canon = getDependentSizedArrayType(CanonicalEltTy, NumElts,
1540 ASM, EltTypeQuals,
1541 SourceRange());
1542 New = new (*this, TypeAlignment)
1543 DependentSizedArrayType(*this, EltTy, Canon,
1544 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001545 }
Mike Stump11289f42009-09-09 15:08:12 +00001546
Douglas Gregor4619e432008-12-05 23:32:09 +00001547 Types.push_back(New);
1548 return QualType(New, 0);
1549}
1550
Eli Friedmanbd258282008-02-15 18:16:39 +00001551QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1552 ArrayType::ArraySizeModifier ASM,
Jay Foad39c79802011-01-12 09:06:06 +00001553 unsigned EltTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001554 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001555 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001556
1557 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001558 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001559 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1560 return QualType(ATP, 0);
1561
1562 // If the element type isn't canonical, this won't be a canonical type
1563 // either, so fill in the canonical type field.
1564 QualType Canonical;
1565
John McCallb692a092009-10-22 20:10:53 +00001566 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001567 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001568 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001569
1570 // Get the new insert position for the node we care about.
1571 IncompleteArrayType *NewIP =
1572 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001573 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001574 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001575
John McCall90d1c2d2009-09-24 23:30:46 +00001576 IncompleteArrayType *New = new (*this, TypeAlignment)
1577 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001578
1579 IncompleteArrayTypes.InsertNode(New, InsertPos);
1580 Types.push_back(New);
1581 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001582}
1583
Steve Naroff91fcddb2007-07-18 18:00:27 +00001584/// getVectorType - Return the unique reference to a vector type of
1585/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001586QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001587 VectorType::VectorKind VecKind) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00001588 BuiltinType *BaseType;
Mike Stump11289f42009-09-09 15:08:12 +00001589
Chris Lattnerdc226c22010-10-01 22:42:38 +00001590 BaseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1591 assert(BaseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001592
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001593 // Check if we've already instantiated a vector of this type.
1594 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001595 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001596
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001597 void *InsertPos = 0;
1598 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1599 return QualType(VTP, 0);
1600
1601 // If the element type isn't canonical, this won't be a canonical type either,
1602 // so fill in the canonical type field.
1603 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001604 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001605 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001606
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001607 // Get the new insert position for the node we care about.
1608 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001609 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001610 }
John McCall90d1c2d2009-09-24 23:30:46 +00001611 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001612 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001613 VectorTypes.InsertNode(New, InsertPos);
1614 Types.push_back(New);
1615 return QualType(New, 0);
1616}
1617
Nate Begemance4d7fc2008-04-18 23:10:10 +00001618/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001619/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001620QualType
1621ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001622 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001623
Chris Lattner76a00cf2008-04-06 22:59:24 +00001624 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001625 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001626
Steve Naroff91fcddb2007-07-18 18:00:27 +00001627 // Check if we've already instantiated a vector of this type.
1628 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001629 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001630 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001631 void *InsertPos = 0;
1632 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1633 return QualType(VTP, 0);
1634
1635 // If the element type isn't canonical, this won't be a canonical type either,
1636 // so fill in the canonical type field.
1637 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001638 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001639 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001640
Steve Naroff91fcddb2007-07-18 18:00:27 +00001641 // Get the new insert position for the node we care about.
1642 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001643 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001644 }
John McCall90d1c2d2009-09-24 23:30:46 +00001645 ExtVectorType *New = new (*this, TypeAlignment)
1646 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001647 VectorTypes.InsertNode(New, InsertPos);
1648 Types.push_back(New);
1649 return QualType(New, 0);
1650}
1651
Jay Foad39c79802011-01-12 09:06:06 +00001652QualType
1653ASTContext::getDependentSizedExtVectorType(QualType vecType,
1654 Expr *SizeExpr,
1655 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001656 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001657 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001658 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001659
Douglas Gregor352169a2009-07-31 03:54:25 +00001660 void *InsertPos = 0;
1661 DependentSizedExtVectorType *Canon
1662 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1663 DependentSizedExtVectorType *New;
1664 if (Canon) {
1665 // We already have a canonical version of this array type; use it as
1666 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001667 New = new (*this, TypeAlignment)
1668 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1669 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001670 } else {
1671 QualType CanonVecTy = getCanonicalType(vecType);
1672 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001673 New = new (*this, TypeAlignment)
1674 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1675 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001676
1677 DependentSizedExtVectorType *CanonCheck
1678 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1679 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1680 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001681 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1682 } else {
1683 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1684 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001685 New = new (*this, TypeAlignment)
1686 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001687 }
1688 }
Mike Stump11289f42009-09-09 15:08:12 +00001689
Douglas Gregor758a8692009-06-17 21:51:59 +00001690 Types.push_back(New);
1691 return QualType(New, 0);
1692}
1693
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001694/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001695///
Jay Foad39c79802011-01-12 09:06:06 +00001696QualType
1697ASTContext::getFunctionNoProtoType(QualType ResultTy,
1698 const FunctionType::ExtInfo &Info) const {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001699 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001700 // Unique functions, to guarantee there is only one function of a particular
1701 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001702 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001703 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001704
Chris Lattner47955de2007-01-27 08:37:20 +00001705 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001706 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001707 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001708 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001709
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001710 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001711 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001712 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001713 Canonical =
1714 getFunctionNoProtoType(getCanonicalType(ResultTy),
1715 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001716
Chris Lattner47955de2007-01-27 08:37:20 +00001717 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001718 FunctionNoProtoType *NewIP =
1719 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001720 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001721 }
Mike Stump11289f42009-09-09 15:08:12 +00001722
John McCall90d1c2d2009-09-24 23:30:46 +00001723 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001724 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001725 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001726 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001727 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001728}
1729
1730/// getFunctionType - Return a normal function type with a typed argument
1731/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001732QualType
1733ASTContext::getFunctionType(QualType ResultTy,
1734 const QualType *ArgArray, unsigned NumArgs,
1735 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001736 // Unique functions, to guarantee there is only one function of a particular
1737 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001738 llvm::FoldingSetNodeID ID;
John McCalldb40c7f2010-12-14 08:05:40 +00001739 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001740
1741 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001742 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001743 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001744 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001745
1746 // Determine whether the type being created is already canonical or not.
John McCalldb40c7f2010-12-14 08:05:40 +00001747 bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001748 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001749 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001750 isCanonical = false;
1751
John McCalldb40c7f2010-12-14 08:05:40 +00001752 const CallingConv CallConv = EPI.ExtInfo.getCC();
1753
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001754 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001755 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001756 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001757 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001758 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001759 CanonicalArgs.reserve(NumArgs);
1760 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001761 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001762
John McCalldb40c7f2010-12-14 08:05:40 +00001763 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1764 if (CanonicalEPI.HasExceptionSpec) {
1765 CanonicalEPI.HasExceptionSpec = false;
1766 CanonicalEPI.HasAnyExceptionSpec = false;
1767 CanonicalEPI.NumExceptions = 0;
1768 }
1769 CanonicalEPI.ExtInfo
1770 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1771
Chris Lattner76a00cf2008-04-06 22:59:24 +00001772 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001773 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00001774 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001775
Chris Lattnerfd4de792007-01-27 01:15:32 +00001776 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001777 FunctionProtoType *NewIP =
1778 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001779 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001780 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001781
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001782 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001783 // for two variable size arrays (for parameter and exception types) at the
1784 // end of them.
John McCalldb40c7f2010-12-14 08:05:40 +00001785 size_t Size = sizeof(FunctionProtoType) +
1786 NumArgs * sizeof(QualType) +
1787 EPI.NumExceptions * sizeof(QualType);
1788 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
1789 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, EPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001790 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001791 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001792 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001793}
Chris Lattneref51c202006-11-10 07:17:23 +00001794
John McCalle78aac42010-03-10 03:28:59 +00001795#ifndef NDEBUG
1796static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1797 if (!isa<CXXRecordDecl>(D)) return false;
1798 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1799 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1800 return true;
1801 if (RD->getDescribedClassTemplate() &&
1802 !isa<ClassTemplateSpecializationDecl>(RD))
1803 return true;
1804 return false;
1805}
1806#endif
1807
1808/// getInjectedClassNameType - Return the unique reference to the
1809/// injected class name type for the specified templated declaration.
1810QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00001811 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00001812 assert(NeedsInjectedClassNameType(Decl));
1813 if (Decl->TypeForDecl) {
1814 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001815 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001816 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1817 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1818 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1819 } else {
John McCall2408e322010-04-27 00:57:59 +00001820 Decl->TypeForDecl =
1821 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001822 Types.push_back(Decl->TypeForDecl);
1823 }
1824 return QualType(Decl->TypeForDecl, 0);
1825}
1826
Douglas Gregor83a586e2008-04-13 21:07:44 +00001827/// getTypeDeclType - Return the unique reference to the type for the
1828/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00001829QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001830 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001831 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001832
John McCall81e38502010-02-16 03:57:14 +00001833 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001834 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001835
John McCall96f0b5f2010-03-10 06:48:02 +00001836 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1837 "Template type parameter types are always available.");
1838
John McCall81e38502010-02-16 03:57:14 +00001839 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001840 assert(!Record->getPreviousDeclaration() &&
1841 "struct/union has previous declaration");
1842 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001843 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001844 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001845 assert(!Enum->getPreviousDeclaration() &&
1846 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001847 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001848 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001849 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1850 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001851 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001852 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001853
John McCall96f0b5f2010-03-10 06:48:02 +00001854 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001855 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001856}
1857
Chris Lattner32d920b2007-01-26 02:01:53 +00001858/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001859/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001860QualType
Jay Foad39c79802011-01-12 09:06:06 +00001861ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001862 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001863
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001864 if (Canonical.isNull())
1865 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001866 Decl->TypeForDecl = new(*this, TypeAlignment)
1867 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001868 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001869 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001870}
1871
Jay Foad39c79802011-01-12 09:06:06 +00001872QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001873 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1874
1875 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1876 if (PrevDecl->TypeForDecl)
1877 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1878
1879 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1880 Types.push_back(Decl->TypeForDecl);
1881 return QualType(Decl->TypeForDecl, 0);
1882}
1883
Jay Foad39c79802011-01-12 09:06:06 +00001884QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001885 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1886
1887 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1888 if (PrevDecl->TypeForDecl)
1889 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1890
1891 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1892 Types.push_back(Decl->TypeForDecl);
1893 return QualType(Decl->TypeForDecl, 0);
1894}
1895
John McCall81904512011-01-06 01:58:22 +00001896QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
1897 QualType modifiedType,
1898 QualType equivalentType) {
1899 llvm::FoldingSetNodeID id;
1900 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
1901
1902 void *insertPos = 0;
1903 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
1904 if (type) return QualType(type, 0);
1905
1906 QualType canon = getCanonicalType(equivalentType);
1907 type = new (*this, TypeAlignment)
1908 AttributedType(canon, attrKind, modifiedType, equivalentType);
1909
1910 Types.push_back(type);
1911 AttributedTypes.InsertNode(type, insertPos);
1912
1913 return QualType(type, 0);
1914}
1915
1916
John McCallcebee162009-10-18 09:09:24 +00001917/// \brief Retrieve a substitution-result type.
1918QualType
1919ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00001920 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00001921 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001922 && "replacement types must always be canonical");
1923
1924 llvm::FoldingSetNodeID ID;
1925 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1926 void *InsertPos = 0;
1927 SubstTemplateTypeParmType *SubstParm
1928 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1929
1930 if (!SubstParm) {
1931 SubstParm = new (*this, TypeAlignment)
1932 SubstTemplateTypeParmType(Parm, Replacement);
1933 Types.push_back(SubstParm);
1934 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1935 }
1936
1937 return QualType(SubstParm, 0);
1938}
1939
Douglas Gregorada4b792011-01-14 02:55:32 +00001940/// \brief Retrieve a
1941QualType ASTContext::getSubstTemplateTypeParmPackType(
1942 const TemplateTypeParmType *Parm,
1943 const TemplateArgument &ArgPack) {
1944#ifndef NDEBUG
1945 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1946 PEnd = ArgPack.pack_end();
1947 P != PEnd; ++P) {
1948 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
1949 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
1950 }
1951#endif
1952
1953 llvm::FoldingSetNodeID ID;
1954 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
1955 void *InsertPos = 0;
1956 if (SubstTemplateTypeParmPackType *SubstParm
1957 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
1958 return QualType(SubstParm, 0);
1959
1960 QualType Canon;
1961 if (!Parm->isCanonicalUnqualified()) {
1962 Canon = getCanonicalType(QualType(Parm, 0));
1963 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
1964 ArgPack);
1965 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
1966 }
1967
1968 SubstTemplateTypeParmPackType *SubstParm
1969 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
1970 ArgPack);
1971 Types.push_back(SubstParm);
1972 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1973 return QualType(SubstParm, 0);
1974}
1975
Douglas Gregoreff93e02009-02-05 23:33:38 +00001976/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001977/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001978/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001979QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001980 bool ParameterPack,
Jay Foad39c79802011-01-12 09:06:06 +00001981 IdentifierInfo *Name) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001982 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001983 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001984 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001985 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001986 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1987
1988 if (TypeParm)
1989 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001990
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001991 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001992 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001993 TypeParm = new (*this, TypeAlignment)
1994 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001995
1996 TemplateTypeParmType *TypeCheck
1997 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1998 assert(!TypeCheck && "Template type parameter canonical type broken");
1999 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002000 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002001 TypeParm = new (*this, TypeAlignment)
2002 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002003
2004 Types.push_back(TypeParm);
2005 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2006
2007 return QualType(TypeParm, 0);
2008}
2009
John McCalle78aac42010-03-10 03:28:59 +00002010TypeSourceInfo *
2011ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2012 SourceLocation NameLoc,
2013 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002014 QualType CanonType) const {
John McCalle78aac42010-03-10 03:28:59 +00002015 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2016
2017 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2018 TemplateSpecializationTypeLoc TL
2019 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2020 TL.setTemplateNameLoc(NameLoc);
2021 TL.setLAngleLoc(Args.getLAngleLoc());
2022 TL.setRAngleLoc(Args.getRAngleLoc());
2023 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2024 TL.setArgLocInfo(i, Args[i].getLocInfo());
2025 return DI;
2026}
2027
Mike Stump11289f42009-09-09 15:08:12 +00002028QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002029ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002030 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002031 QualType Canon) const {
John McCall6b51f282009-11-23 01:53:49 +00002032 unsigned NumArgs = Args.size();
2033
John McCall0ad16662009-10-29 08:12:44 +00002034 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2035 ArgVec.reserve(NumArgs);
2036 for (unsigned i = 0; i != NumArgs; ++i)
2037 ArgVec.push_back(Args[i].getArgument());
2038
John McCall2408e322010-04-27 00:57:59 +00002039 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00002040 Canon);
John McCall0ad16662009-10-29 08:12:44 +00002041}
2042
2043QualType
2044ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002045 const TemplateArgument *Args,
2046 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002047 QualType Canon) const {
Douglas Gregor15301382009-07-30 17:40:51 +00002048 if (!Canon.isNull())
2049 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002050 else
2051 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00002052
Douglas Gregora8e02e72009-07-28 23:00:59 +00002053 // Allocate the (non-canonical) template specialization type, but don't
2054 // try to unique it: these types typically have location information that
2055 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002056 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002057 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002058 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002059 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002060 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002061 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002062 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002063
Douglas Gregor8bf42052009-02-09 18:46:07 +00002064 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002065 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002066}
2067
Mike Stump11289f42009-09-09 15:08:12 +00002068QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002069ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2070 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002071 unsigned NumArgs) const {
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002072 // Build the canonical template specialization type.
2073 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2074 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2075 CanonArgs.reserve(NumArgs);
2076 for (unsigned I = 0; I != NumArgs; ++I)
2077 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2078
2079 // Determine whether this canonical template specialization type already
2080 // exists.
2081 llvm::FoldingSetNodeID ID;
2082 TemplateSpecializationType::Profile(ID, CanonTemplate,
2083 CanonArgs.data(), NumArgs, *this);
2084
2085 void *InsertPos = 0;
2086 TemplateSpecializationType *Spec
2087 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2088
2089 if (!Spec) {
2090 // Allocate a new canonical template specialization type.
2091 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2092 sizeof(TemplateArgument) * NumArgs),
2093 TypeAlignment);
2094 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2095 CanonArgs.data(), NumArgs,
2096 QualType());
2097 Types.push_back(Spec);
2098 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2099 }
2100
2101 assert(Spec->isDependentType() &&
2102 "Non-dependent template-id type must have a canonical type");
2103 return QualType(Spec, 0);
2104}
2105
2106QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002107ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2108 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002109 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002110 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002111 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002112
2113 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002114 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002115 if (T)
2116 return QualType(T, 0);
2117
Douglas Gregorc42075a2010-02-04 18:10:26 +00002118 QualType Canon = NamedType;
2119 if (!Canon.isCanonical()) {
2120 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002121 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2122 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002123 (void)CheckT;
2124 }
2125
Abramo Bagnara6150c882010-05-11 21:36:43 +00002126 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002127 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002128 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002129 return QualType(T, 0);
2130}
2131
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002132QualType
Jay Foad39c79802011-01-12 09:06:06 +00002133ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002134 llvm::FoldingSetNodeID ID;
2135 ParenType::Profile(ID, InnerType);
2136
2137 void *InsertPos = 0;
2138 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2139 if (T)
2140 return QualType(T, 0);
2141
2142 QualType Canon = InnerType;
2143 if (!Canon.isCanonical()) {
2144 Canon = getCanonicalType(InnerType);
2145 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2146 assert(!CheckT && "Paren canonical type broken");
2147 (void)CheckT;
2148 }
2149
2150 T = new (*this) ParenType(InnerType, Canon);
2151 Types.push_back(T);
2152 ParenTypes.InsertNode(T, InsertPos);
2153 return QualType(T, 0);
2154}
2155
Douglas Gregor02085352010-03-31 20:19:30 +00002156QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2157 NestedNameSpecifier *NNS,
2158 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002159 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002160 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2161
2162 if (Canon.isNull()) {
2163 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002164 ElaboratedTypeKeyword CanonKeyword = Keyword;
2165 if (Keyword == ETK_None)
2166 CanonKeyword = ETK_Typename;
2167
2168 if (CanonNNS != NNS || CanonKeyword != Keyword)
2169 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002170 }
2171
2172 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002173 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002174
2175 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002176 DependentNameType *T
2177 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002178 if (T)
2179 return QualType(T, 0);
2180
Douglas Gregor02085352010-03-31 20:19:30 +00002181 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002182 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002183 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002184 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002185}
2186
Mike Stump11289f42009-09-09 15:08:12 +00002187QualType
John McCallc392f372010-06-11 00:33:02 +00002188ASTContext::getDependentTemplateSpecializationType(
2189 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002190 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002191 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002192 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002193 // TODO: avoid this copy
2194 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2195 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2196 ArgCopy.push_back(Args[I].getArgument());
2197 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2198 ArgCopy.size(),
2199 ArgCopy.data());
2200}
2201
2202QualType
2203ASTContext::getDependentTemplateSpecializationType(
2204 ElaboratedTypeKeyword Keyword,
2205 NestedNameSpecifier *NNS,
2206 const IdentifierInfo *Name,
2207 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002208 const TemplateArgument *Args) const {
Douglas Gregordce2b622009-04-01 00:28:59 +00002209 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2210
Douglas Gregorc42075a2010-02-04 18:10:26 +00002211 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002212 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2213 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002214
2215 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002216 DependentTemplateSpecializationType *T
2217 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002218 if (T)
2219 return QualType(T, 0);
2220
John McCallc392f372010-06-11 00:33:02 +00002221 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002222
John McCallc392f372010-06-11 00:33:02 +00002223 ElaboratedTypeKeyword CanonKeyword = Keyword;
2224 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2225
2226 bool AnyNonCanonArgs = false;
2227 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2228 for (unsigned I = 0; I != NumArgs; ++I) {
2229 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2230 if (!CanonArgs[I].structurallyEquals(Args[I]))
2231 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002232 }
2233
John McCallc392f372010-06-11 00:33:02 +00002234 QualType Canon;
2235 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2236 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2237 Name, NumArgs,
2238 CanonArgs.data());
2239
2240 // Find the insert position again.
2241 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2242 }
2243
2244 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2245 sizeof(TemplateArgument) * NumArgs),
2246 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002247 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002248 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002249 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002250 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002251 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002252}
2253
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002254QualType ASTContext::getPackExpansionType(QualType Pattern,
2255 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002256 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002257 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002258
2259 assert(Pattern->containsUnexpandedParameterPack() &&
2260 "Pack expansions must expand one or more parameter packs");
2261 void *InsertPos = 0;
2262 PackExpansionType *T
2263 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2264 if (T)
2265 return QualType(T, 0);
2266
2267 QualType Canon;
2268 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002269 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002270
2271 // Find the insert position again.
2272 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2273 }
2274
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002275 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002276 Types.push_back(T);
2277 PackExpansionTypes.InsertNode(T, InsertPos);
2278 return QualType(T, 0);
2279}
2280
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002281/// CmpProtocolNames - Comparison predicate for sorting protocols
2282/// alphabetically.
2283static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2284 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002285 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002286}
2287
John McCall8b07ec22010-05-15 11:32:37 +00002288static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002289 unsigned NumProtocols) {
2290 if (NumProtocols == 0) return true;
2291
2292 for (unsigned i = 1; i != NumProtocols; ++i)
2293 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2294 return false;
2295 return true;
2296}
2297
2298static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002299 unsigned &NumProtocols) {
2300 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002301
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002302 // Sort protocols, keyed by name.
2303 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2304
2305 // Remove duplicates.
2306 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2307 NumProtocols = ProtocolsEnd-Protocols;
2308}
2309
John McCall8b07ec22010-05-15 11:32:37 +00002310QualType ASTContext::getObjCObjectType(QualType BaseType,
2311 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002312 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002313 // If the base type is an interface and there aren't any protocols
2314 // to add, then the interface type will do just fine.
2315 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2316 return BaseType;
2317
2318 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002319 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002320 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002321 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002322 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2323 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002324
John McCall8b07ec22010-05-15 11:32:37 +00002325 // Build the canonical type, which has the canonical base type and
2326 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002327 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002328 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2329 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2330 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002331 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2332 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002333 unsigned UniqueCount = NumProtocols;
2334
John McCallfc93cf92009-10-22 22:37:11 +00002335 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002336 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2337 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002338 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002339 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2340 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002341 }
2342
2343 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002344 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2345 }
2346
2347 unsigned Size = sizeof(ObjCObjectTypeImpl);
2348 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2349 void *Mem = Allocate(Size, TypeAlignment);
2350 ObjCObjectTypeImpl *T =
2351 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2352
2353 Types.push_back(T);
2354 ObjCObjectTypes.InsertNode(T, InsertPos);
2355 return QualType(T, 0);
2356}
2357
2358/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2359/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002360QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002361 llvm::FoldingSetNodeID ID;
2362 ObjCObjectPointerType::Profile(ID, ObjectT);
2363
2364 void *InsertPos = 0;
2365 if (ObjCObjectPointerType *QT =
2366 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2367 return QualType(QT, 0);
2368
2369 // Find the canonical object type.
2370 QualType Canonical;
2371 if (!ObjectT.isCanonical()) {
2372 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2373
2374 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002375 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2376 }
2377
Douglas Gregorf85bee62010-02-08 22:59:26 +00002378 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002379 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2380 ObjCObjectPointerType *QType =
2381 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002382
Steve Narofffb4330f2009-06-17 22:40:22 +00002383 Types.push_back(QType);
2384 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002385 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002386}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002387
Douglas Gregor1c283312010-08-11 12:19:30 +00002388/// getObjCInterfaceType - Return the unique reference to the type for the
2389/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002390QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002391 if (Decl->TypeForDecl)
2392 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002393
Douglas Gregor1c283312010-08-11 12:19:30 +00002394 // FIXME: redeclarations?
2395 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2396 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2397 Decl->TypeForDecl = T;
2398 Types.push_back(T);
2399 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002400}
2401
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002402/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2403/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002404/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002405/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002406/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002407QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002408 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002409 if (tofExpr->isTypeDependent()) {
2410 llvm::FoldingSetNodeID ID;
2411 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002412
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002413 void *InsertPos = 0;
2414 DependentTypeOfExprType *Canon
2415 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2416 if (Canon) {
2417 // We already have a "canonical" version of an identical, dependent
2418 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002419 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002420 QualType((TypeOfExprType*)Canon, 0));
2421 }
2422 else {
2423 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002424 Canon
2425 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002426 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2427 toe = Canon;
2428 }
2429 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002430 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002431 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002432 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002433 Types.push_back(toe);
2434 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002435}
2436
Steve Naroffa773cd52007-08-01 18:02:17 +00002437/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2438/// TypeOfType AST's. The only motivation to unique these nodes would be
2439/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002440/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002441/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002442QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002443 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002444 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002445 Types.push_back(tot);
2446 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002447}
2448
Anders Carlssonad6bd352009-06-24 21:24:56 +00002449/// getDecltypeForExpr - Given an expr, will return the decltype for that
2450/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002451static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002452 if (e->isTypeDependent())
2453 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002454
Anders Carlssonad6bd352009-06-24 21:24:56 +00002455 // If e is an id expression or a class member access, decltype(e) is defined
2456 // as the type of the entity named by e.
2457 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2458 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2459 return VD->getType();
2460 }
2461 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2462 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2463 return FD->getType();
2464 }
2465 // If e is a function call or an invocation of an overloaded operator,
2466 // (parentheses around e are ignored), decltype(e) is defined as the
2467 // return type of that function.
2468 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2469 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002470
Anders Carlssonad6bd352009-06-24 21:24:56 +00002471 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002472
2473 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002474 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002475 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002476 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002477
Anders Carlssonad6bd352009-06-24 21:24:56 +00002478 return T;
2479}
2480
Anders Carlsson81df7b82009-06-24 19:06:50 +00002481/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2482/// DecltypeType AST's. The only motivation to unique these nodes would be
2483/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002484/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002485/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002486QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002487 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002488 if (e->isTypeDependent()) {
2489 llvm::FoldingSetNodeID ID;
2490 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002491
Douglas Gregora21f6c32009-07-30 23:36:40 +00002492 void *InsertPos = 0;
2493 DependentDecltypeType *Canon
2494 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2495 if (Canon) {
2496 // We already have a "canonical" version of an equivalent, dependent
2497 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002498 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002499 QualType((DecltypeType*)Canon, 0));
2500 }
2501 else {
2502 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002503 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002504 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2505 dt = Canon;
2506 }
2507 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002508 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002509 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002510 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002511 Types.push_back(dt);
2512 return QualType(dt, 0);
2513}
2514
Chris Lattnerfb072462007-01-23 05:45:31 +00002515/// getTagDeclType - Return the unique reference to the type for the
2516/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002517QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002518 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002519 // FIXME: What is the design on getTagDeclType when it requires casting
2520 // away const? mutable?
2521 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002522}
2523
Mike Stump11289f42009-09-09 15:08:12 +00002524/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2525/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2526/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002527CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002528 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002529}
Chris Lattnerfb072462007-01-23 05:45:31 +00002530
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002531/// getSignedWCharType - Return the type of "signed wchar_t".
2532/// Used when in C++, as a GCC extension.
2533QualType ASTContext::getSignedWCharType() const {
2534 // FIXME: derive from "Target" ?
2535 return WCharTy;
2536}
2537
2538/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2539/// Used when in C++, as a GCC extension.
2540QualType ASTContext::getUnsignedWCharType() const {
2541 // FIXME: derive from "Target" ?
2542 return UnsignedIntTy;
2543}
2544
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002545/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2546/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2547QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002548 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002549}
2550
Chris Lattnera21ad802008-04-02 05:18:44 +00002551//===----------------------------------------------------------------------===//
2552// Type Operators
2553//===----------------------------------------------------------------------===//
2554
Jay Foad39c79802011-01-12 09:06:06 +00002555CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002556 // Push qualifiers into arrays, and then discard any remaining
2557 // qualifiers.
2558 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002559 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002560 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002561 QualType Result;
2562 if (isa<ArrayType>(Ty)) {
2563 Result = getArrayDecayedType(QualType(Ty,0));
2564 } else if (isa<FunctionType>(Ty)) {
2565 Result = getPointerType(QualType(Ty, 0));
2566 } else {
2567 Result = QualType(Ty, 0);
2568 }
2569
2570 return CanQualType::CreateUnsafe(Result);
2571}
2572
Chris Lattnered0d0792008-04-06 22:41:35 +00002573/// getCanonicalType - Return the canonical (structural) type corresponding to
2574/// the specified potentially non-canonical type. The non-canonical version
2575/// of a type may have many "decorated" versions of types. Decorators can
2576/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2577/// to be free of any of these, allowing two canonical types to be compared
2578/// for exact equality with a simple pointer comparison.
Jay Foad39c79802011-01-12 09:06:06 +00002579CanQualType ASTContext::getCanonicalType(QualType T) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002580 QualifierCollector Quals;
2581 const Type *Ptr = Quals.strip(T);
2582 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002583
John McCall8ccfcb52009-09-24 19:53:00 +00002584 // The canonical internal type will be the canonical type *except*
2585 // that we push type qualifiers down through array types.
2586
2587 // If there are no new qualifiers to push down, stop here.
2588 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002589 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002590
John McCall8ccfcb52009-09-24 19:53:00 +00002591 // If the type qualifiers are on an array type, get the canonical
2592 // type of the array with the qualifiers applied to the element
2593 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002594 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2595 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002596 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002597
Chris Lattner7adf0762008-08-04 07:31:14 +00002598 // Get the canonical version of the element with the extra qualifiers on it.
2599 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002600 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002601 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002602
Chris Lattner7adf0762008-08-04 07:31:14 +00002603 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002604 return CanQualType::CreateUnsafe(
2605 getConstantArrayType(NewEltTy, CAT->getSize(),
2606 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002607 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002608 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002609 return CanQualType::CreateUnsafe(
2610 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002611 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002612
Douglas Gregor4619e432008-12-05 23:32:09 +00002613 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002614 return CanQualType::CreateUnsafe(
2615 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002616 DSAT->getSizeExpr(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002617 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002618 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002619 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002620
Chris Lattner7adf0762008-08-04 07:31:14 +00002621 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002622 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002623 VAT->getSizeExpr(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002624 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002625 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002626 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002627}
2628
Chandler Carruth607f38e2009-12-29 07:16:59 +00002629QualType ASTContext::getUnqualifiedArrayType(QualType T,
2630 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002631 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002632 const ArrayType *AT = getAsArrayType(T);
2633 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002634 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002635 }
2636
Chandler Carruth607f38e2009-12-29 07:16:59 +00002637 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002638 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002639 if (Elt == UnqualElt)
2640 return T;
2641
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002642 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002643 return getConstantArrayType(UnqualElt, CAT->getSize(),
2644 CAT->getSizeModifier(), 0);
2645 }
2646
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002647 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002648 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2649 }
2650
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002651 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2652 return getVariableArrayType(UnqualElt,
John McCallc3007a22010-10-26 07:05:15 +00002653 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002654 VAT->getSizeModifier(),
2655 VAT->getIndexTypeCVRQualifiers(),
2656 VAT->getBracketsRange());
2657 }
2658
2659 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCallc3007a22010-10-26 07:05:15 +00002660 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002661 DSAT->getSizeModifier(), 0,
2662 SourceRange());
2663}
2664
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002665/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2666/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2667/// they point to and return true. If T1 and T2 aren't pointer types
2668/// or pointer-to-member types, or if they are not similar at this
2669/// level, returns false and leaves T1 and T2 unchanged. Top-level
2670/// qualifiers on T1 and T2 are ignored. This function will typically
2671/// be called in a loop that successively "unwraps" pointer and
2672/// pointer-to-member types to compare them at each level.
2673bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2674 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2675 *T2PtrType = T2->getAs<PointerType>();
2676 if (T1PtrType && T2PtrType) {
2677 T1 = T1PtrType->getPointeeType();
2678 T2 = T2PtrType->getPointeeType();
2679 return true;
2680 }
2681
2682 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2683 *T2MPType = T2->getAs<MemberPointerType>();
2684 if (T1MPType && T2MPType &&
2685 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2686 QualType(T2MPType->getClass(), 0))) {
2687 T1 = T1MPType->getPointeeType();
2688 T2 = T2MPType->getPointeeType();
2689 return true;
2690 }
2691
2692 if (getLangOptions().ObjC1) {
2693 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2694 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2695 if (T1OPType && T2OPType) {
2696 T1 = T1OPType->getPointeeType();
2697 T2 = T2OPType->getPointeeType();
2698 return true;
2699 }
2700 }
2701
2702 // FIXME: Block pointers, too?
2703
2704 return false;
2705}
2706
Jay Foad39c79802011-01-12 09:06:06 +00002707DeclarationNameInfo
2708ASTContext::getNameForTemplate(TemplateName Name,
2709 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002710 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002711 // DNInfo work in progress: CHECKME: what about DNLoc?
2712 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2713
John McCall847e2a12009-11-24 18:42:40 +00002714 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002715 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002716 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002717 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2718 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002719 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002720 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2721 // DNInfo work in progress: FIXME: source locations?
2722 DeclarationNameLoc DNLoc;
2723 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2724 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2725 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002726 }
2727 }
2728
John McCalld28ae272009-12-02 08:04:21 +00002729 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2730 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002731 // DNInfo work in progress: CHECKME: what about DNLoc?
2732 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002733}
2734
Jay Foad39c79802011-01-12 09:06:06 +00002735TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002736 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2737 if (TemplateTemplateParmDecl *TTP
2738 = dyn_cast<TemplateTemplateParmDecl>(Template))
2739 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2740
2741 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002742 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002743 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002744
Douglas Gregor5590be02011-01-15 06:45:20 +00002745 if (SubstTemplateTemplateParmPackStorage *SubstPack
2746 = Name.getAsSubstTemplateTemplateParmPack()) {
2747 TemplateTemplateParmDecl *CanonParam
2748 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2749 TemplateArgument CanonArgPack
2750 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2751 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2752 }
2753
John McCalld28ae272009-12-02 08:04:21 +00002754 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002755
Douglas Gregor6bc50582009-05-07 06:41:52 +00002756 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2757 assert(DTN && "Non-dependent template names must refer to template decls.");
2758 return DTN->CanonicalTemplateName;
2759}
2760
Douglas Gregoradee3e32009-11-11 23:06:43 +00002761bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2762 X = getCanonicalTemplateName(X);
2763 Y = getCanonicalTemplateName(Y);
2764 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2765}
2766
Mike Stump11289f42009-09-09 15:08:12 +00002767TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00002768ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00002769 switch (Arg.getKind()) {
2770 case TemplateArgument::Null:
2771 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002772
Douglas Gregora8e02e72009-07-28 23:00:59 +00002773 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002774 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002775
Douglas Gregora8e02e72009-07-28 23:00:59 +00002776 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002777 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002778
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002779 case TemplateArgument::Template:
2780 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002781
2782 case TemplateArgument::TemplateExpansion:
2783 return TemplateArgument(getCanonicalTemplateName(
2784 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00002785 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002786
Douglas Gregora8e02e72009-07-28 23:00:59 +00002787 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002788 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002789 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002790
Douglas Gregora8e02e72009-07-28 23:00:59 +00002791 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002792 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002793
Douglas Gregora8e02e72009-07-28 23:00:59 +00002794 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00002795 if (Arg.pack_size() == 0)
2796 return Arg;
2797
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002798 TemplateArgument *CanonArgs
2799 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00002800 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002801 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002802 AEnd = Arg.pack_end();
2803 A != AEnd; (void)++A, ++Idx)
2804 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002805
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002806 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00002807 }
2808 }
2809
2810 // Silence GCC warning
2811 assert(false && "Unhandled template argument kind");
2812 return TemplateArgument();
2813}
2814
Douglas Gregor333489b2009-03-27 23:10:48 +00002815NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00002816ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00002817 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002818 return 0;
2819
2820 switch (NNS->getKind()) {
2821 case NestedNameSpecifier::Identifier:
2822 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002823 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002824 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2825 NNS->getAsIdentifier());
2826
2827 case NestedNameSpecifier::Namespace:
2828 // A namespace is canonical; build a nested-name-specifier with
2829 // this namespace and no prefix.
2830 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2831
2832 case NestedNameSpecifier::TypeSpec:
2833 case NestedNameSpecifier::TypeSpecWithTemplate: {
2834 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00002835
2836 // If we have some kind of dependent-named type (e.g., "typename T::type"),
2837 // break it apart into its prefix and identifier, then reconsititute those
2838 // as the canonical nested-name-specifier. This is required to canonicalize
2839 // a dependent nested-name-specifier involving typedefs of dependent-name
2840 // types, e.g.,
2841 // typedef typename T::type T1;
2842 // typedef typename T1::type T2;
2843 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
2844 NestedNameSpecifier *Prefix
2845 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
2846 return NestedNameSpecifier::Create(*this, Prefix,
2847 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
2848 }
2849
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00002850 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00002851 if (const DependentTemplateSpecializationType *DTST
2852 = T->getAs<DependentTemplateSpecializationType>()) {
2853 NestedNameSpecifier *Prefix
2854 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
2855 TemplateName Name
2856 = getDependentTemplateName(Prefix, DTST->getIdentifier());
2857 T = getTemplateSpecializationType(Name,
2858 DTST->getArgs(), DTST->getNumArgs());
2859 T = getCanonicalType(T);
2860 }
2861
2862 return NestedNameSpecifier::Create(*this, 0, false, T.getTypePtr());
Douglas Gregor333489b2009-03-27 23:10:48 +00002863 }
2864
2865 case NestedNameSpecifier::Global:
2866 // The global specifier is canonical and unique.
2867 return NNS;
2868 }
2869
2870 // Required to silence a GCC warning
2871 return 0;
2872}
2873
Chris Lattner7adf0762008-08-04 07:31:14 +00002874
Jay Foad39c79802011-01-12 09:06:06 +00002875const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00002876 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002877 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002878 // Handle the common positive case fast.
2879 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2880 return AT;
2881 }
Mike Stump11289f42009-09-09 15:08:12 +00002882
John McCall8ccfcb52009-09-24 19:53:00 +00002883 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002884 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002885 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002886 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002887
John McCall8ccfcb52009-09-24 19:53:00 +00002888 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002889 // implements C99 6.7.3p8: "If the specification of an array type includes
2890 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002891
Chris Lattner7adf0762008-08-04 07:31:14 +00002892 // If we get here, we either have type qualifiers on the type, or we have
2893 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002894 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002895
John McCall8ccfcb52009-09-24 19:53:00 +00002896 QualifierCollector Qs;
John McCall717d9b02010-12-10 11:01:00 +00002897 const Type *Ty = Qs.strip(T.getDesugaredType(*this));
Mike Stump11289f42009-09-09 15:08:12 +00002898
Chris Lattner7adf0762008-08-04 07:31:14 +00002899 // If we have a simple case, just return now.
2900 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002901 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002902 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002903
Chris Lattner7adf0762008-08-04 07:31:14 +00002904 // Otherwise, we have an array and we have qualifiers on it. Push the
2905 // qualifiers into the array element type and return a new array type.
2906 // Get the canonical version of the element with the extra qualifiers on it.
2907 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002908 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002909
Chris Lattner7adf0762008-08-04 07:31:14 +00002910 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2911 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2912 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002913 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002914 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2915 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2916 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002917 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002918
Mike Stump11289f42009-09-09 15:08:12 +00002919 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002920 = dyn_cast<DependentSizedArrayType>(ATy))
2921 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002922 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002923 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00002924 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002925 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002926 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002927
Chris Lattner7adf0762008-08-04 07:31:14 +00002928 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002929 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00002930 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00002931 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002932 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002933 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002934}
2935
Chris Lattnera21ad802008-04-02 05:18:44 +00002936/// getArrayDecayedType - Return the properly qualified result of decaying the
2937/// specified array type to a pointer. This operation is non-trivial when
2938/// handling typedefs etc. The canonical type of "T" must be an array type,
2939/// this returns a pointer to a properly qualified element of the array.
2940///
2941/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00002942QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00002943 // Get the element type with 'getAsArrayType' so that we don't lose any
2944 // typedefs in the element type of the array. This also handles propagation
2945 // of type qualifiers from the array type into the element type if present
2946 // (C99 6.7.3p8).
2947 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2948 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002949
Chris Lattner7adf0762008-08-04 07:31:14 +00002950 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002951
2952 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002953 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002954}
2955
Jay Foad39c79802011-01-12 09:06:06 +00002956QualType ASTContext::getBaseElementType(QualType QT) const {
John McCall8ccfcb52009-09-24 19:53:00 +00002957 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002958 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2959 QT = AT->getElementType();
John McCall717d9b02010-12-10 11:01:00 +00002960 return Qs.apply(*this, QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002961}
2962
Jay Foad39c79802011-01-12 09:06:06 +00002963QualType ASTContext::getBaseElementType(const ArrayType *AT) const {
Anders Carlsson4bf82142009-09-25 01:23:32 +00002964 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002965
Anders Carlsson4bf82142009-09-25 01:23:32 +00002966 if (const ArrayType *AT = getAsArrayType(ElemTy))
2967 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002968
Anders Carlssone0808df2008-12-21 03:44:36 +00002969 return ElemTy;
2970}
2971
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002972/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002973uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002974ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2975 uint64_t ElementCount = 1;
2976 do {
2977 ElementCount *= CA->getSize().getZExtValue();
2978 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2979 } while (CA);
2980 return ElementCount;
2981}
2982
Steve Naroff0af91202007-04-27 21:51:21 +00002983/// getFloatingRank - Return a relative rank for floating point types.
2984/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002985static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002986 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002987 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002988
John McCall9dd450b2009-09-21 23:43:11 +00002989 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2990 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002991 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002992 case BuiltinType::Float: return FloatRank;
2993 case BuiltinType::Double: return DoubleRank;
2994 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002995 }
2996}
2997
Mike Stump11289f42009-09-09 15:08:12 +00002998/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2999/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003000/// 'typeDomain' is a real floating point or complex type.
3001/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003002QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3003 QualType Domain) const {
3004 FloatingRank EltRank = getFloatingRank(Size);
3005 if (Domain->isComplexType()) {
3006 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003007 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003008 case FloatRank: return FloatComplexTy;
3009 case DoubleRank: return DoubleComplexTy;
3010 case LongDoubleRank: return LongDoubleComplexTy;
3011 }
Steve Naroff0af91202007-04-27 21:51:21 +00003012 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003013
3014 assert(Domain->isRealFloatingType() && "Unknown domain!");
3015 switch (EltRank) {
3016 default: assert(0 && "getFloatingRank(): illegal value for rank");
3017 case FloatRank: return FloatTy;
3018 case DoubleRank: return DoubleTy;
3019 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003020 }
Steve Naroffe4718892007-04-27 18:30:00 +00003021}
3022
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003023/// getFloatingTypeOrder - Compare the rank of the two specified floating
3024/// point types, ignoring the domain of the type (i.e. 'double' ==
3025/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003026/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003027int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003028 FloatingRank LHSR = getFloatingRank(LHS);
3029 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003030
Chris Lattnerb90739d2008-04-06 23:38:49 +00003031 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003032 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003033 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003034 return 1;
3035 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003036}
3037
Chris Lattner76a00cf2008-04-06 22:59:24 +00003038/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3039/// routine will assert if passed a built-in type that isn't an integer or enum,
3040/// or if it is not canonicalized.
Jay Foad39c79802011-01-12 09:06:06 +00003041unsigned ASTContext::getIntegerRank(Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003042 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00003043 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003044 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003045
Chris Lattnerad3467e2010-12-25 23:25:43 +00003046 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3047 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003048 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3049
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003050 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3051 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3052
3053 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3054 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3055
Chris Lattner76a00cf2008-04-06 22:59:24 +00003056 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003057 default: assert(0 && "getIntegerRank(): not a built-in integer");
3058 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003059 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003060 case BuiltinType::Char_S:
3061 case BuiltinType::Char_U:
3062 case BuiltinType::SChar:
3063 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003064 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003065 case BuiltinType::Short:
3066 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003067 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003068 case BuiltinType::Int:
3069 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003070 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003071 case BuiltinType::Long:
3072 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003073 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003074 case BuiltinType::LongLong:
3075 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003076 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003077 case BuiltinType::Int128:
3078 case BuiltinType::UInt128:
3079 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003080 }
3081}
3082
Eli Friedman629ffb92009-08-20 04:21:42 +00003083/// \brief Whether this is a promotable bitfield reference according
3084/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3085///
3086/// \returns the type this bit-field will promote to, or NULL if no
3087/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003088QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003089 if (E->isTypeDependent() || E->isValueDependent())
3090 return QualType();
3091
Eli Friedman629ffb92009-08-20 04:21:42 +00003092 FieldDecl *Field = E->getBitField();
3093 if (!Field)
3094 return QualType();
3095
3096 QualType FT = Field->getType();
3097
3098 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3099 uint64_t BitWidth = BitWidthAP.getZExtValue();
3100 uint64_t IntSize = getTypeSize(IntTy);
3101 // GCC extension compatibility: if the bit-field size is less than or equal
3102 // to the size of int, it gets promoted no matter what its type is.
3103 // For instance, unsigned long bf : 4 gets promoted to signed int.
3104 if (BitWidth < IntSize)
3105 return IntTy;
3106
3107 if (BitWidth == IntSize)
3108 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3109
3110 // Types bigger than int are not subject to promotions, and therefore act
3111 // like the base type.
3112 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3113 // is ridiculous.
3114 return QualType();
3115}
3116
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003117/// getPromotedIntegerType - Returns the type that Promotable will
3118/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3119/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003120QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003121 assert(!Promotable.isNull());
3122 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003123 if (const EnumType *ET = Promotable->getAs<EnumType>())
3124 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003125 if (Promotable->isSignedIntegerType())
3126 return IntTy;
3127 uint64_t PromotableSize = getTypeSize(Promotable);
3128 uint64_t IntSize = getTypeSize(IntTy);
3129 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3130 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3131}
3132
Mike Stump11289f42009-09-09 15:08:12 +00003133/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003134/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003135/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003136int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003137 Type *LHSC = getCanonicalType(LHS).getTypePtr();
3138 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003139 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003140
Chris Lattner76a00cf2008-04-06 22:59:24 +00003141 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3142 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003143
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003144 unsigned LHSRank = getIntegerRank(LHSC);
3145 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003146
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003147 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3148 if (LHSRank == RHSRank) return 0;
3149 return LHSRank > RHSRank ? 1 : -1;
3150 }
Mike Stump11289f42009-09-09 15:08:12 +00003151
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003152 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3153 if (LHSUnsigned) {
3154 // If the unsigned [LHS] type is larger, return it.
3155 if (LHSRank >= RHSRank)
3156 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003157
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003158 // If the signed type can represent all values of the unsigned type, it
3159 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003160 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003161 return -1;
3162 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003163
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003164 // If the unsigned [RHS] type is larger, return it.
3165 if (RHSRank >= LHSRank)
3166 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003167
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003168 // If the signed type can represent all values of the unsigned type, it
3169 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003170 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003171 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003172}
Anders Carlsson98f07902007-08-17 05:31:46 +00003173
Anders Carlsson6d417272009-11-14 21:45:58 +00003174static RecordDecl *
Jay Foad39c79802011-01-12 09:06:06 +00003175CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
Anders Carlsson6d417272009-11-14 21:45:58 +00003176 SourceLocation L, IdentifierInfo *Id) {
3177 if (Ctx.getLangOptions().CPlusPlus)
3178 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3179 else
3180 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3181}
3182
Mike Stump11289f42009-09-09 15:08:12 +00003183// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003184QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003185 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003186 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003187 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003188 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003189 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003190
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003191 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003192
Anders Carlsson98f07902007-08-17 05:31:46 +00003193 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003194 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003195 // int flags;
3196 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003197 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003198 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003199 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003200 FieldTypes[3] = LongTy;
3201
Anders Carlsson98f07902007-08-17 05:31:46 +00003202 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003203 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003204 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003205 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003206 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003207 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003208 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003209 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003210 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003211 }
3212
Douglas Gregord5058122010-02-11 01:19:42 +00003213 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003214 }
Mike Stump11289f42009-09-09 15:08:12 +00003215
Anders Carlsson98f07902007-08-17 05:31:46 +00003216 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003217}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003218
Douglas Gregor512b0772009-04-23 22:29:11 +00003219void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003220 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003221 assert(Rec && "Invalid CFConstantStringType");
3222 CFConstantStringTypeDecl = Rec->getDecl();
3223}
3224
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003225// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003226QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003227 if (!NSConstantStringTypeDecl) {
3228 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003229 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003230 &Idents.get("__builtin_NSString"));
3231 NSConstantStringTypeDecl->startDefinition();
3232
3233 QualType FieldTypes[3];
3234
3235 // const int *isa;
3236 FieldTypes[0] = getPointerType(IntTy.withConst());
3237 // const char *str;
3238 FieldTypes[1] = getPointerType(CharTy.withConst());
3239 // unsigned int length;
3240 FieldTypes[2] = UnsignedIntTy;
3241
3242 // Create fields
3243 for (unsigned i = 0; i < 3; ++i) {
3244 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3245 SourceLocation(), 0,
3246 FieldTypes[i], /*TInfo=*/0,
3247 /*BitWidth=*/0,
3248 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003249 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003250 NSConstantStringTypeDecl->addDecl(Field);
3251 }
3252
3253 NSConstantStringTypeDecl->completeDefinition();
3254 }
3255
3256 return getTagDeclType(NSConstantStringTypeDecl);
3257}
3258
3259void ASTContext::setNSConstantStringType(QualType T) {
3260 const RecordType *Rec = T->getAs<RecordType>();
3261 assert(Rec && "Invalid NSConstantStringType");
3262 NSConstantStringTypeDecl = Rec->getDecl();
3263}
3264
Jay Foad39c79802011-01-12 09:06:06 +00003265QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003266 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003267 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003268 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003269 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003270 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003271
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003272 QualType FieldTypes[] = {
3273 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003274 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003275 getPointerType(UnsignedLongTy),
3276 getConstantArrayType(UnsignedLongTy,
3277 llvm::APInt(32, 5), ArrayType::Normal, 0)
3278 };
Mike Stump11289f42009-09-09 15:08:12 +00003279
Douglas Gregor91f84212008-12-11 16:49:14 +00003280 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003281 FieldDecl *Field = FieldDecl::Create(*this,
3282 ObjCFastEnumerationStateTypeDecl,
3283 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003284 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003285 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003286 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003287 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003288 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003289 }
Mike Stump11289f42009-09-09 15:08:12 +00003290
Douglas Gregord5058122010-02-11 01:19:42 +00003291 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003292 }
Mike Stump11289f42009-09-09 15:08:12 +00003293
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003294 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3295}
3296
Jay Foad39c79802011-01-12 09:06:06 +00003297QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003298 if (BlockDescriptorType)
3299 return getTagDeclType(BlockDescriptorType);
3300
3301 RecordDecl *T;
3302 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003303 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003304 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003305 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003306
3307 QualType FieldTypes[] = {
3308 UnsignedLongTy,
3309 UnsignedLongTy,
3310 };
3311
3312 const char *FieldNames[] = {
3313 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003314 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003315 };
3316
3317 for (size_t i = 0; i < 2; ++i) {
3318 FieldDecl *Field = FieldDecl::Create(*this,
3319 T,
3320 SourceLocation(),
3321 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003322 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003323 /*BitWidth=*/0,
3324 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003325 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003326 T->addDecl(Field);
3327 }
3328
Douglas Gregord5058122010-02-11 01:19:42 +00003329 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003330
3331 BlockDescriptorType = T;
3332
3333 return getTagDeclType(BlockDescriptorType);
3334}
3335
3336void ASTContext::setBlockDescriptorType(QualType T) {
3337 const RecordType *Rec = T->getAs<RecordType>();
3338 assert(Rec && "Invalid BlockDescriptorType");
3339 BlockDescriptorType = Rec->getDecl();
3340}
3341
Jay Foad39c79802011-01-12 09:06:06 +00003342QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003343 if (BlockDescriptorExtendedType)
3344 return getTagDeclType(BlockDescriptorExtendedType);
3345
3346 RecordDecl *T;
3347 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003348 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003349 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003350 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003351
3352 QualType FieldTypes[] = {
3353 UnsignedLongTy,
3354 UnsignedLongTy,
3355 getPointerType(VoidPtrTy),
3356 getPointerType(VoidPtrTy)
3357 };
3358
3359 const char *FieldNames[] = {
3360 "reserved",
3361 "Size",
3362 "CopyFuncPtr",
3363 "DestroyFuncPtr"
3364 };
3365
3366 for (size_t i = 0; i < 4; ++i) {
3367 FieldDecl *Field = FieldDecl::Create(*this,
3368 T,
3369 SourceLocation(),
3370 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003371 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003372 /*BitWidth=*/0,
3373 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003374 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003375 T->addDecl(Field);
3376 }
3377
Douglas Gregord5058122010-02-11 01:19:42 +00003378 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003379
3380 BlockDescriptorExtendedType = T;
3381
3382 return getTagDeclType(BlockDescriptorExtendedType);
3383}
3384
3385void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3386 const RecordType *Rec = T->getAs<RecordType>();
3387 assert(Rec && "Invalid BlockDescriptorType");
3388 BlockDescriptorExtendedType = Rec->getDecl();
3389}
3390
Jay Foad39c79802011-01-12 09:06:06 +00003391bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003392 if (Ty->isBlockPointerType())
3393 return true;
3394 if (isObjCNSObjectType(Ty))
3395 return true;
3396 if (Ty->isObjCObjectPointerType())
3397 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003398 if (getLangOptions().CPlusPlus) {
3399 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3400 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3401 return RD->hasConstCopyConstructor(*this);
3402
3403 }
3404 }
Mike Stump94967902009-10-21 18:16:27 +00003405 return false;
3406}
3407
Jay Foad39c79802011-01-12 09:06:06 +00003408QualType
3409ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003410 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003411 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003412 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003413 // unsigned int __flags;
3414 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003415 // void *__copy_helper; // as needed
3416 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003417 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003418 // } *
3419
Mike Stump94967902009-10-21 18:16:27 +00003420 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3421
3422 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003423 llvm::SmallString<36> Name;
3424 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3425 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003426 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003427 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003428 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003429 T->startDefinition();
3430 QualType Int32Ty = IntTy;
3431 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3432 QualType FieldTypes[] = {
3433 getPointerType(VoidPtrTy),
3434 getPointerType(getTagDeclType(T)),
3435 Int32Ty,
3436 Int32Ty,
3437 getPointerType(VoidPtrTy),
3438 getPointerType(VoidPtrTy),
3439 Ty
3440 };
3441
Daniel Dunbar56df9772010-08-17 22:39:59 +00003442 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003443 "__isa",
3444 "__forwarding",
3445 "__flags",
3446 "__size",
3447 "__copy_helper",
3448 "__destroy_helper",
3449 DeclName,
3450 };
3451
3452 for (size_t i = 0; i < 7; ++i) {
3453 if (!HasCopyAndDispose && i >=4 && i <= 5)
3454 continue;
3455 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3456 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003457 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003458 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003459 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003460 T->addDecl(Field);
3461 }
3462
Douglas Gregord5058122010-02-11 01:19:42 +00003463 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003464
3465 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003466}
3467
3468
3469QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003470 bool BlockHasCopyDispose,
Jay Foad39c79802011-01-12 09:06:06 +00003471 llvm::SmallVectorImpl<const Expr *> &Layout) const {
John McCall87fe5d52010-05-20 01:18:31 +00003472
Mike Stumpd0153282009-10-20 02:12:22 +00003473 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003474 llvm::SmallString<36> Name;
3475 llvm::raw_svector_ostream(Name) << "__block_literal_"
3476 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003477 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003478 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003479 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003480 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003481 QualType FieldTypes[] = {
3482 getPointerType(VoidPtrTy),
3483 IntTy,
3484 IntTy,
3485 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003486 (BlockHasCopyDispose ?
3487 getPointerType(getBlockDescriptorExtendedType()) :
3488 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003489 };
3490
3491 const char *FieldNames[] = {
3492 "__isa",
3493 "__flags",
3494 "__reserved",
3495 "__FuncPtr",
3496 "__descriptor"
3497 };
3498
3499 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003500 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003501 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003502 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003503 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003504 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003505 T->addDecl(Field);
3506 }
3507
John McCall87fe5d52010-05-20 01:18:31 +00003508 for (unsigned i = 0; i < Layout.size(); ++i) {
3509 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003510
John McCall87fe5d52010-05-20 01:18:31 +00003511 QualType FieldType = E->getType();
3512 IdentifierInfo *FieldName = 0;
3513 if (isa<CXXThisExpr>(E)) {
3514 FieldName = &Idents.get("this");
3515 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3516 const ValueDecl *D = BDRE->getDecl();
3517 FieldName = D->getIdentifier();
3518 if (BDRE->isByRef())
Daniel Dunbar56df9772010-08-17 22:39:59 +00003519 FieldType = BuildByRefType(D->getName(), FieldType);
John McCall87fe5d52010-05-20 01:18:31 +00003520 } else {
3521 // Padding.
3522 assert(isa<ConstantArrayType>(FieldType) &&
3523 isa<DeclRefExpr>(E) &&
3524 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3525 "doesn't match characteristics of padding decl");
3526 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003527
3528 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003529 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003530 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003531 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003532 T->addDecl(Field);
3533 }
3534
Douglas Gregord5058122010-02-11 01:19:42 +00003535 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003536
3537 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003538}
3539
Douglas Gregor512b0772009-04-23 22:29:11 +00003540void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003541 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003542 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3543 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3544}
3545
Anders Carlsson18acd442007-10-29 06:33:42 +00003546// This returns true if a type has been typedefed to BOOL:
3547// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003548static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003549 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003550 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3551 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003552
Anders Carlssond8499822007-10-29 05:01:08 +00003553 return false;
3554}
3555
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003556/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003557/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003558CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003559 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003560
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003561 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003562 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003563 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003564 // Treat arrays as pointers, since that's how they're passed in.
3565 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003566 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003567 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003568}
3569
3570static inline
3571std::string charUnitsToString(const CharUnits &CU) {
3572 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003573}
3574
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003575/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003576/// declaration.
3577void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
Jay Foad39c79802011-01-12 09:06:06 +00003578 std::string& S) const {
David Chisnall950a9512009-11-17 19:33:30 +00003579 const BlockDecl *Decl = Expr->getBlockDecl();
3580 QualType BlockTy =
3581 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3582 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003583 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003584 // Compute size of all parameters.
3585 // Start with computing size of a pointer in number of bytes.
3586 // FIXME: There might(should) be a better way of doing this computation!
3587 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003588 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3589 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003590 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003591 E = Decl->param_end(); PI != E; ++PI) {
3592 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003593 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003594 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003595 ParmOffset += sz;
3596 }
3597 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003598 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003599 // Block pointer and offset.
3600 S += "@?0";
3601 ParmOffset = PtrSize;
3602
3603 // Argument types.
3604 ParmOffset = PtrSize;
3605 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3606 Decl->param_end(); PI != E; ++PI) {
3607 ParmVarDecl *PVDecl = *PI;
3608 QualType PType = PVDecl->getOriginalType();
3609 if (const ArrayType *AT =
3610 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3611 // Use array's original type only if it has known number of
3612 // elements.
3613 if (!isa<ConstantArrayType>(AT))
3614 PType = PVDecl->getType();
3615 } else if (PType->isFunctionType())
3616 PType = PVDecl->getType();
3617 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003618 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003619 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003620 }
3621}
3622
David Chisnall50e4eba2010-12-30 14:05:53 +00003623void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3624 std::string& S) {
3625 // Encode result type.
3626 getObjCEncodingForType(Decl->getResultType(), S);
3627 CharUnits ParmOffset;
3628 // Compute size of all parameters.
3629 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3630 E = Decl->param_end(); PI != E; ++PI) {
3631 QualType PType = (*PI)->getType();
3632 CharUnits sz = getObjCEncodingTypeSize(PType);
3633 assert (sz.isPositive() &&
3634 "getObjCEncodingForMethodDecl - Incomplete param type");
3635 ParmOffset += sz;
3636 }
3637 S += charUnitsToString(ParmOffset);
3638 ParmOffset = CharUnits::Zero();
3639
3640 // Argument types.
3641 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3642 E = Decl->param_end(); PI != E; ++PI) {
3643 ParmVarDecl *PVDecl = *PI;
3644 QualType PType = PVDecl->getOriginalType();
3645 if (const ArrayType *AT =
3646 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3647 // Use array's original type only if it has known number of
3648 // elements.
3649 if (!isa<ConstantArrayType>(AT))
3650 PType = PVDecl->getType();
3651 } else if (PType->isFunctionType())
3652 PType = PVDecl->getType();
3653 getObjCEncodingForType(PType, S);
3654 S += charUnitsToString(ParmOffset);
3655 ParmOffset += getObjCEncodingTypeSize(PType);
3656 }
3657}
3658
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003659/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003660/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003661void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003662 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003663 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003664 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003665 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003666 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003667 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003668 // Compute size of all parameters.
3669 // Start with computing size of a pointer in number of bytes.
3670 // FIXME: There might(should) be a better way of doing this computation!
3671 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003672 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003673 // The first two arguments (self and _cmd) are pointers; account for
3674 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003675 CharUnits 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 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003679 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003680 assert (sz.isPositive() &&
3681 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003682 ParmOffset += sz;
3683 }
Ken Dyck40775002010-01-11 17:06:35 +00003684 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003685 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003686 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003687
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003688 // Argument types.
3689 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003690 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003691 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003692 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003693 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003694 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003695 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3696 // Use array's original type only if it has known number of
3697 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003698 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003699 PType = PVDecl->getType();
3700 } else if (PType->isFunctionType())
3701 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003702 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003703 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003704 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003705 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003706 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003707 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003708 }
3709}
3710
Daniel Dunbar4932b362008-08-28 04:38:10 +00003711/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003712/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003713/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3714/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003715/// Property attributes are stored as a comma-delimited C string. The simple
3716/// attributes readonly and bycopy are encoded as single characters. The
3717/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3718/// encoded as single characters, followed by an identifier. Property types
3719/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003720/// these attributes are defined by the following enumeration:
3721/// @code
3722/// enum PropertyAttributes {
3723/// kPropertyReadOnly = 'R', // property is read-only.
3724/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3725/// kPropertyByref = '&', // property is a reference to the value last assigned
3726/// kPropertyDynamic = 'D', // property is dynamic
3727/// kPropertyGetter = 'G', // followed by getter selector name
3728/// kPropertySetter = 'S', // followed by setter selector name
3729/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3730/// kPropertyType = 't' // followed by old-style type encoding.
3731/// kPropertyWeak = 'W' // 'weak' property
3732/// kPropertyStrong = 'P' // property GC'able
3733/// kPropertyNonAtomic = 'N' // property non-atomic
3734/// };
3735/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003736void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003737 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003738 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003739 // Collect information from the property implementation decl(s).
3740 bool Dynamic = false;
3741 ObjCPropertyImplDecl *SynthesizePID = 0;
3742
3743 // FIXME: Duplicated code due to poor abstraction.
3744 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003745 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003746 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3747 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003748 i = CID->propimpl_begin(), e = CID->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 }
3758 }
3759 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003760 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003761 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003762 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003763 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003764 ObjCPropertyImplDecl *PID = *i;
3765 if (PID->getPropertyDecl() == PD) {
3766 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3767 Dynamic = true;
3768 } else {
3769 SynthesizePID = PID;
3770 }
3771 }
Mike Stump11289f42009-09-09 15:08:12 +00003772 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003773 }
3774 }
3775
3776 // FIXME: This is not very efficient.
3777 S = "T";
3778
3779 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003780 // GCC has some special rules regarding encoding of properties which
3781 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003782 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003783 true /* outermost type */,
3784 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003785
3786 if (PD->isReadOnly()) {
3787 S += ",R";
3788 } else {
3789 switch (PD->getSetterKind()) {
3790 case ObjCPropertyDecl::Assign: break;
3791 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003792 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003793 }
3794 }
3795
3796 // It really isn't clear at all what this means, since properties
3797 // are "dynamic by default".
3798 if (Dynamic)
3799 S += ",D";
3800
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003801 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3802 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003803
Daniel Dunbar4932b362008-08-28 04:38:10 +00003804 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3805 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003806 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003807 }
3808
3809 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3810 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003811 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003812 }
3813
3814 if (SynthesizePID) {
3815 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3816 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003817 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003818 }
3819
3820 // FIXME: OBJCGC: weak & strong
3821}
3822
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003823/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003824/// Another legacy compatibility encoding: 32-bit longs are encoded as
3825/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003826/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3827///
3828void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003829 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003830 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00003831 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003832 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003833 else
Jay Foad39c79802011-01-12 09:06:06 +00003834 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003835 PointeeTy = IntTy;
3836 }
3837 }
3838}
3839
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003840void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00003841 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003842 // We follow the behavior of gcc, expanding structures which are
3843 // directly pointed to, and expanding embedded structures. Note that
3844 // these rules are sufficient to prevent recursive encoding of the
3845 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003846 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003847 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003848}
3849
David Chisnallb190a2c2010-06-04 01:10:52 +00003850static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3851 switch (T->getAs<BuiltinType>()->getKind()) {
3852 default: assert(0 && "Unhandled builtin type kind");
3853 case BuiltinType::Void: return 'v';
3854 case BuiltinType::Bool: return 'B';
3855 case BuiltinType::Char_U:
3856 case BuiltinType::UChar: return 'C';
3857 case BuiltinType::UShort: return 'S';
3858 case BuiltinType::UInt: return 'I';
3859 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00003860 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003861 case BuiltinType::UInt128: return 'T';
3862 case BuiltinType::ULongLong: return 'Q';
3863 case BuiltinType::Char_S:
3864 case BuiltinType::SChar: return 'c';
3865 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00003866 case BuiltinType::WChar_S:
3867 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00003868 case BuiltinType::Int: return 'i';
3869 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00003870 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003871 case BuiltinType::LongLong: return 'q';
3872 case BuiltinType::Int128: return 't';
3873 case BuiltinType::Float: return 'f';
3874 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00003875 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00003876 }
3877}
3878
Jay Foad39c79802011-01-12 09:06:06 +00003879static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003880 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003881 const Expr *E = FD->getBitWidth();
3882 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003883 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003884 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3885 // The GNU runtime requires more information; bitfields are encoded as b,
3886 // then the offset (in bits) of the first element, then the type of the
3887 // bitfield, then the size in bits. For example, in this structure:
3888 //
3889 // struct
3890 // {
3891 // int integer;
3892 // int flags:2;
3893 // };
3894 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3895 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3896 // information is not especially sensible, but we're stuck with it for
3897 // compatibility with GCC, although providing it breaks anything that
3898 // actually uses runtime introspection and wants to work on both runtimes...
3899 if (!Ctx->getLangOptions().NeXTRuntime) {
3900 const RecordDecl *RD = FD->getParent();
3901 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3902 // FIXME: This same linear search is also used in ExprConstant - it might
3903 // be better if the FieldDecl stored its offset. We'd be increasing the
3904 // size of the object slightly, but saving some time every time it is used.
3905 unsigned i = 0;
3906 for (RecordDecl::field_iterator Field = RD->field_begin(),
3907 FieldEnd = RD->field_end();
3908 Field != FieldEnd; (void)++Field, ++i) {
3909 if (*Field == FD)
3910 break;
3911 }
3912 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00003913 if (T->isEnumeralType())
3914 S += 'i';
3915 else
Jay Foad39c79802011-01-12 09:06:06 +00003916 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00003917 }
3918 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003919 S += llvm::utostr(N);
3920}
3921
Daniel Dunbar07d07852009-10-18 21:17:35 +00003922// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003923void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3924 bool ExpandPointedToStructures,
3925 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003926 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003927 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00003928 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00003929 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003930 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003931 return EncodeBitField(this, S, T, FD);
3932 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003933 return;
3934 }
Mike Stump11289f42009-09-09 15:08:12 +00003935
John McCall9dd450b2009-09-21 23:43:11 +00003936 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003937 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003938 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003939 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003940 return;
3941 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003942
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003943 // encoding for pointer or r3eference types.
3944 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003945 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003946 if (PT->isObjCSelType()) {
3947 S += ':';
3948 return;
3949 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003950 PointeeTy = PT->getPointeeType();
3951 }
3952 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3953 PointeeTy = RT->getPointeeType();
3954 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003955 bool isReadOnly = false;
3956 // For historical/compatibility reasons, the read-only qualifier of the
3957 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3958 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003959 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003960 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003961 if (OutermostType && T.isConstQualified()) {
3962 isReadOnly = true;
3963 S += 'r';
3964 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003965 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003966 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003967 while (P->getAs<PointerType>())
3968 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003969 if (P.isConstQualified()) {
3970 isReadOnly = true;
3971 S += 'r';
3972 }
3973 }
3974 if (isReadOnly) {
3975 // Another legacy compatibility encoding. Some ObjC qualifier and type
3976 // combinations need to be rearranged.
3977 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003978 if (llvm::StringRef(S).endswith("nr"))
3979 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003980 }
Mike Stump11289f42009-09-09 15:08:12 +00003981
Anders Carlssond8499822007-10-29 05:01:08 +00003982 if (PointeeTy->isCharType()) {
3983 // char pointer types should be encoded as '*' unless it is a
3984 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003985 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003986 S += '*';
3987 return;
3988 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003989 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003990 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3991 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3992 S += '#';
3993 return;
3994 }
3995 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3996 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3997 S += '@';
3998 return;
3999 }
4000 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004001 }
Anders Carlssond8499822007-10-29 05:01:08 +00004002 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004003 getLegacyIntegralTypeEncoding(PointeeTy);
4004
Mike Stump11289f42009-09-09 15:08:12 +00004005 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004006 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004007 return;
4008 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004009
Chris Lattnere7cabb92009-07-13 00:10:46 +00004010 if (const ArrayType *AT =
4011 // Ignore type qualifiers etc.
4012 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004013 if (isa<IncompleteArrayType>(AT)) {
4014 // Incomplete arrays are encoded as a pointer to the array element.
4015 S += '^';
4016
Mike Stump11289f42009-09-09 15:08:12 +00004017 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004018 false, ExpandStructures, FD);
4019 } else {
4020 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004021
Anders Carlssond05f44b2009-02-22 01:38:57 +00004022 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4023 S += llvm::utostr(CAT->getSize().getZExtValue());
4024 else {
4025 //Variable length arrays are encoded as a regular array with 0 elements.
4026 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4027 S += '0';
4028 }
Mike Stump11289f42009-09-09 15:08:12 +00004029
4030 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004031 false, ExpandStructures, FD);
4032 S += ']';
4033 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004034 return;
4035 }
Mike Stump11289f42009-09-09 15:08:12 +00004036
John McCall9dd450b2009-09-21 23:43:11 +00004037 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004038 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004039 return;
4040 }
Mike Stump11289f42009-09-09 15:08:12 +00004041
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004042 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004043 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004044 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004045 // Anonymous structures print as '?'
4046 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4047 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004048 if (ClassTemplateSpecializationDecl *Spec
4049 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4050 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4051 std::string TemplateArgsStr
4052 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004053 TemplateArgs.data(),
4054 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004055 (*this).PrintingPolicy);
4056
4057 S += TemplateArgsStr;
4058 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004059 } else {
4060 S += '?';
4061 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004062 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004063 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004064 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4065 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004066 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004067 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004068 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004069 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004070 S += '"';
4071 }
Mike Stump11289f42009-09-09 15:08:12 +00004072
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004073 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004074 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004075 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004076 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004077 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004078 QualType qt = Field->getType();
4079 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004080 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004081 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004082 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004083 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004084 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004085 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004086 return;
4087 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004088
Chris Lattnere7cabb92009-07-13 00:10:46 +00004089 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004090 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004091 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004092 else
4093 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004094 return;
4095 }
Mike Stump11289f42009-09-09 15:08:12 +00004096
Chris Lattnere7cabb92009-07-13 00:10:46 +00004097 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004098 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004099 return;
4100 }
Mike Stump11289f42009-09-09 15:08:12 +00004101
John McCall8b07ec22010-05-15 11:32:37 +00004102 // Ignore protocol qualifiers when mangling at this level.
4103 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4104 T = OT->getBaseType();
4105
John McCall8ccfcb52009-09-24 19:53:00 +00004106 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004107 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004108 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004109 S += '{';
4110 const IdentifierInfo *II = OI->getIdentifier();
4111 S += II->getName();
4112 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004113 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4114 DeepCollectObjCIvars(OI, true, Ivars);
4115 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4116 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4117 if (Field->isBitField())
4118 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004119 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004120 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004121 }
4122 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004123 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004124 }
Mike Stump11289f42009-09-09 15:08:12 +00004125
John McCall9dd450b2009-09-21 23:43:11 +00004126 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004127 if (OPT->isObjCIdType()) {
4128 S += '@';
4129 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004130 }
Mike Stump11289f42009-09-09 15:08:12 +00004131
Steve Narofff0c86112009-10-28 22:03:49 +00004132 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4133 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4134 // Since this is a binary compatibility issue, need to consult with runtime
4135 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004136 S += '#';
4137 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004138 }
Mike Stump11289f42009-09-09 15:08:12 +00004139
Chris Lattnere7cabb92009-07-13 00:10:46 +00004140 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004141 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004142 ExpandPointedToStructures,
4143 ExpandStructures, FD);
4144 if (FD || EncodingProperty) {
4145 // Note that we do extended encoding of protocol qualifer list
4146 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004147 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004148 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4149 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004150 S += '<';
4151 S += (*I)->getNameAsString();
4152 S += '>';
4153 }
4154 S += '"';
4155 }
4156 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004157 }
Mike Stump11289f42009-09-09 15:08:12 +00004158
Chris Lattnere7cabb92009-07-13 00:10:46 +00004159 QualType PointeeTy = OPT->getPointeeType();
4160 if (!EncodingProperty &&
4161 isa<TypedefType>(PointeeTy.getTypePtr())) {
4162 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004163 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004164 // {...};
4165 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004166 getObjCEncodingForTypeImpl(PointeeTy, S,
4167 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004168 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004169 return;
4170 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004171
4172 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004173 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004174 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004175 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004176 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4177 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004178 S += '<';
4179 S += (*I)->getNameAsString();
4180 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004181 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004182 S += '"';
4183 }
4184 return;
4185 }
Mike Stump11289f42009-09-09 15:08:12 +00004186
John McCalla9e6e8d2010-05-17 23:56:34 +00004187 // gcc just blithely ignores member pointers.
4188 // TODO: maybe there should be a mangling for these
4189 if (T->getAs<MemberPointerType>())
4190 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004191
4192 if (T->isVectorType()) {
4193 // This matches gcc's encoding, even though technically it is
4194 // insufficient.
4195 // FIXME. We should do a better job than gcc.
4196 return;
4197 }
4198
Chris Lattnere7cabb92009-07-13 00:10:46 +00004199 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004200}
4201
Mike Stump11289f42009-09-09 15:08:12 +00004202void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004203 std::string& S) const {
4204 if (QT & Decl::OBJC_TQ_In)
4205 S += 'n';
4206 if (QT & Decl::OBJC_TQ_Inout)
4207 S += 'N';
4208 if (QT & Decl::OBJC_TQ_Out)
4209 S += 'o';
4210 if (QT & Decl::OBJC_TQ_Bycopy)
4211 S += 'O';
4212 if (QT & Decl::OBJC_TQ_Byref)
4213 S += 'R';
4214 if (QT & Decl::OBJC_TQ_Oneway)
4215 S += 'V';
4216}
4217
Chris Lattnere7cabb92009-07-13 00:10:46 +00004218void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004219 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004220
Anders Carlsson87c149b2007-10-11 01:00:40 +00004221 BuiltinVaListType = T;
4222}
4223
Chris Lattnere7cabb92009-07-13 00:10:46 +00004224void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004225 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004226}
4227
Chris Lattnere7cabb92009-07-13 00:10:46 +00004228void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004229 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004230}
4231
Chris Lattnere7cabb92009-07-13 00:10:46 +00004232void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004233 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004234}
4235
Chris Lattnere7cabb92009-07-13 00:10:46 +00004236void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004237 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004238}
4239
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004240void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004241 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004242 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004243
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004244 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004245}
4246
John McCalld28ae272009-12-02 08:04:21 +00004247/// \brief Retrieve the template name that corresponds to a non-empty
4248/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004249TemplateName
4250ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4251 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004252 unsigned size = End - Begin;
4253 assert(size > 1 && "set is not overloaded!");
4254
4255 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4256 size * sizeof(FunctionTemplateDecl*));
4257 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4258
4259 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004260 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004261 NamedDecl *D = *I;
4262 assert(isa<FunctionTemplateDecl>(D) ||
4263 (isa<UsingShadowDecl>(D) &&
4264 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4265 *Storage++ = D;
4266 }
4267
4268 return TemplateName(OT);
4269}
4270
Douglas Gregordc572a32009-03-30 22:58:21 +00004271/// \brief Retrieve the template name that represents a qualified
4272/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004273TemplateName
4274ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4275 bool TemplateKeyword,
4276 TemplateDecl *Template) const {
Douglas Gregorc42075a2010-02-04 18:10:26 +00004277 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004278 llvm::FoldingSetNodeID ID;
4279 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4280
4281 void *InsertPos = 0;
4282 QualifiedTemplateName *QTN =
4283 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4284 if (!QTN) {
4285 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4286 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4287 }
4288
4289 return TemplateName(QTN);
4290}
4291
4292/// \brief Retrieve the template name that represents a dependent
4293/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004294TemplateName
4295ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4296 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004297 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004298 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004299
4300 llvm::FoldingSetNodeID ID;
4301 DependentTemplateName::Profile(ID, NNS, Name);
4302
4303 void *InsertPos = 0;
4304 DependentTemplateName *QTN =
4305 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4306
4307 if (QTN)
4308 return TemplateName(QTN);
4309
4310 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4311 if (CanonNNS == NNS) {
4312 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4313 } else {
4314 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4315 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004316 DependentTemplateName *CheckQTN =
4317 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4318 assert(!CheckQTN && "Dependent type name canonicalization broken");
4319 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004320 }
4321
4322 DependentTemplateNames.InsertNode(QTN, InsertPos);
4323 return TemplateName(QTN);
4324}
4325
Douglas Gregor71395fa2009-11-04 00:56:37 +00004326/// \brief Retrieve the template name that represents a dependent
4327/// template name such as \c MetaFun::template operator+.
4328TemplateName
4329ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004330 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004331 assert((!NNS || NNS->isDependent()) &&
4332 "Nested name specifier must be dependent");
4333
4334 llvm::FoldingSetNodeID ID;
4335 DependentTemplateName::Profile(ID, NNS, Operator);
4336
4337 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004338 DependentTemplateName *QTN
4339 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004340
4341 if (QTN)
4342 return TemplateName(QTN);
4343
4344 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4345 if (CanonNNS == NNS) {
4346 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4347 } else {
4348 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4349 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004350
4351 DependentTemplateName *CheckQTN
4352 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4353 assert(!CheckQTN && "Dependent template name canonicalization broken");
4354 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004355 }
4356
4357 DependentTemplateNames.InsertNode(QTN, InsertPos);
4358 return TemplateName(QTN);
4359}
4360
Douglas Gregor5590be02011-01-15 06:45:20 +00004361TemplateName
4362ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4363 const TemplateArgument &ArgPack) const {
4364 ASTContext &Self = const_cast<ASTContext &>(*this);
4365 llvm::FoldingSetNodeID ID;
4366 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4367
4368 void *InsertPos = 0;
4369 SubstTemplateTemplateParmPackStorage *Subst
4370 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4371
4372 if (!Subst) {
4373 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4374 ArgPack.pack_size(),
4375 ArgPack.pack_begin());
4376 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4377 }
4378
4379 return TemplateName(Subst);
4380}
4381
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004382/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004383/// TargetInfo, produce the corresponding type. The unsigned @p Type
4384/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004385CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004386 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004387 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004388 case TargetInfo::SignedShort: return ShortTy;
4389 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4390 case TargetInfo::SignedInt: return IntTy;
4391 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4392 case TargetInfo::SignedLong: return LongTy;
4393 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4394 case TargetInfo::SignedLongLong: return LongLongTy;
4395 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4396 }
4397
4398 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004399 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004400}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004401
4402//===----------------------------------------------------------------------===//
4403// Type Predicates.
4404//===----------------------------------------------------------------------===//
4405
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004406/// isObjCNSObjectType - Return true if this is an NSObject object using
4407/// NSObject attribute on a c-style pointer type.
4408/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004409/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004410///
4411bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4412 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4413 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004414 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004415 return true;
4416 }
Mike Stump11289f42009-09-09 15:08:12 +00004417 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004418}
4419
Fariborz Jahanian96207692009-02-18 21:49:28 +00004420/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4421/// garbage collection attribute.
4422///
John McCall553d45a2011-01-12 00:34:59 +00004423Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4424 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4425 return Qualifiers::GCNone;
4426
4427 assert(getLangOptions().ObjC1);
4428 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4429
4430 // Default behaviour under objective-C's gc is for ObjC pointers
4431 // (or pointers to them) be treated as though they were declared
4432 // as __strong.
4433 if (GCAttrs == Qualifiers::GCNone) {
4434 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4435 return Qualifiers::Strong;
4436 else if (Ty->isPointerType())
4437 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4438 } else {
4439 // It's not valid to set GC attributes on anything that isn't a
4440 // pointer.
4441#ifndef NDEBUG
4442 QualType CT = Ty->getCanonicalTypeInternal();
4443 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4444 CT = AT->getElementType();
4445 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4446#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004447 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004448 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004449}
4450
Chris Lattner49af6a42008-04-07 06:51:04 +00004451//===----------------------------------------------------------------------===//
4452// Type Compatibility Testing
4453//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004454
Mike Stump11289f42009-09-09 15:08:12 +00004455/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004456/// compatible.
4457static bool areCompatVectorTypes(const VectorType *LHS,
4458 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004459 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004460 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004461 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004462}
4463
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004464bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4465 QualType SecondVec) {
4466 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4467 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4468
4469 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4470 return true;
4471
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004472 // Treat Neon vector types and most AltiVec vector types as if they are the
4473 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004474 const VectorType *First = FirstVec->getAs<VectorType>();
4475 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004476 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004477 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004478 First->getVectorKind() != VectorType::AltiVecPixel &&
4479 First->getVectorKind() != VectorType::AltiVecBool &&
4480 Second->getVectorKind() != VectorType::AltiVecPixel &&
4481 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004482 return true;
4483
4484 return false;
4485}
4486
Steve Naroff8e6aee52009-07-23 01:01:38 +00004487//===----------------------------------------------------------------------===//
4488// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4489//===----------------------------------------------------------------------===//
4490
4491/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4492/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004493bool
4494ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4495 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004496 if (lProto == rProto)
4497 return true;
4498 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4499 E = rProto->protocol_end(); PI != E; ++PI)
4500 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4501 return true;
4502 return false;
4503}
4504
Steve Naroff8e6aee52009-07-23 01:01:38 +00004505/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4506/// return true if lhs's protocols conform to rhs's protocol; false
4507/// otherwise.
4508bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4509 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4510 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4511 return false;
4512}
4513
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004514/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4515/// Class<p1, ...>.
4516bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4517 QualType rhs) {
4518 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4519 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4520 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4521
4522 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4523 E = lhsQID->qual_end(); I != E; ++I) {
4524 bool match = false;
4525 ObjCProtocolDecl *lhsProto = *I;
4526 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4527 E = rhsOPT->qual_end(); J != E; ++J) {
4528 ObjCProtocolDecl *rhsProto = *J;
4529 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4530 match = true;
4531 break;
4532 }
4533 }
4534 if (!match)
4535 return false;
4536 }
4537 return true;
4538}
4539
Steve Naroff8e6aee52009-07-23 01:01:38 +00004540/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4541/// ObjCQualifiedIDType.
4542bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4543 bool compare) {
4544 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004545 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004546 lhs->isObjCIdType() || lhs->isObjCClassType())
4547 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004548 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004549 rhs->isObjCIdType() || rhs->isObjCClassType())
4550 return true;
4551
4552 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004553 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004554
Steve Naroff8e6aee52009-07-23 01:01:38 +00004555 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004556
Steve Naroff8e6aee52009-07-23 01:01:38 +00004557 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004558 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004559 // make sure we check the class hierarchy.
4560 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4561 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4562 E = lhsQID->qual_end(); I != E; ++I) {
4563 // when comparing an id<P> on lhs with a static type on rhs,
4564 // see if static class implements all of id's protocols, directly or
4565 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004566 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004567 return false;
4568 }
4569 }
4570 // If there are no qualifiers and no interface, we have an 'id'.
4571 return true;
4572 }
Mike Stump11289f42009-09-09 15:08:12 +00004573 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004574 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4575 E = lhsQID->qual_end(); I != E; ++I) {
4576 ObjCProtocolDecl *lhsProto = *I;
4577 bool match = false;
4578
4579 // when comparing an id<P> on lhs with a static type on rhs,
4580 // see if static class implements all of id's protocols, directly or
4581 // through its super class and categories.
4582 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4583 E = rhsOPT->qual_end(); J != E; ++J) {
4584 ObjCProtocolDecl *rhsProto = *J;
4585 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4586 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4587 match = true;
4588 break;
4589 }
4590 }
Mike Stump11289f42009-09-09 15:08:12 +00004591 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004592 // make sure we check the class hierarchy.
4593 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4594 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4595 E = lhsQID->qual_end(); I != E; ++I) {
4596 // when comparing an id<P> on lhs with a static type on rhs,
4597 // see if static class implements all of id's protocols, directly or
4598 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004599 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004600 match = true;
4601 break;
4602 }
4603 }
4604 }
4605 if (!match)
4606 return false;
4607 }
Mike Stump11289f42009-09-09 15:08:12 +00004608
Steve Naroff8e6aee52009-07-23 01:01:38 +00004609 return true;
4610 }
Mike Stump11289f42009-09-09 15:08:12 +00004611
Steve Naroff8e6aee52009-07-23 01:01:38 +00004612 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4613 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4614
Mike Stump11289f42009-09-09 15:08:12 +00004615 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004616 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004617 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004618 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4619 E = lhsOPT->qual_end(); I != E; ++I) {
4620 ObjCProtocolDecl *lhsProto = *I;
4621 bool match = false;
4622
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004623 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004624 // see if static class implements all of id's protocols, directly or
4625 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004626 // First, lhs protocols in the qualifier list must be found, direct
4627 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004628 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4629 E = rhsQID->qual_end(); J != E; ++J) {
4630 ObjCProtocolDecl *rhsProto = *J;
4631 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4632 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4633 match = true;
4634 break;
4635 }
4636 }
4637 if (!match)
4638 return false;
4639 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004640
4641 // Static class's protocols, or its super class or category protocols
4642 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4643 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4644 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4645 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4646 // This is rather dubious but matches gcc's behavior. If lhs has
4647 // no type qualifier and its class has no static protocol(s)
4648 // assume that it is mismatch.
4649 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4650 return false;
4651 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4652 LHSInheritedProtocols.begin(),
4653 E = LHSInheritedProtocols.end(); I != E; ++I) {
4654 bool match = false;
4655 ObjCProtocolDecl *lhsProto = (*I);
4656 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4657 E = rhsQID->qual_end(); J != E; ++J) {
4658 ObjCProtocolDecl *rhsProto = *J;
4659 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4660 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4661 match = true;
4662 break;
4663 }
4664 }
4665 if (!match)
4666 return false;
4667 }
4668 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004669 return true;
4670 }
4671 return false;
4672}
4673
Eli Friedman47f77112008-08-22 00:56:42 +00004674/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004675/// compatible for assignment from RHS to LHS. This handles validation of any
4676/// protocol qualifiers on the LHS or RHS.
4677///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004678bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4679 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004680 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4681 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4682
Steve Naroff1329fa02009-07-15 18:40:39 +00004683 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004684 if (LHS->isObjCUnqualifiedIdOrClass() ||
4685 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004686 return true;
4687
John McCall8b07ec22010-05-15 11:32:37 +00004688 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004689 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4690 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004691 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004692
4693 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4694 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4695 QualType(RHSOPT,0));
4696
John McCall8b07ec22010-05-15 11:32:37 +00004697 // If we have 2 user-defined types, fall into that path.
4698 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004699 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004700
Steve Naroff8e6aee52009-07-23 01:01:38 +00004701 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004702}
4703
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004704/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4705/// for providing type-safty for objective-c pointers used to pass/return
4706/// arguments in block literals. When passed as arguments, passing 'A*' where
4707/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4708/// not OK. For the return type, the opposite is not OK.
4709bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4710 const ObjCObjectPointerType *LHSOPT,
4711 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004712 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004713 return true;
4714
4715 if (LHSOPT->isObjCBuiltinType()) {
4716 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4717 }
4718
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004719 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004720 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4721 QualType(RHSOPT,0),
4722 false);
4723
4724 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4725 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4726 if (LHS && RHS) { // We have 2 user-defined types.
4727 if (LHS != RHS) {
4728 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4729 return false;
4730 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4731 return true;
4732 }
4733 else
4734 return true;
4735 }
4736 return false;
4737}
4738
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004739/// getIntersectionOfProtocols - This routine finds the intersection of set
4740/// of protocols inherited from two distinct objective-c pointer objects.
4741/// It is used to build composite qualifier list of the composite type of
4742/// the conditional expression involving two objective-c pointer objects.
4743static
4744void getIntersectionOfProtocols(ASTContext &Context,
4745 const ObjCObjectPointerType *LHSOPT,
4746 const ObjCObjectPointerType *RHSOPT,
4747 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4748
John McCall8b07ec22010-05-15 11:32:37 +00004749 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4750 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4751 assert(LHS->getInterface() && "LHS must have an interface base");
4752 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004753
4754 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4755 unsigned LHSNumProtocols = LHS->getNumProtocols();
4756 if (LHSNumProtocols > 0)
4757 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4758 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004759 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004760 Context.CollectInheritedProtocols(LHS->getInterface(),
4761 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004762 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4763 LHSInheritedProtocols.end());
4764 }
4765
4766 unsigned RHSNumProtocols = RHS->getNumProtocols();
4767 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004768 ObjCProtocolDecl **RHSProtocols =
4769 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004770 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4771 if (InheritedProtocolSet.count(RHSProtocols[i]))
4772 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4773 }
4774 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004775 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004776 Context.CollectInheritedProtocols(RHS->getInterface(),
4777 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004778 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4779 RHSInheritedProtocols.begin(),
4780 E = RHSInheritedProtocols.end(); I != E; ++I)
4781 if (InheritedProtocolSet.count((*I)))
4782 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004783 }
4784}
4785
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004786/// areCommonBaseCompatible - Returns common base class of the two classes if
4787/// one found. Note that this is O'2 algorithm. But it will be called as the
4788/// last type comparison in a ?-exp of ObjC pointer types before a
4789/// warning is issued. So, its invokation is extremely rare.
4790QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004791 const ObjCObjectPointerType *Lptr,
4792 const ObjCObjectPointerType *Rptr) {
4793 const ObjCObjectType *LHS = Lptr->getObjectType();
4794 const ObjCObjectType *RHS = Rptr->getObjectType();
4795 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4796 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4797 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004798 return QualType();
4799
John McCall8b07ec22010-05-15 11:32:37 +00004800 while ((LDecl = LDecl->getSuperClass())) {
4801 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004802 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004803 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4804 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4805
4806 QualType Result = QualType(LHS, 0);
4807 if (!Protocols.empty())
4808 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4809 Result = getObjCObjectPointerType(Result);
4810 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004811 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004812 }
4813
4814 return QualType();
4815}
4816
John McCall8b07ec22010-05-15 11:32:37 +00004817bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4818 const ObjCObjectType *RHS) {
4819 assert(LHS->getInterface() && "LHS is not an interface type");
4820 assert(RHS->getInterface() && "RHS is not an interface type");
4821
Chris Lattner49af6a42008-04-07 06:51:04 +00004822 // Verify that the base decls are compatible: the RHS must be a subclass of
4823 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004824 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004825 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004826
Chris Lattner49af6a42008-04-07 06:51:04 +00004827 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4828 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004829 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004830 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004831
Chris Lattner49af6a42008-04-07 06:51:04 +00004832 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4833 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004834 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004835 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004836
John McCall8b07ec22010-05-15 11:32:37 +00004837 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4838 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004839 LHSPI != LHSPE; LHSPI++) {
4840 bool RHSImplementsProtocol = false;
4841
4842 // If the RHS doesn't implement the protocol on the left, the types
4843 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004844 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4845 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004846 RHSPI != RHSPE; RHSPI++) {
4847 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004848 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004849 break;
4850 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004851 }
4852 // FIXME: For better diagnostics, consider passing back the protocol name.
4853 if (!RHSImplementsProtocol)
4854 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004855 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004856 // The RHS implements all protocols listed on the LHS.
4857 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004858}
4859
Steve Naroffb7605152009-02-12 17:52:19 +00004860bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4861 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004862 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4863 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004864
Steve Naroff7cae42b2009-07-10 23:34:53 +00004865 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004866 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004867
4868 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4869 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004870}
4871
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004872bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4873 return canAssignObjCInterfaces(
4874 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4875 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4876}
4877
Mike Stump11289f42009-09-09 15:08:12 +00004878/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004879/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004880/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004881/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004882bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4883 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004884 if (getLangOptions().CPlusPlus)
4885 return hasSameType(LHS, RHS);
4886
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004887 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00004888}
4889
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004890bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4891 return !mergeTypes(LHS, RHS, true).isNull();
4892}
4893
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004894/// mergeTransparentUnionType - if T is a transparent union type and a member
4895/// of T is compatible with SubType, return the merged type, else return
4896/// QualType()
4897QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
4898 bool OfBlockPointer,
4899 bool Unqualified) {
4900 if (const RecordType *UT = T->getAsUnionType()) {
4901 RecordDecl *UD = UT->getDecl();
4902 if (UD->hasAttr<TransparentUnionAttr>()) {
4903 for (RecordDecl::field_iterator it = UD->field_begin(),
4904 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00004905 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00004906 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
4907 if (!MT.isNull())
4908 return MT;
4909 }
4910 }
4911 }
4912
4913 return QualType();
4914}
4915
4916/// mergeFunctionArgumentTypes - merge two types which appear as function
4917/// argument types
4918QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
4919 bool OfBlockPointer,
4920 bool Unqualified) {
4921 // GNU extension: two types are compatible if they appear as a function
4922 // argument, one of the types is a transparent union type and the other
4923 // type is compatible with a union member
4924 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
4925 Unqualified);
4926 if (!lmerge.isNull())
4927 return lmerge;
4928
4929 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
4930 Unqualified);
4931 if (!rmerge.isNull())
4932 return rmerge;
4933
4934 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
4935}
4936
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004937QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004938 bool OfBlockPointer,
4939 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00004940 const FunctionType *lbase = lhs->getAs<FunctionType>();
4941 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004942 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4943 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004944 bool allLTypes = true;
4945 bool allRTypes = true;
4946
4947 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004948 QualType retType;
4949 if (OfBlockPointer)
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004950 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4951 Unqualified);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004952 else
John McCall8c6b56f2010-12-15 01:06:38 +00004953 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
4954 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004955 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004956
4957 if (Unqualified)
4958 retType = retType.getUnqualifiedType();
4959
4960 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4961 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4962 if (Unqualified) {
4963 LRetType = LRetType.getUnqualifiedType();
4964 RRetType = RRetType.getUnqualifiedType();
4965 }
4966
4967 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004968 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004969 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004970 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00004971
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004972 // FIXME: double check this
4973 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4974 // rbase->getRegParmAttr() != 0 &&
4975 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004976 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4977 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00004978
Douglas Gregor8c940862010-01-18 17:14:39 +00004979 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00004980 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00004981 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004982
John McCall8c6b56f2010-12-15 01:06:38 +00004983 // Regparm is part of the calling convention.
4984 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
4985 return QualType();
4986
4987 // It's noreturn if either type is.
4988 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
4989 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4990 if (NoReturn != lbaseInfo.getNoReturn())
4991 allLTypes = false;
4992 if (NoReturn != rbaseInfo.getNoReturn())
4993 allRTypes = false;
4994
4995 FunctionType::ExtInfo einfo(NoReturn,
4996 lbaseInfo.getRegParm(),
4997 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00004998
Eli Friedman47f77112008-08-22 00:56:42 +00004999 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005000 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5001 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005002 unsigned lproto_nargs = lproto->getNumArgs();
5003 unsigned rproto_nargs = rproto->getNumArgs();
5004
5005 // Compatible functions must have the same number of arguments
5006 if (lproto_nargs != rproto_nargs)
5007 return QualType();
5008
5009 // Variadic and non-variadic functions aren't compatible
5010 if (lproto->isVariadic() != rproto->isVariadic())
5011 return QualType();
5012
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005013 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5014 return QualType();
5015
Eli Friedman47f77112008-08-22 00:56:42 +00005016 // Check argument compatibility
5017 llvm::SmallVector<QualType, 10> types;
5018 for (unsigned i = 0; i < lproto_nargs; i++) {
5019 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5020 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005021 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5022 OfBlockPointer,
5023 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005024 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005025
5026 if (Unqualified)
5027 argtype = argtype.getUnqualifiedType();
5028
Eli Friedman47f77112008-08-22 00:56:42 +00005029 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005030 if (Unqualified) {
5031 largtype = largtype.getUnqualifiedType();
5032 rargtype = rargtype.getUnqualifiedType();
5033 }
5034
Chris Lattner465fa322008-10-05 17:34:18 +00005035 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5036 allLTypes = false;
5037 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5038 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005039 }
5040 if (allLTypes) return lhs;
5041 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005042
5043 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5044 EPI.ExtInfo = einfo;
5045 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005046 }
5047
5048 if (lproto) allRTypes = false;
5049 if (rproto) allLTypes = false;
5050
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005051 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005052 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005053 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005054 if (proto->isVariadic()) return QualType();
5055 // Check that the types are compatible with the types that
5056 // would result from default argument promotions (C99 6.7.5.3p15).
5057 // The only types actually affected are promotable integer
5058 // types and floats, which would be passed as a different
5059 // type depending on whether the prototype is visible.
5060 unsigned proto_nargs = proto->getNumArgs();
5061 for (unsigned i = 0; i < proto_nargs; ++i) {
5062 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005063
5064 // Look at the promotion type of enum types, since that is the type used
5065 // to pass enum values.
5066 if (const EnumType *Enum = argTy->getAs<EnumType>())
5067 argTy = Enum->getDecl()->getPromotionType();
5068
Eli Friedman47f77112008-08-22 00:56:42 +00005069 if (argTy->isPromotableIntegerType() ||
5070 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5071 return QualType();
5072 }
5073
5074 if (allLTypes) return lhs;
5075 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005076
5077 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5078 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005079 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005080 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005081 }
5082
5083 if (allLTypes) return lhs;
5084 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005085 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005086}
5087
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005088QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005089 bool OfBlockPointer,
5090 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005091 // C++ [expr]: If an expression initially has the type "reference to T", the
5092 // type is adjusted to "T" prior to any further analysis, the expression
5093 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005094 // expression is an lvalue unless the reference is an rvalue reference and
5095 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005096 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5097 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005098
5099 if (Unqualified) {
5100 LHS = LHS.getUnqualifiedType();
5101 RHS = RHS.getUnqualifiedType();
5102 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005103
Eli Friedman47f77112008-08-22 00:56:42 +00005104 QualType LHSCan = getCanonicalType(LHS),
5105 RHSCan = getCanonicalType(RHS);
5106
5107 // If two types are identical, they are compatible.
5108 if (LHSCan == RHSCan)
5109 return LHS;
5110
John McCall8ccfcb52009-09-24 19:53:00 +00005111 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005112 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5113 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005114 if (LQuals != RQuals) {
5115 // If any of these qualifiers are different, we have a type
5116 // mismatch.
5117 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5118 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5119 return QualType();
5120
5121 // Exactly one GC qualifier difference is allowed: __strong is
5122 // okay if the other type has no GC qualifier but is an Objective
5123 // C object pointer (i.e. implicitly strong by default). We fix
5124 // this by pretending that the unqualified type was actually
5125 // qualified __strong.
5126 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5127 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5128 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5129
5130 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5131 return QualType();
5132
5133 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5134 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5135 }
5136 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5137 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5138 }
Eli Friedman47f77112008-08-22 00:56:42 +00005139 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005140 }
5141
5142 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005143
Eli Friedmandcca6332009-06-01 01:22:52 +00005144 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5145 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005146
Chris Lattnerfd652912008-01-14 05:45:46 +00005147 // We want to consider the two function types to be the same for these
5148 // comparisons, just force one to the other.
5149 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5150 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005151
5152 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005153 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5154 LHSClass = Type::ConstantArray;
5155 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5156 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005157
John McCall8b07ec22010-05-15 11:32:37 +00005158 // ObjCInterfaces are just specialized ObjCObjects.
5159 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5160 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5161
Nate Begemance4d7fc2008-04-18 23:10:10 +00005162 // Canonicalize ExtVector -> Vector.
5163 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5164 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005165
Chris Lattner95554662008-04-07 05:43:21 +00005166 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005167 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005168 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005169 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005170 // Compatibility is based on the underlying type, not the promotion
5171 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005172 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005173 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5174 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005175 }
John McCall9dd450b2009-09-21 23:43:11 +00005176 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005177 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5178 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005179 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005180
Eli Friedman47f77112008-08-22 00:56:42 +00005181 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005182 }
Eli Friedman47f77112008-08-22 00:56:42 +00005183
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005184 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005185 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005186#define TYPE(Class, Base)
5187#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005188#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005189#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5190#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5191#include "clang/AST/TypeNodes.def"
5192 assert(false && "Non-canonical and dependent types shouldn't get here");
5193 return QualType();
5194
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005195 case Type::LValueReference:
5196 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005197 case Type::MemberPointer:
5198 assert(false && "C++ should never be in mergeTypes");
5199 return QualType();
5200
John McCall8b07ec22010-05-15 11:32:37 +00005201 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005202 case Type::IncompleteArray:
5203 case Type::VariableArray:
5204 case Type::FunctionProto:
5205 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005206 assert(false && "Types are eliminated above");
5207 return QualType();
5208
Chris Lattnerfd652912008-01-14 05:45:46 +00005209 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005210 {
5211 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005212 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5213 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005214 if (Unqualified) {
5215 LHSPointee = LHSPointee.getUnqualifiedType();
5216 RHSPointee = RHSPointee.getUnqualifiedType();
5217 }
5218 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5219 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005220 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005221 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005222 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005223 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005224 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005225 return getPointerType(ResultType);
5226 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005227 case Type::BlockPointer:
5228 {
5229 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005230 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5231 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005232 if (Unqualified) {
5233 LHSPointee = LHSPointee.getUnqualifiedType();
5234 RHSPointee = RHSPointee.getUnqualifiedType();
5235 }
5236 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5237 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005238 if (ResultType.isNull()) return QualType();
5239 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5240 return LHS;
5241 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5242 return RHS;
5243 return getBlockPointerType(ResultType);
5244 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005245 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005246 {
5247 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5248 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5249 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5250 return QualType();
5251
5252 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5253 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005254 if (Unqualified) {
5255 LHSElem = LHSElem.getUnqualifiedType();
5256 RHSElem = RHSElem.getUnqualifiedType();
5257 }
5258
5259 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005260 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005261 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5262 return LHS;
5263 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5264 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005265 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5266 ArrayType::ArraySizeModifier(), 0);
5267 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5268 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005269 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5270 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005271 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5272 return LHS;
5273 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5274 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005275 if (LVAT) {
5276 // FIXME: This isn't correct! But tricky to implement because
5277 // the array's size has to be the size of LHS, but the type
5278 // has to be different.
5279 return LHS;
5280 }
5281 if (RVAT) {
5282 // FIXME: This isn't correct! But tricky to implement because
5283 // the array's size has to be the size of RHS, but the type
5284 // has to be different.
5285 return RHS;
5286 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005287 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5288 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005289 return getIncompleteArrayType(ResultType,
5290 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005291 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005292 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005293 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005294 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005295 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005296 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005297 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005298 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005299 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005300 case Type::Complex:
5301 // Distinct complex types are incompatible.
5302 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005303 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005304 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005305 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5306 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005307 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005308 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005309 case Type::ObjCObject: {
5310 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005311 // FIXME: This should be type compatibility, e.g. whether
5312 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005313 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5314 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5315 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005316 return LHS;
5317
Eli Friedman47f77112008-08-22 00:56:42 +00005318 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005319 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005320 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005321 if (OfBlockPointer) {
5322 if (canAssignObjCInterfacesInBlockPointer(
5323 LHS->getAs<ObjCObjectPointerType>(),
5324 RHS->getAs<ObjCObjectPointerType>()))
5325 return LHS;
5326 return QualType();
5327 }
John McCall9dd450b2009-09-21 23:43:11 +00005328 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5329 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005330 return LHS;
5331
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005332 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005333 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005334 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005335
5336 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005337}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005338
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005339/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5340/// 'RHS' attributes and returns the merged version; including for function
5341/// return types.
5342QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5343 QualType LHSCan = getCanonicalType(LHS),
5344 RHSCan = getCanonicalType(RHS);
5345 // If two types are identical, they are compatible.
5346 if (LHSCan == RHSCan)
5347 return LHS;
5348 if (RHSCan->isFunctionType()) {
5349 if (!LHSCan->isFunctionType())
5350 return QualType();
5351 QualType OldReturnType =
5352 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5353 QualType NewReturnType =
5354 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5355 QualType ResReturnType =
5356 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5357 if (ResReturnType.isNull())
5358 return QualType();
5359 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5360 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5361 // In either case, use OldReturnType to build the new function type.
5362 const FunctionType *F = LHS->getAs<FunctionType>();
5363 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005364 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5365 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005366 QualType ResultType
5367 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005368 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005369 return ResultType;
5370 }
5371 }
5372 return QualType();
5373 }
5374
5375 // If the qualifiers are different, the types can still be merged.
5376 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5377 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5378 if (LQuals != RQuals) {
5379 // If any of these qualifiers are different, we have a type mismatch.
5380 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5381 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5382 return QualType();
5383
5384 // Exactly one GC qualifier difference is allowed: __strong is
5385 // okay if the other type has no GC qualifier but is an Objective
5386 // C object pointer (i.e. implicitly strong by default). We fix
5387 // this by pretending that the unqualified type was actually
5388 // qualified __strong.
5389 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5390 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5391 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5392
5393 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5394 return QualType();
5395
5396 if (GC_L == Qualifiers::Strong)
5397 return LHS;
5398 if (GC_R == Qualifiers::Strong)
5399 return RHS;
5400 return QualType();
5401 }
5402
5403 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5404 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5405 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5406 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5407 if (ResQT == LHSBaseQT)
5408 return LHS;
5409 if (ResQT == RHSBaseQT)
5410 return RHS;
5411 }
5412 return QualType();
5413}
5414
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005415//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005416// Integer Predicates
5417//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005418
Jay Foad39c79802011-01-12 09:06:06 +00005419unsigned ASTContext::getIntWidth(QualType T) const {
John McCall56774992009-12-09 09:09:27 +00005420 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005421 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005422 if (T->isBooleanType())
5423 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005424 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005425 return (unsigned)getTypeSize(T);
5426}
5427
5428QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005429 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005430
5431 // Turn <4 x signed int> -> <4 x unsigned int>
5432 if (const VectorType *VTy = T->getAs<VectorType>())
5433 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005434 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005435
5436 // For enums, we return the unsigned version of the base type.
5437 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005438 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005439
5440 const BuiltinType *BTy = T->getAs<BuiltinType>();
5441 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005442 switch (BTy->getKind()) {
5443 case BuiltinType::Char_S:
5444 case BuiltinType::SChar:
5445 return UnsignedCharTy;
5446 case BuiltinType::Short:
5447 return UnsignedShortTy;
5448 case BuiltinType::Int:
5449 return UnsignedIntTy;
5450 case BuiltinType::Long:
5451 return UnsignedLongTy;
5452 case BuiltinType::LongLong:
5453 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005454 case BuiltinType::Int128:
5455 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005456 default:
5457 assert(0 && "Unexpected signed integer type");
5458 return QualType();
5459 }
5460}
5461
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005462ExternalASTSource::~ExternalASTSource() { }
5463
5464void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00005465
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005466ASTMutationListener::~ASTMutationListener() { }
5467
Chris Lattnerecd79c62009-06-14 00:45:47 +00005468
5469//===----------------------------------------------------------------------===//
5470// Builtin Type Computation
5471//===----------------------------------------------------------------------===//
5472
5473/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005474/// pointer over the consumed characters. This returns the resultant type. If
5475/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5476/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5477/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005478///
5479/// RequiresICE is filled in on return to indicate whether the value is required
5480/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005481static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005482 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005483 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005484 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005485 // Modifiers.
5486 int HowLong = 0;
5487 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005488 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005489
Chris Lattnerdc226c22010-10-01 22:42:38 +00005490 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005491 bool Done = false;
5492 while (!Done) {
5493 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005494 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005495 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005496 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005497 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005498 case 'S':
5499 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5500 assert(!Signed && "Can't use 'S' modifier multiple times!");
5501 Signed = true;
5502 break;
5503 case 'U':
5504 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5505 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5506 Unsigned = true;
5507 break;
5508 case 'L':
5509 assert(HowLong <= 2 && "Can't have LLLL modifier");
5510 ++HowLong;
5511 break;
5512 }
5513 }
5514
5515 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005516
Chris Lattnerecd79c62009-06-14 00:45:47 +00005517 // Read the base type.
5518 switch (*Str++) {
5519 default: assert(0 && "Unknown builtin type letter!");
5520 case 'v':
5521 assert(HowLong == 0 && !Signed && !Unsigned &&
5522 "Bad modifiers used with 'v'!");
5523 Type = Context.VoidTy;
5524 break;
5525 case 'f':
5526 assert(HowLong == 0 && !Signed && !Unsigned &&
5527 "Bad modifiers used with 'f'!");
5528 Type = Context.FloatTy;
5529 break;
5530 case 'd':
5531 assert(HowLong < 2 && !Signed && !Unsigned &&
5532 "Bad modifiers used with 'd'!");
5533 if (HowLong)
5534 Type = Context.LongDoubleTy;
5535 else
5536 Type = Context.DoubleTy;
5537 break;
5538 case 's':
5539 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5540 if (Unsigned)
5541 Type = Context.UnsignedShortTy;
5542 else
5543 Type = Context.ShortTy;
5544 break;
5545 case 'i':
5546 if (HowLong == 3)
5547 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5548 else if (HowLong == 2)
5549 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5550 else if (HowLong == 1)
5551 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5552 else
5553 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5554 break;
5555 case 'c':
5556 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5557 if (Signed)
5558 Type = Context.SignedCharTy;
5559 else if (Unsigned)
5560 Type = Context.UnsignedCharTy;
5561 else
5562 Type = Context.CharTy;
5563 break;
5564 case 'b': // boolean
5565 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5566 Type = Context.BoolTy;
5567 break;
5568 case 'z': // size_t.
5569 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5570 Type = Context.getSizeType();
5571 break;
5572 case 'F':
5573 Type = Context.getCFConstantStringType();
5574 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005575 case 'G':
5576 Type = Context.getObjCIdType();
5577 break;
5578 case 'H':
5579 Type = Context.getObjCSelType();
5580 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005581 case 'a':
5582 Type = Context.getBuiltinVaListType();
5583 assert(!Type.isNull() && "builtin va list type not initialized!");
5584 break;
5585 case 'A':
5586 // This is a "reference" to a va_list; however, what exactly
5587 // this means depends on how va_list is defined. There are two
5588 // different kinds of va_list: ones passed by value, and ones
5589 // passed by reference. An example of a by-value va_list is
5590 // x86, where va_list is a char*. An example of by-ref va_list
5591 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5592 // we want this argument to be a char*&; for x86-64, we want
5593 // it to be a __va_list_tag*.
5594 Type = Context.getBuiltinVaListType();
5595 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005596 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005597 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005598 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005599 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005600 break;
5601 case 'V': {
5602 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005603 unsigned NumElements = strtoul(Str, &End, 10);
5604 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005605 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005606
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005607 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5608 RequiresICE, false);
5609 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005610
5611 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005612 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005613 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005614 break;
5615 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005616 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005617 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5618 false);
5619 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005620 Type = Context.getComplexType(ElementType);
5621 break;
5622 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005623 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005624 Type = Context.getFILEType();
5625 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005626 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005627 return QualType();
5628 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005629 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005630 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005631 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005632 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005633 else
5634 Type = Context.getjmp_bufType();
5635
Mike Stump2adb4da2009-07-28 23:47:15 +00005636 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005637 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005638 return QualType();
5639 }
5640 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005641 }
Mike Stump11289f42009-09-09 15:08:12 +00005642
Chris Lattnerdc226c22010-10-01 22:42:38 +00005643 // If there are modifiers and if we're allowed to parse them, go for it.
5644 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005645 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005646 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005647 default: Done = true; --Str; break;
5648 case '*':
5649 case '&': {
5650 // Both pointers and references can have their pointee types
5651 // qualified with an address space.
5652 char *End;
5653 unsigned AddrSpace = strtoul(Str, &End, 10);
5654 if (End != Str && AddrSpace != 0) {
5655 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5656 Str = End;
5657 }
5658 if (c == '*')
5659 Type = Context.getPointerType(Type);
5660 else
5661 Type = Context.getLValueReferenceType(Type);
5662 break;
5663 }
5664 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5665 case 'C':
5666 Type = Type.withConst();
5667 break;
5668 case 'D':
5669 Type = Context.getVolatileType(Type);
5670 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005671 }
5672 }
Chris Lattner84733392010-10-01 07:13:18 +00005673
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005674 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005675 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005676
Chris Lattnerecd79c62009-06-14 00:45:47 +00005677 return Type;
5678}
5679
5680/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005681QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005682 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005683 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005684 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005685
Chris Lattnerecd79c62009-06-14 00:45:47 +00005686 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005687
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005688 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005689 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005690 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5691 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005692 if (Error != GE_None)
5693 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005694
5695 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5696
Chris Lattnerecd79c62009-06-14 00:45:47 +00005697 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005698 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005699 if (Error != GE_None)
5700 return QualType();
5701
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005702 // If this argument is required to be an IntegerConstantExpression and the
5703 // caller cares, fill in the bitmask we return.
5704 if (RequiresICE && IntegerConstantArgs)
5705 *IntegerConstantArgs |= 1 << ArgTypes.size();
5706
Chris Lattnerecd79c62009-06-14 00:45:47 +00005707 // Do array -> pointer decay. The builtin should use the decayed type.
5708 if (Ty->isArrayType())
5709 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005710
Chris Lattnerecd79c62009-06-14 00:45:47 +00005711 ArgTypes.push_back(Ty);
5712 }
5713
5714 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5715 "'.' should only occur at end of builtin type list!");
5716
John McCall991eb4b2010-12-21 00:44:39 +00005717 FunctionType::ExtInfo EI;
5718 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5719
5720 bool Variadic = (TypeStr[0] == '.');
5721
5722 // We really shouldn't be making a no-proto type here, especially in C++.
5723 if (ArgTypes.empty() && Variadic)
5724 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005725
John McCalldb40c7f2010-12-14 08:05:40 +00005726 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005727 EPI.ExtInfo = EI;
5728 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00005729
5730 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005731}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005732
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005733GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5734 GVALinkage External = GVA_StrongExternal;
5735
5736 Linkage L = FD->getLinkage();
5737 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5738 FD->getType()->getLinkage() == UniqueExternalLinkage)
5739 L = UniqueExternalLinkage;
5740
5741 switch (L) {
5742 case NoLinkage:
5743 case InternalLinkage:
5744 case UniqueExternalLinkage:
5745 return GVA_Internal;
5746
5747 case ExternalLinkage:
5748 switch (FD->getTemplateSpecializationKind()) {
5749 case TSK_Undeclared:
5750 case TSK_ExplicitSpecialization:
5751 External = GVA_StrongExternal;
5752 break;
5753
5754 case TSK_ExplicitInstantiationDefinition:
5755 return GVA_ExplicitTemplateInstantiation;
5756
5757 case TSK_ExplicitInstantiationDeclaration:
5758 case TSK_ImplicitInstantiation:
5759 External = GVA_TemplateInstantiation;
5760 break;
5761 }
5762 }
5763
5764 if (!FD->isInlined())
5765 return External;
5766
5767 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5768 // GNU or C99 inline semantics. Determine whether this symbol should be
5769 // externally visible.
5770 if (FD->isInlineDefinitionExternallyVisible())
5771 return External;
5772
5773 // C99 inline semantics, where the symbol is not externally visible.
5774 return GVA_C99Inline;
5775 }
5776
5777 // C++0x [temp.explicit]p9:
5778 // [ Note: The intent is that an inline function that is the subject of
5779 // an explicit instantiation declaration will still be implicitly
5780 // instantiated when used so that the body can be considered for
5781 // inlining, but that no out-of-line copy of the inline function would be
5782 // generated in the translation unit. -- end note ]
5783 if (FD->getTemplateSpecializationKind()
5784 == TSK_ExplicitInstantiationDeclaration)
5785 return GVA_C99Inline;
5786
5787 return GVA_CXXInline;
5788}
5789
5790GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5791 // If this is a static data member, compute the kind of template
5792 // specialization. Otherwise, this variable is not part of a
5793 // template.
5794 TemplateSpecializationKind TSK = TSK_Undeclared;
5795 if (VD->isStaticDataMember())
5796 TSK = VD->getTemplateSpecializationKind();
5797
5798 Linkage L = VD->getLinkage();
5799 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5800 VD->getType()->getLinkage() == UniqueExternalLinkage)
5801 L = UniqueExternalLinkage;
5802
5803 switch (L) {
5804 case NoLinkage:
5805 case InternalLinkage:
5806 case UniqueExternalLinkage:
5807 return GVA_Internal;
5808
5809 case ExternalLinkage:
5810 switch (TSK) {
5811 case TSK_Undeclared:
5812 case TSK_ExplicitSpecialization:
5813 return GVA_StrongExternal;
5814
5815 case TSK_ExplicitInstantiationDeclaration:
5816 llvm_unreachable("Variable should not be instantiated");
5817 // Fall through to treat this like any other instantiation.
5818
5819 case TSK_ExplicitInstantiationDefinition:
5820 return GVA_ExplicitTemplateInstantiation;
5821
5822 case TSK_ImplicitInstantiation:
5823 return GVA_TemplateInstantiation;
5824 }
5825 }
5826
5827 return GVA_StrongExternal;
5828}
5829
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005830bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005831 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5832 if (!VD->isFileVarDecl())
5833 return false;
5834 } else if (!isa<FunctionDecl>(D))
5835 return false;
5836
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005837 // Weak references don't produce any output by themselves.
5838 if (D->hasAttr<WeakRefAttr>())
5839 return false;
5840
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005841 // Aliases and used decls are required.
5842 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5843 return true;
5844
5845 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5846 // Forward declarations aren't required.
5847 if (!FD->isThisDeclarationADefinition())
5848 return false;
5849
5850 // Constructors and destructors are required.
5851 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5852 return true;
5853
5854 // The key function for a class is required.
5855 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5856 const CXXRecordDecl *RD = MD->getParent();
5857 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5858 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5859 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5860 return true;
5861 }
5862 }
5863
5864 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5865
5866 // static, static inline, always_inline, and extern inline functions can
5867 // always be deferred. Normal inline functions can be deferred in C99/C++.
5868 // Implicit template instantiations can also be deferred in C++.
5869 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5870 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5871 return false;
5872 return true;
5873 }
5874
5875 const VarDecl *VD = cast<VarDecl>(D);
5876 assert(VD->isFileVarDecl() && "Expected file scoped var");
5877
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005878 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5879 return false;
5880
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005881 // Structs that have non-trivial constructors or destructors are required.
5882
5883 // FIXME: Handle references.
5884 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5885 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00005886 if (RD->hasDefinition() &&
5887 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005888 return true;
5889 }
5890 }
5891
5892 GVALinkage L = GetGVALinkageForVariable(VD);
5893 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5894 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5895 return false;
5896 }
5897
5898 return true;
5899}
Charles Davis53c59df2010-08-16 03:33:14 +00005900
Charles Davis99202b32010-11-09 18:04:24 +00005901CallingConv ASTContext::getDefaultMethodCallConv() {
5902 // Pass through to the C++ ABI object
5903 return ABI->getDefaultMethodCallConv();
5904}
5905
Jay Foad39c79802011-01-12 09:06:06 +00005906bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00005907 // Pass through to the C++ ABI object
5908 return ABI->isNearlyEmpty(RD);
5909}
5910
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00005911MangleContext *ASTContext::createMangleContext() {
5912 switch (Target.getCXXABI()) {
5913 case CXXABI_ARM:
5914 case CXXABI_Itanium:
5915 return createItaniumMangleContext(*this, getDiagnostics());
5916 case CXXABI_Microsoft:
5917 return createMicrosoftMangleContext(*this, getDiagnostics());
5918 }
5919 assert(0 && "Unsupported ABI");
5920 return 0;
5921}
5922
Charles Davis53c59df2010-08-16 03:33:14 +00005923CXXABI::~CXXABI() {}