blob: 4b4c56502b2c652d6ec812a815536ad746c5aba0 [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"
Anders Carlsson15b73de2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000025#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000026#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000027#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000028#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000029#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000030#include "llvm/Support/raw_ostream.h"
Charles Davis53c59df2010-08-16 03:33:14 +000031#include "CXXABI.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000032
Chris Lattnerddc135e2006-11-10 06:34:16 +000033using namespace clang;
34
Douglas Gregor9672f922010-07-03 00:47:00 +000035unsigned ASTContext::NumImplicitDefaultConstructors;
36unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000037unsigned ASTContext::NumImplicitCopyConstructors;
38unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000039unsigned ASTContext::NumImplicitCopyAssignmentOperators;
40unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000041unsigned ASTContext::NumImplicitDestructors;
42unsigned ASTContext::NumImplicitDestructorsDeclared;
43
Steve Naroff0af91202007-04-27 21:51:21 +000044enum FloatingRank {
45 FloatRank, DoubleRank, LongDoubleRank
46};
47
Douglas Gregor7dbfb462010-06-16 21:09:37 +000048void
49ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
50 TemplateTemplateParmDecl *Parm) {
51 ID.AddInteger(Parm->getDepth());
52 ID.AddInteger(Parm->getPosition());
53 // FIXME: Parameter pack
54
55 TemplateParameterList *Params = Parm->getTemplateParameters();
56 ID.AddInteger(Params->size());
57 for (TemplateParameterList::const_iterator P = Params->begin(),
58 PEnd = Params->end();
59 P != PEnd; ++P) {
60 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
61 ID.AddInteger(0);
62 ID.AddBoolean(TTP->isParameterPack());
63 continue;
64 }
65
66 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
67 ID.AddInteger(1);
68 // FIXME: Parameter pack
69 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
70 continue;
71 }
72
73 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
74 ID.AddInteger(2);
75 Profile(ID, TTP);
76 }
77}
78
79TemplateTemplateParmDecl *
80ASTContext::getCanonicalTemplateTemplateParmDecl(
81 TemplateTemplateParmDecl *TTP) {
82 // Check if we already have a canonical template template parameter.
83 llvm::FoldingSetNodeID ID;
84 CanonicalTemplateTemplateParm::Profile(ID, TTP);
85 void *InsertPos = 0;
86 CanonicalTemplateTemplateParm *Canonical
87 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
88 if (Canonical)
89 return Canonical->getParam();
90
91 // Build a canonical template parameter list.
92 TemplateParameterList *Params = TTP->getTemplateParameters();
93 llvm::SmallVector<NamedDecl *, 4> CanonParams;
94 CanonParams.reserve(Params->size());
95 for (TemplateParameterList::const_iterator P = Params->begin(),
96 PEnd = Params->end();
97 P != PEnd; ++P) {
98 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
99 CanonParams.push_back(
100 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
101 SourceLocation(), TTP->getDepth(),
102 TTP->getIndex(), 0, false,
103 TTP->isParameterPack()));
104 else if (NonTypeTemplateParmDecl *NTTP
105 = dyn_cast<NonTypeTemplateParmDecl>(*P))
106 CanonParams.push_back(
107 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
108 SourceLocation(), NTTP->getDepth(),
109 NTTP->getPosition(), 0,
110 getCanonicalType(NTTP->getType()),
111 0));
112 else
113 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
114 cast<TemplateTemplateParmDecl>(*P)));
115 }
116
117 TemplateTemplateParmDecl *CanonTTP
118 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
119 SourceLocation(), TTP->getDepth(),
120 TTP->getPosition(), 0,
121 TemplateParameterList::Create(*this, SourceLocation(),
122 SourceLocation(),
123 CanonParams.data(),
124 CanonParams.size(),
125 SourceLocation()));
126
127 // Get the new insert position for the node we care about.
128 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
129 assert(Canonical == 0 && "Shouldn't be in the map!");
130 (void)Canonical;
131
132 // Create the canonical template template parameter entry.
133 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
134 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
135 return CanonTTP;
136}
137
Charles Davis53c59df2010-08-16 03:33:14 +0000138CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000139 if (!LangOpts.CPlusPlus) return 0;
140
Charles Davis6bcb07a2010-08-19 02:18:14 +0000141 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000142 case CXXABI_ARM:
143 return CreateARMCXXABI(*this);
144 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000145 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000146 case CXXABI_Microsoft:
147 return CreateMicrosoftCXXABI(*this);
148 }
John McCall86353412010-08-21 22:46:04 +0000149 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000150}
151
Chris Lattner465fa322008-10-05 17:34:18 +0000152ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000153 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000154 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000155 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000156 unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000157 TemplateSpecializationTypes(this_()),
158 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000159 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
160 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000161 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000162 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000163 NullTypeSourceInfo(QualType()),
Charles Davis53c59df2010-08-16 03:33:14 +0000164 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000165 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000166 BuiltinInfo(builtins),
167 DeclarationNames(*this),
168 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000169 LastSDM(0, 0),
170 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000171 ObjCIdRedefinitionType = QualType();
172 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000173 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000174 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000175 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000176 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000177}
178
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000179ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000180 // Release the DenseMaps associated with DeclContext objects.
181 // FIXME: Is this the ideal solution?
182 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000183
Douglas Gregor5b11d492010-07-25 17:53:33 +0000184 // Call all of the deallocation functions.
185 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
186 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000187
Douglas Gregor832940b2010-03-02 23:58:15 +0000188 // Release all of the memory associated with overridden C++ methods.
189 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
190 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
191 OM != OMEnd; ++OM)
192 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000193
Ted Kremenek076baeb2010-06-08 23:00:58 +0000194 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000195 // because they can contain DenseMaps.
196 for (llvm::DenseMap<const ObjCContainerDecl*,
197 const ASTRecordLayout*>::iterator
198 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
199 // Increment in loop to prevent using deallocated memory.
200 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
201 R->Destroy(*this);
202
Ted Kremenek076baeb2010-06-08 23:00:58 +0000203 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
204 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
205 // Increment in loop to prevent using deallocated memory.
206 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
207 R->Destroy(*this);
208 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000209
210 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
211 AEnd = DeclAttrs.end();
212 A != AEnd; ++A)
213 A->second->~AttrVec();
214}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000215
Douglas Gregor1a809332010-05-23 18:26:36 +0000216void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
217 Deallocations.push_back(std::make_pair(Callback, Data));
218}
219
Mike Stump11289f42009-09-09 15:08:12 +0000220void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000221ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
222 ExternalSource.reset(Source.take());
223}
224
Chris Lattner4eb445d2007-01-26 01:27:23 +0000225void ASTContext::PrintStats() const {
226 fprintf(stderr, "*** AST Context Stats:\n");
227 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000228
Douglas Gregora30d0462009-05-26 14:40:08 +0000229 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000230#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000231#define ABSTRACT_TYPE(Name, Parent)
232#include "clang/AST/TypeNodes.def"
233 0 // Extra
234 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000235
Chris Lattner4eb445d2007-01-26 01:27:23 +0000236 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
237 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000238 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000239 }
240
Douglas Gregora30d0462009-05-26 14:40:08 +0000241 unsigned Idx = 0;
242 unsigned TotalBytes = 0;
243#define TYPE(Name, Parent) \
244 if (counts[Idx]) \
245 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
246 TotalBytes += counts[Idx] * sizeof(Name##Type); \
247 ++Idx;
248#define ABSTRACT_TYPE(Name, Parent)
249#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000250
Douglas Gregora30d0462009-05-26 14:40:08 +0000251 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000252
Douglas Gregor7454c562010-07-02 20:37:36 +0000253 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000254 fprintf(stderr, " %u/%u implicit default constructors created\n",
255 NumImplicitDefaultConstructorsDeclared,
256 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000257 fprintf(stderr, " %u/%u implicit copy constructors created\n",
258 NumImplicitCopyConstructorsDeclared,
259 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000260 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
261 NumImplicitCopyAssignmentOperatorsDeclared,
262 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000263 fprintf(stderr, " %u/%u implicit destructors created\n",
264 NumImplicitDestructorsDeclared, NumImplicitDestructors);
265
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000266 if (ExternalSource.get()) {
267 fprintf(stderr, "\n");
268 ExternalSource->PrintStats();
269 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000270
Douglas Gregor5b11d492010-07-25 17:53:33 +0000271 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000272}
273
274
John McCall48f2d582009-10-23 23:03:21 +0000275void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000276 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000277 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000278 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000279}
280
Chris Lattner970e54e2006-11-12 00:37:36 +0000281void ASTContext::InitBuiltinTypes() {
282 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000283
Chris Lattner970e54e2006-11-12 00:37:36 +0000284 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000285 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000286
Chris Lattner970e54e2006-11-12 00:37:36 +0000287 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000288 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000289 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000290 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000291 InitBuiltinType(CharTy, BuiltinType::Char_S);
292 else
293 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000294 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000295 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
296 InitBuiltinType(ShortTy, BuiltinType::Short);
297 InitBuiltinType(IntTy, BuiltinType::Int);
298 InitBuiltinType(LongTy, BuiltinType::Long);
299 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000300
Chris Lattner970e54e2006-11-12 00:37:36 +0000301 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000302 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
303 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
304 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
305 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
306 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000307
Chris Lattner970e54e2006-11-12 00:37:36 +0000308 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000309 InitBuiltinType(FloatTy, BuiltinType::Float);
310 InitBuiltinType(DoubleTy, BuiltinType::Double);
311 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000312
Chris Lattnerf122cef2009-04-30 02:43:43 +0000313 // GNU extension, 128-bit integers.
314 InitBuiltinType(Int128Ty, BuiltinType::Int128);
315 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
316
Chris Lattner007cb022009-02-26 23:43:47 +0000317 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
318 InitBuiltinType(WCharTy, BuiltinType::WChar);
319 else // C99
320 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000321
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000322 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
323 InitBuiltinType(Char16Ty, BuiltinType::Char16);
324 else // C99
325 Char16Ty = getFromTargetType(Target.getChar16Type());
326
327 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
328 InitBuiltinType(Char32Ty, BuiltinType::Char32);
329 else // C99
330 Char32Ty = getFromTargetType(Target.getChar32Type());
331
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000332 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000333 InitBuiltinType(OverloadTy, BuiltinType::Overload);
334
335 // Placeholder type for type-dependent expressions whose type is
336 // completely unknown. No code should ever check a type against
337 // DependentTy and users should never see it; however, it is here to
338 // help diagnose failures to properly check for type-dependent
339 // expressions.
340 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000341
Mike Stump11289f42009-09-09 15:08:12 +0000342 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000343 // not yet been deduced.
344 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000345
Chris Lattner970e54e2006-11-12 00:37:36 +0000346 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000347 FloatComplexTy = getComplexType(FloatTy);
348 DoubleComplexTy = getComplexType(DoubleTy);
349 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000350
Steve Naroff66e9f332007-10-15 14:41:52 +0000351 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000352
Steve Naroff1329fa02009-07-15 18:40:39 +0000353 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
354 ObjCIdTypedefType = QualType();
355 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000356 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000357
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000358 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000359 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
360 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000361 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000362
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000363 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000364
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000365 // void * type
366 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000367
368 // nullptr type (C++0x 2.14.7)
369 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000370}
371
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000372Diagnostic &ASTContext::getDiagnostics() const {
373 return SourceMgr.getDiagnostics();
374}
375
Douglas Gregor561eceb2010-08-30 16:49:28 +0000376AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
377 AttrVec *&Result = DeclAttrs[D];
378 if (!Result) {
379 void *Mem = Allocate(sizeof(AttrVec));
380 Result = new (Mem) AttrVec;
381 }
382
383 return *Result;
384}
385
386/// \brief Erase the attributes corresponding to the given declaration.
387void ASTContext::eraseDeclAttrs(const Decl *D) {
388 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
389 if (Pos != DeclAttrs.end()) {
390 Pos->second->~AttrVec();
391 DeclAttrs.erase(Pos);
392 }
393}
394
395
Douglas Gregor86d142a2009-10-08 07:24:58 +0000396MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000397ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000398 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000399 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000400 = InstantiatedFromStaticDataMember.find(Var);
401 if (Pos == InstantiatedFromStaticDataMember.end())
402 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000403
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000404 return Pos->second;
405}
406
Mike Stump11289f42009-09-09 15:08:12 +0000407void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000408ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000409 TemplateSpecializationKind TSK,
410 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000411 assert(Inst->isStaticDataMember() && "Not a static data member");
412 assert(Tmpl->isStaticDataMember() && "Not a static data member");
413 assert(!InstantiatedFromStaticDataMember[Inst] &&
414 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000415 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000416 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000417}
418
John McCalle61f2ba2009-11-18 02:36:19 +0000419NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000420ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000421 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000422 = InstantiatedFromUsingDecl.find(UUD);
423 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000424 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000425
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000426 return Pos->second;
427}
428
429void
John McCallb96ec562009-12-04 22:46:56 +0000430ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
431 assert((isa<UsingDecl>(Pattern) ||
432 isa<UnresolvedUsingValueDecl>(Pattern) ||
433 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
434 "pattern decl is not a using decl");
435 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
436 InstantiatedFromUsingDecl[Inst] = Pattern;
437}
438
439UsingShadowDecl *
440ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
441 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
442 = InstantiatedFromUsingShadowDecl.find(Inst);
443 if (Pos == InstantiatedFromUsingShadowDecl.end())
444 return 0;
445
446 return Pos->second;
447}
448
449void
450ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
451 UsingShadowDecl *Pattern) {
452 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
453 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000454}
455
Anders Carlsson5da84842009-09-01 04:26:58 +0000456FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
457 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
458 = InstantiatedFromUnnamedFieldDecl.find(Field);
459 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
460 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000461
Anders Carlsson5da84842009-09-01 04:26:58 +0000462 return Pos->second;
463}
464
465void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
466 FieldDecl *Tmpl) {
467 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
468 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
469 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
470 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000471
Anders Carlsson5da84842009-09-01 04:26:58 +0000472 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
473}
474
Douglas Gregor832940b2010-03-02 23:58:15 +0000475ASTContext::overridden_cxx_method_iterator
476ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
477 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
478 = OverriddenMethods.find(Method);
479 if (Pos == OverriddenMethods.end())
480 return 0;
481
482 return Pos->second.begin();
483}
484
485ASTContext::overridden_cxx_method_iterator
486ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
487 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
488 = OverriddenMethods.find(Method);
489 if (Pos == OverriddenMethods.end())
490 return 0;
491
492 return Pos->second.end();
493}
494
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000495unsigned
496ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
497 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
498 = OverriddenMethods.find(Method);
499 if (Pos == OverriddenMethods.end())
500 return 0;
501
502 return Pos->second.size();
503}
504
Douglas Gregor832940b2010-03-02 23:58:15 +0000505void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
506 const CXXMethodDecl *Overridden) {
507 OverriddenMethods[Method].push_back(Overridden);
508}
509
Chris Lattner53cfe802007-07-18 17:52:12 +0000510//===----------------------------------------------------------------------===//
511// Type Sizing and Analysis
512//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000513
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000514/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
515/// scalar floating point type.
516const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000517 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000518 assert(BT && "Not a floating point type!");
519 switch (BT->getKind()) {
520 default: assert(0 && "Not a floating point type!");
521 case BuiltinType::Float: return Target.getFloatFormat();
522 case BuiltinType::Double: return Target.getDoubleFormat();
523 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
524 }
525}
526
Ken Dyck160146e2010-01-27 17:10:57 +0000527/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000528/// specified decl. Note that bitfields do not have a valid alignment, so
529/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000530/// If @p RefAsPointee, references are treated like their underlying type
531/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000532CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000533 unsigned Align = Target.getCharWidth();
534
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000535 Align = std::max(Align, D->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000536
Chris Lattner68061312009-01-24 21:53:27 +0000537 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
538 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000539 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000540 if (RefAsPointee)
541 T = RT->getPointeeType();
542 else
543 T = getPointerType(RT->getPointeeType());
544 }
545 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000546 unsigned MinWidth = Target.getLargeArrayMinWidth();
547 unsigned ArrayAlign = Target.getLargeArrayAlign();
548 if (isa<VariableArrayType>(T) && MinWidth != 0)
549 Align = std::max(Align, ArrayAlign);
550 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
551 unsigned Size = getTypeSize(CT);
552 if (MinWidth != 0 && MinWidth <= Size)
553 Align = std::max(Align, ArrayAlign);
554 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000555 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000556 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
557 T = cast<ArrayType>(T)->getElementType();
558
559 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
560 }
Charles Davis3fc51072010-02-23 04:52:00 +0000561 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
562 // In the case of a field in a packed struct, we want the minimum
563 // of the alignment of the field and the alignment of the struct.
564 Align = std::min(Align,
565 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
566 }
Chris Lattner68061312009-01-24 21:53:27 +0000567 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000568
Ken Dyck160146e2010-01-27 17:10:57 +0000569 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000570}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000571
John McCall87fe5d52010-05-20 01:18:31 +0000572std::pair<CharUnits, CharUnits>
573ASTContext::getTypeInfoInChars(const Type *T) {
574 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
575 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
576 CharUnits::fromQuantity(Info.second / getCharWidth()));
577}
578
579std::pair<CharUnits, CharUnits>
580ASTContext::getTypeInfoInChars(QualType T) {
581 return getTypeInfoInChars(T.getTypePtr());
582}
583
Chris Lattner983a8bb2007-07-13 22:13:22 +0000584/// getTypeSize - Return the size of the specified type, in bits. This method
585/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000586///
587/// FIXME: Pointers into different addr spaces could have different sizes and
588/// alignment requirements: getPointerInfo should take an AddrSpace, this
589/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000590std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000591ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000592 uint64_t Width=0;
593 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000594 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000595#define TYPE(Class, Base)
596#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000597#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000598#define DEPENDENT_TYPE(Class, Base) case Type::Class:
599#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000600 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000601 break;
602
Chris Lattner355332d2007-07-13 22:27:08 +0000603 case Type::FunctionNoProto:
604 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000605 // GCC extension: alignof(function) = 32 bits
606 Width = 0;
607 Align = 32;
608 break;
609
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000610 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000611 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000612 Width = 0;
613 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
614 break;
615
Steve Naroff5c131802007-08-30 01:06:46 +0000616 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000617 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000618
Chris Lattner37e05872008-03-05 18:54:05 +0000619 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000620 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000621 Align = EltInfo.second;
622 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000623 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000624 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000625 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000626 const VectorType *VT = cast<VectorType>(T);
627 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
628 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000629 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000630 // If the alignment is not a power of 2, round up to the next power of 2.
631 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000632 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000633 Align = llvm::NextPowerOf2(Align);
634 Width = llvm::RoundUpToAlignment(Width, Align);
635 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000636 break;
637 }
Chris Lattner647fb222007-07-18 18:26:58 +0000638
Chris Lattner7570e9c2008-03-08 08:52:55 +0000639 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000640 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000641 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000642 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000643 // GCC extension: alignof(void) = 8 bits.
644 Width = 0;
645 Align = 8;
646 break;
647
Chris Lattner6a4f7452007-12-19 19:23:28 +0000648 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000649 Width = Target.getBoolWidth();
650 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000651 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000652 case BuiltinType::Char_S:
653 case BuiltinType::Char_U:
654 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000655 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000656 Width = Target.getCharWidth();
657 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000658 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000659 case BuiltinType::WChar:
660 Width = Target.getWCharWidth();
661 Align = Target.getWCharAlign();
662 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000663 case BuiltinType::Char16:
664 Width = Target.getChar16Width();
665 Align = Target.getChar16Align();
666 break;
667 case BuiltinType::Char32:
668 Width = Target.getChar32Width();
669 Align = Target.getChar32Align();
670 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000671 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000672 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000673 Width = Target.getShortWidth();
674 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000675 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000676 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000677 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000678 Width = Target.getIntWidth();
679 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000680 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000681 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000682 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000683 Width = Target.getLongWidth();
684 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000685 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000686 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000687 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000688 Width = Target.getLongLongWidth();
689 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000690 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000691 case BuiltinType::Int128:
692 case BuiltinType::UInt128:
693 Width = 128;
694 Align = 128; // int128_t is 128-bit aligned on all targets.
695 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000696 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000697 Width = Target.getFloatWidth();
698 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000699 break;
700 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000701 Width = Target.getDoubleWidth();
702 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000703 break;
704 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000705 Width = Target.getLongDoubleWidth();
706 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000707 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000708 case BuiltinType::NullPtr:
709 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
710 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000711 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000712 case BuiltinType::ObjCId:
713 case BuiltinType::ObjCClass:
714 case BuiltinType::ObjCSel:
715 Width = Target.getPointerWidth(0);
716 Align = Target.getPointerAlign(0);
717 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000718 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000719 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000720 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000721 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000722 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000723 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000724 case Type::BlockPointer: {
725 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
726 Width = Target.getPointerWidth(AS);
727 Align = Target.getPointerAlign(AS);
728 break;
729 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000730 case Type::LValueReference:
731 case Type::RValueReference: {
732 // alignof and sizeof should never enter this code path here, so we go
733 // the pointer route.
734 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
735 Width = Target.getPointerWidth(AS);
736 Align = Target.getPointerAlign(AS);
737 break;
738 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000739 case Type::Pointer: {
740 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000741 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000742 Align = Target.getPointerAlign(AS);
743 break;
744 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000745 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000746 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000747 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000748 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000749 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000750 Align = PtrDiffInfo.second;
751 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000752 }
Chris Lattner647fb222007-07-18 18:26:58 +0000753 case Type::Complex: {
754 // Complex types have the same alignment as their elements, but twice the
755 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000756 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000757 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000758 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000759 Align = EltInfo.second;
760 break;
761 }
John McCall8b07ec22010-05-15 11:32:37 +0000762 case Type::ObjCObject:
763 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000764 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000765 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000766 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
767 Width = Layout.getSize();
768 Align = Layout.getAlignment();
769 break;
770 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000771 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000772 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000773 const TagType *TT = cast<TagType>(T);
774
775 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000776 Width = 1;
777 Align = 1;
778 break;
779 }
Mike Stump11289f42009-09-09 15:08:12 +0000780
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000781 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000782 return getTypeInfo(ET->getDecl()->getIntegerType());
783
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000784 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000785 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
786 Width = Layout.getSize();
787 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000788 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000789 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000790
Chris Lattner63d2b362009-10-22 05:17:15 +0000791 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000792 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
793 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000794
Douglas Gregoref462e62009-04-30 17:32:17 +0000795 case Type::Typedef: {
796 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000797 std::pair<uint64_t, unsigned> Info
798 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
799 Align = std::max(Typedef->getMaxAlignment(), Info.second);
800 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000801 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000802 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000803
804 case Type::TypeOfExpr:
805 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
806 .getTypePtr());
807
808 case Type::TypeOf:
809 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
810
Anders Carlsson81df7b82009-06-24 19:06:50 +0000811 case Type::Decltype:
812 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
813 .getTypePtr());
814
Abramo Bagnara6150c882010-05-11 21:36:43 +0000815 case Type::Elaborated:
816 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000817
Douglas Gregoref462e62009-04-30 17:32:17 +0000818 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000819 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000820 "Cannot request the size of a dependent type");
821 // FIXME: this is likely to be wrong once we support template
822 // aliases, since a template alias could refer to a typedef that
823 // has an __aligned__ attribute on it.
824 return getTypeInfo(getCanonicalType(T));
825 }
Mike Stump11289f42009-09-09 15:08:12 +0000826
Chris Lattner53cfe802007-07-18 17:52:12 +0000827 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000828 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000829}
830
Ken Dyck8c89d592009-12-22 14:23:30 +0000831/// getTypeSizeInChars - Return the size of the specified type, in characters.
832/// This method does not work on incomplete types.
833CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000834 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000835}
836CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000837 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000838}
839
Ken Dycka6046ab2010-01-26 17:25:18 +0000840/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000841/// characters. This method does not work on incomplete types.
842CharUnits ASTContext::getTypeAlignInChars(QualType T) {
843 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
844}
845CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
846 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
847}
848
Chris Lattnera3402cd2009-01-27 18:08:34 +0000849/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
850/// type for the current target in bits. This can be different than the ABI
851/// alignment in cases where it is beneficial for performance to overalign
852/// a data type.
853unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
854 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000855
856 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000857 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000858 T = CT->getElementType().getTypePtr();
859 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
860 T->isSpecificBuiltinType(BuiltinType::LongLong))
861 return std::max(ABIAlign, (unsigned)getTypeSize(T));
862
Chris Lattnera3402cd2009-01-27 18:08:34 +0000863 return ABIAlign;
864}
865
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000866/// ShallowCollectObjCIvars -
867/// Collect all ivars, including those synthesized, in the current class.
868///
869void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000870 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000871 // FIXME. This need be removed but there are two many places which
872 // assume const-ness of ObjCInterfaceDecl
873 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
874 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
875 Iv= Iv->getNextIvar())
876 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000877}
878
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000879/// DeepCollectObjCIvars -
880/// This routine first collects all declared, but not synthesized, ivars in
881/// super class and then collects all ivars, including those synthesized for
882/// current class. This routine is used for implementation of current class
883/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000884///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000885void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
886 bool leafClass,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000887 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000888 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
889 DeepCollectObjCIvars(SuperClass, false, Ivars);
890 if (!leafClass) {
891 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
892 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000893 Ivars.push_back(*I);
894 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000895 else
896 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000897}
898
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000899/// CollectInheritedProtocols - Collect all protocols in current class and
900/// those inherited by it.
901void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000902 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000903 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000904 // We can use protocol_iterator here instead of
905 // all_referenced_protocol_iterator since we are walking all categories.
906 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
907 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000908 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000909 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000910 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000911 PE = Proto->protocol_end(); P != PE; ++P) {
912 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000913 CollectInheritedProtocols(*P, Protocols);
914 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000915 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000916
917 // Categories of this Interface.
918 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
919 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
920 CollectInheritedProtocols(CDeclChain, Protocols);
921 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
922 while (SD) {
923 CollectInheritedProtocols(SD, Protocols);
924 SD = SD->getSuperClass();
925 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000926 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000927 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000928 PE = OC->protocol_end(); P != PE; ++P) {
929 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000930 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000931 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
932 PE = Proto->protocol_end(); P != PE; ++P)
933 CollectInheritedProtocols(*P, Protocols);
934 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000935 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000936 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
937 PE = OP->protocol_end(); P != PE; ++P) {
938 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000939 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000940 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
941 PE = Proto->protocol_end(); P != PE; ++P)
942 CollectInheritedProtocols(*P, Protocols);
943 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000944 }
945}
946
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000947unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
948 unsigned count = 0;
949 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000950 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
951 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000952 count += CDecl->ivar_size();
953
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000954 // Count ivar defined in this class's implementation. This
955 // includes synthesized ivars.
956 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000957 count += ImplDecl->ivar_size();
958
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000959 return count;
960}
961
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000962/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
963ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
964 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
965 I = ObjCImpls.find(D);
966 if (I != ObjCImpls.end())
967 return cast<ObjCImplementationDecl>(I->second);
968 return 0;
969}
970/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
971ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
972 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
973 I = ObjCImpls.find(D);
974 if (I != ObjCImpls.end())
975 return cast<ObjCCategoryImplDecl>(I->second);
976 return 0;
977}
978
979/// \brief Set the implementation of ObjCInterfaceDecl.
980void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
981 ObjCImplementationDecl *ImplD) {
982 assert(IFaceD && ImplD && "Passed null params");
983 ObjCImpls[IFaceD] = ImplD;
984}
985/// \brief Set the implementation of ObjCCategoryDecl.
986void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
987 ObjCCategoryImplDecl *ImplD) {
988 assert(CatD && ImplD && "Passed null params");
989 ObjCImpls[CatD] = ImplD;
990}
991
John McCallbcd03502009-12-07 02:54:59 +0000992/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000993///
John McCallbcd03502009-12-07 02:54:59 +0000994/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000995/// the TypeLoc wrappers.
996///
997/// \param T the type that will be the basis for type source info. This type
998/// should refer to how the declarator was written in source code, not to
999/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001000TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +00001001 unsigned DataSize) {
1002 if (!DataSize)
1003 DataSize = TypeLoc::getFullDataSizeForType(T);
1004 else
1005 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001006 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001007
John McCallbcd03502009-12-07 02:54:59 +00001008 TypeSourceInfo *TInfo =
1009 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1010 new (TInfo) TypeSourceInfo(T);
1011 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001012}
1013
John McCallbcd03502009-12-07 02:54:59 +00001014TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001015 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001016 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001017 DI->getTypeLoc().initialize(L);
1018 return DI;
1019}
1020
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001021const ASTRecordLayout &
1022ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1023 return getObjCLayout(D, 0);
1024}
1025
1026const ASTRecordLayout &
1027ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1028 return getObjCLayout(D->getClassInterface(), D);
1029}
1030
Chris Lattner983a8bb2007-07-13 22:13:22 +00001031//===----------------------------------------------------------------------===//
1032// Type creation/memoization methods
1033//===----------------------------------------------------------------------===//
1034
John McCall8ccfcb52009-09-24 19:53:00 +00001035QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1036 unsigned Fast = Quals.getFastQualifiers();
1037 Quals.removeFastQualifiers();
1038
1039 // Check if we've already instantiated this type.
1040 llvm::FoldingSetNodeID ID;
1041 ExtQuals::Profile(ID, TypeNode, Quals);
1042 void *InsertPos = 0;
1043 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1044 assert(EQ->getQualifiers() == Quals);
1045 QualType T = QualType(EQ, Fast);
1046 return T;
1047 }
1048
John McCall90d1c2d2009-09-24 23:30:46 +00001049 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001050 ExtQualNodes.InsertNode(New, InsertPos);
1051 QualType T = QualType(New, Fast);
1052 return T;
1053}
1054
1055QualType ASTContext::getVolatileType(QualType T) {
1056 QualType CanT = getCanonicalType(T);
1057 if (CanT.isVolatileQualified()) return T;
1058
1059 QualifierCollector Quals;
1060 const Type *TypeNode = Quals.strip(T);
1061 Quals.addVolatile();
1062
1063 return getExtQualType(TypeNode, Quals);
1064}
1065
Fariborz Jahanianece85822009-02-17 18:27:45 +00001066QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001067 QualType CanT = getCanonicalType(T);
1068 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001069 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001070
John McCall8ccfcb52009-09-24 19:53:00 +00001071 // If we are composing extended qualifiers together, merge together
1072 // into one ExtQuals node.
1073 QualifierCollector Quals;
1074 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001075
John McCall8ccfcb52009-09-24 19:53:00 +00001076 // If this type already has an address space specified, it cannot get
1077 // another one.
1078 assert(!Quals.hasAddressSpace() &&
1079 "Type cannot be in multiple addr spaces!");
1080 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001081
John McCall8ccfcb52009-09-24 19:53:00 +00001082 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001083}
1084
Chris Lattnerd60183d2009-02-18 22:53:11 +00001085QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001086 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001087 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001088 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001089 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001090
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001091 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001092 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001093 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001094 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1095 return getPointerType(ResultType);
1096 }
1097 }
Mike Stump11289f42009-09-09 15:08:12 +00001098
John McCall8ccfcb52009-09-24 19:53:00 +00001099 // If we are composing extended qualifiers together, merge together
1100 // into one ExtQuals node.
1101 QualifierCollector Quals;
1102 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001103
John McCall8ccfcb52009-09-24 19:53:00 +00001104 // If this type already has an ObjCGC specified, it cannot get
1105 // another one.
1106 assert(!Quals.hasObjCGCAttr() &&
1107 "Type cannot have multiple ObjCGCs!");
1108 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001109
John McCall8ccfcb52009-09-24 19:53:00 +00001110 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001111}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001112
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001113static QualType getExtFunctionType(ASTContext& Context, QualType T,
1114 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +00001115 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001116 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1117 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001118 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001119 if (ResultType == Pointee)
1120 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001121
1122 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001123 } else if (const BlockPointerType *BlockPointer
1124 = T->getAs<BlockPointerType>()) {
1125 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001126 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001127 if (ResultType == Pointee)
1128 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001129
1130 ResultType = Context.getBlockPointerType(ResultType);
Douglas Gregoreece0ea2010-09-01 16:29:03 +00001131 } else if (const MemberPointerType *MemberPointer
1132 = T->getAs<MemberPointerType>()) {
1133 QualType Pointee = MemberPointer->getPointeeType();
1134 ResultType = getExtFunctionType(Context, Pointee, Info);
1135 if (ResultType == Pointee)
1136 return T;
1137
1138 ResultType = Context.getMemberPointerType(ResultType,
1139 MemberPointer->getClass());
Douglas Gregor8c940862010-01-18 17:14:39 +00001140 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001141 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001142 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001143
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001144 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001145 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001146 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001147 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001148 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001149 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001150 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1151 FPT->getNumArgs(), FPT->isVariadic(),
1152 FPT->getTypeQuals(),
1153 FPT->hasExceptionSpec(),
1154 FPT->hasAnyExceptionSpec(),
1155 FPT->getNumExceptions(),
1156 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001157 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001158 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001159 } else
1160 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001161
1162 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1163}
1164
1165QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001166 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001167 return getExtFunctionType(*this, T,
1168 Info.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001169}
1170
1171QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001172 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001173 return getExtFunctionType(*this, T,
1174 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001175}
1176
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001177QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1178 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1179 return getExtFunctionType(*this, T,
1180 Info.withRegParm(RegParm));
1181}
1182
Chris Lattnerc6395932007-06-22 20:56:16 +00001183/// getComplexType - Return the uniqued reference to the type for a complex
1184/// number with the specified element type.
1185QualType ASTContext::getComplexType(QualType T) {
1186 // Unique pointers, to guarantee there is only one pointer of a particular
1187 // structure.
1188 llvm::FoldingSetNodeID ID;
1189 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001190
Chris Lattnerc6395932007-06-22 20:56:16 +00001191 void *InsertPos = 0;
1192 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1193 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001194
Chris Lattnerc6395932007-06-22 20:56:16 +00001195 // If the pointee type isn't canonical, this won't be a canonical type either,
1196 // so fill in the canonical type field.
1197 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001198 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001199 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001200
Chris Lattnerc6395932007-06-22 20:56:16 +00001201 // Get the new insert position for the node we care about.
1202 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001203 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001204 }
John McCall90d1c2d2009-09-24 23:30:46 +00001205 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001206 Types.push_back(New);
1207 ComplexTypes.InsertNode(New, InsertPos);
1208 return QualType(New, 0);
1209}
1210
Chris Lattner970e54e2006-11-12 00:37:36 +00001211/// getPointerType - Return the uniqued reference to the type for a pointer to
1212/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001213QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001214 // Unique pointers, to guarantee there is only one pointer of a particular
1215 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001216 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001217 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001218
Chris Lattner67521df2007-01-27 01:29:36 +00001219 void *InsertPos = 0;
1220 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001221 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001222
Chris Lattner7ccecb92006-11-12 08:50:50 +00001223 // If the pointee type isn't canonical, this won't be a canonical type either,
1224 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001225 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001226 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001227 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001228
Chris Lattner67521df2007-01-27 01:29:36 +00001229 // Get the new insert position for the node we care about.
1230 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001231 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001232 }
John McCall90d1c2d2009-09-24 23:30:46 +00001233 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001234 Types.push_back(New);
1235 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001236 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001237}
1238
Mike Stump11289f42009-09-09 15:08:12 +00001239/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001240/// a pointer to the specified block.
1241QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001242 assert(T->isFunctionType() && "block of function types only");
1243 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001244 // structure.
1245 llvm::FoldingSetNodeID ID;
1246 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001247
Steve Naroffec33ed92008-08-27 16:04:49 +00001248 void *InsertPos = 0;
1249 if (BlockPointerType *PT =
1250 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1251 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001252
1253 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001254 // type either so fill in the canonical type field.
1255 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001256 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001257 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001258
Steve Naroffec33ed92008-08-27 16:04:49 +00001259 // Get the new insert position for the node we care about.
1260 BlockPointerType *NewIP =
1261 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001262 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001263 }
John McCall90d1c2d2009-09-24 23:30:46 +00001264 BlockPointerType *New
1265 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001266 Types.push_back(New);
1267 BlockPointerTypes.InsertNode(New, InsertPos);
1268 return QualType(New, 0);
1269}
1270
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001271/// getLValueReferenceType - Return the uniqued reference to the type for an
1272/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001273QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
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);
Chris Lattnere05f5342008-10-12 00:26:57 +00001296 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = 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.
1310QualType ASTContext::getRValueReferenceType(QualType T) {
1311 // 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);
1333 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1334 }
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.
Mike Stump11289f42009-09-09 15:08:12 +00001345QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
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);
1365 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1366 }
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,
1379 unsigned EltTypeQuals) {
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);
1387 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001388
Chris Lattner23b7eb62007-06-15 23:05:46 +00001389 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001390 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001391
Chris Lattner36f8e652007-01-27 08:31:04 +00001392 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001393 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001394 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001395 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001396
Chris Lattner7ccecb92006-11-12 08:50:50 +00001397 // If the element type isn't canonical, this won't be a canonical type either,
1398 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001399 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001400 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001401 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001402 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001403 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001404 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001405 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001406 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001407 }
Mike Stump11289f42009-09-09 15:08:12 +00001408
John McCall90d1c2d2009-09-24 23:30:46 +00001409 ConstantArrayType *New = new(*this,TypeAlignment)
1410 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001411 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001412 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001413 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001414}
1415
Steve Naroffcadebd02007-08-30 18:14:25 +00001416/// getVariableArrayType - Returns a non-unique reference to the type for a
1417/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001418QualType ASTContext::getVariableArrayType(QualType EltTy,
1419 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001420 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001421 unsigned EltTypeQuals,
1422 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001423 // Since we don't unique expressions, it isn't possible to unique VLA's
1424 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001425 QualType CanonType;
1426
1427 if (!EltTy.isCanonical()) {
1428 if (NumElts)
1429 NumElts->Retain();
1430 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1431 EltTypeQuals, Brackets);
1432 }
1433
John McCall90d1c2d2009-09-24 23:30:46 +00001434 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001435 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001436
1437 VariableArrayTypes.push_back(New);
1438 Types.push_back(New);
1439 return QualType(New, 0);
1440}
1441
Douglas Gregor4619e432008-12-05 23:32:09 +00001442/// getDependentSizedArrayType - Returns a non-unique reference to
1443/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001444/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001445QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1446 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001447 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001448 unsigned EltTypeQuals,
1449 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001450 assert((!NumElts || NumElts->isTypeDependent() ||
1451 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001452 "Size must be type- or value-dependent!");
1453
Douglas Gregorf3f95522009-07-31 00:23:35 +00001454 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001455 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001456 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001457
1458 if (NumElts) {
1459 // Dependently-sized array types that do not have a specified
1460 // number of elements will have their sizes deduced from an
1461 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001462 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1463 EltTypeQuals, NumElts);
1464
1465 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1466 }
1467
Douglas Gregorf3f95522009-07-31 00:23:35 +00001468 DependentSizedArrayType *New;
1469 if (Canon) {
1470 // We already have a canonical version of this array type; use it as
1471 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001472 New = new (*this, TypeAlignment)
1473 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1474 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001475 } else {
1476 QualType CanonEltTy = getCanonicalType(EltTy);
1477 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001478 New = new (*this, TypeAlignment)
1479 DependentSizedArrayType(*this, EltTy, QualType(),
1480 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001481
Douglas Gregorc42075a2010-02-04 18:10:26 +00001482 if (NumElts) {
1483 DependentSizedArrayType *CanonCheck
1484 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1485 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1486 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001487 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001488 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001489 } else {
1490 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1491 ASM, EltTypeQuals,
1492 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001493 New = new (*this, TypeAlignment)
1494 DependentSizedArrayType(*this, EltTy, Canon,
1495 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001496 }
1497 }
Mike Stump11289f42009-09-09 15:08:12 +00001498
Douglas Gregor4619e432008-12-05 23:32:09 +00001499 Types.push_back(New);
1500 return QualType(New, 0);
1501}
1502
Eli Friedmanbd258282008-02-15 18:16:39 +00001503QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1504 ArrayType::ArraySizeModifier ASM,
1505 unsigned EltTypeQuals) {
1506 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001507 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001508
1509 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001510 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001511 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1512 return QualType(ATP, 0);
1513
1514 // If the element type isn't canonical, this won't be a canonical type
1515 // either, so fill in the canonical type field.
1516 QualType Canonical;
1517
John McCallb692a092009-10-22 20:10:53 +00001518 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001519 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001520 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001521
1522 // Get the new insert position for the node we care about.
1523 IncompleteArrayType *NewIP =
1524 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001525 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001526 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001527
John McCall90d1c2d2009-09-24 23:30:46 +00001528 IncompleteArrayType *New = new (*this, TypeAlignment)
1529 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001530
1531 IncompleteArrayTypes.InsertNode(New, InsertPos);
1532 Types.push_back(New);
1533 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001534}
1535
Steve Naroff91fcddb2007-07-18 18:00:27 +00001536/// getVectorType - Return the unique reference to a vector type of
1537/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001538QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Chris Lattner37141f42010-06-23 06:00:24 +00001539 VectorType::AltiVecSpecific AltiVecSpec) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001540 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001541
Chris Lattner76a00cf2008-04-06 22:59:24 +00001542 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001543 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001544
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001545 // Check if we've already instantiated a vector of this type.
1546 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001547 VectorType::Profile(ID, vecType, NumElts, Type::Vector, AltiVecSpec);
1548
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001549 void *InsertPos = 0;
1550 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1551 return QualType(VTP, 0);
1552
1553 // If the element type isn't canonical, this won't be a canonical type either,
1554 // so fill in the canonical type field.
1555 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001556 if (!vecType.isCanonical()) {
Chris Lattner37141f42010-06-23 06:00:24 +00001557 Canonical = getVectorType(getCanonicalType(vecType), NumElts,
1558 VectorType::NotAltiVec);
Mike Stump11289f42009-09-09 15:08:12 +00001559
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001560 // Get the new insert position for the node we care about.
1561 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001562 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001563 }
John McCall90d1c2d2009-09-24 23:30:46 +00001564 VectorType *New = new (*this, TypeAlignment)
Chris Lattner37141f42010-06-23 06:00:24 +00001565 VectorType(vecType, NumElts, Canonical, AltiVecSpec);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001566 VectorTypes.InsertNode(New, InsertPos);
1567 Types.push_back(New);
1568 return QualType(New, 0);
1569}
1570
Nate Begemance4d7fc2008-04-18 23:10:10 +00001571/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001572/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001573QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001574 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001575
Chris Lattner76a00cf2008-04-06 22:59:24 +00001576 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001577 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001578
Steve Naroff91fcddb2007-07-18 18:00:27 +00001579 // Check if we've already instantiated a vector of this type.
1580 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001581 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1582 VectorType::NotAltiVec);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001583 void *InsertPos = 0;
1584 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1585 return QualType(VTP, 0);
1586
1587 // If the element type isn't canonical, this won't be a canonical type either,
1588 // so fill in the canonical type field.
1589 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001590 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001591 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001592
Steve Naroff91fcddb2007-07-18 18:00:27 +00001593 // Get the new insert position for the node we care about.
1594 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001595 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001596 }
John McCall90d1c2d2009-09-24 23:30:46 +00001597 ExtVectorType *New = new (*this, TypeAlignment)
1598 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001599 VectorTypes.InsertNode(New, InsertPos);
1600 Types.push_back(New);
1601 return QualType(New, 0);
1602}
1603
Mike Stump11289f42009-09-09 15:08:12 +00001604QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001605 Expr *SizeExpr,
1606 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001607 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001608 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001609 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001610
Douglas Gregor352169a2009-07-31 03:54:25 +00001611 void *InsertPos = 0;
1612 DependentSizedExtVectorType *Canon
1613 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1614 DependentSizedExtVectorType *New;
1615 if (Canon) {
1616 // We already have a canonical version of this array type; use it as
1617 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001618 New = new (*this, TypeAlignment)
1619 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1620 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001621 } else {
1622 QualType CanonVecTy = getCanonicalType(vecType);
1623 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001624 New = new (*this, TypeAlignment)
1625 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1626 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001627
1628 DependentSizedExtVectorType *CanonCheck
1629 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1630 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1631 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001632 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1633 } else {
1634 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1635 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001636 New = new (*this, TypeAlignment)
1637 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001638 }
1639 }
Mike Stump11289f42009-09-09 15:08:12 +00001640
Douglas Gregor758a8692009-06-17 21:51:59 +00001641 Types.push_back(New);
1642 return QualType(New, 0);
1643}
1644
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001645/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001646///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001647QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1648 const FunctionType::ExtInfo &Info) {
1649 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001650 // Unique functions, to guarantee there is only one function of a particular
1651 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001652 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001653 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001654
Chris Lattner47955de2007-01-27 08:37:20 +00001655 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001656 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001657 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001658 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001659
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001660 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001661 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001662 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001663 Canonical =
1664 getFunctionNoProtoType(getCanonicalType(ResultTy),
1665 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001666
Chris Lattner47955de2007-01-27 08:37:20 +00001667 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001668 FunctionNoProtoType *NewIP =
1669 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001670 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001671 }
Mike Stump11289f42009-09-09 15:08:12 +00001672
John McCall90d1c2d2009-09-24 23:30:46 +00001673 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001674 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001675 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001676 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001677 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001678}
1679
1680/// getFunctionType - Return a normal function type with a typed argument
1681/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001682QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001683 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001684 unsigned TypeQuals, bool hasExceptionSpec,
1685 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001686 const QualType *ExArray,
1687 const FunctionType::ExtInfo &Info) {
1688 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001689 // Unique functions, to guarantee there is only one function of a particular
1690 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001691 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001692 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001693 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001694 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001695
1696 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001697 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001698 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001699 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001700
1701 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001702 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001703 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001704 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001705 isCanonical = false;
1706
1707 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001708 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001709 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001710 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001711 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001712 CanonicalArgs.reserve(NumArgs);
1713 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001714 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001715
Chris Lattner76a00cf2008-04-06 22:59:24 +00001716 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001717 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001718 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001719 false, 0, 0,
1720 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001721
Chris Lattnerfd4de792007-01-27 01:15:32 +00001722 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001723 FunctionProtoType *NewIP =
1724 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001725 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001726 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001727
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001728 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001729 // for two variable size arrays (for parameter and exception types) at the
1730 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001731 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001732 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1733 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001734 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001735 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001736 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001737 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001738 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001739 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001740 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001741}
Chris Lattneref51c202006-11-10 07:17:23 +00001742
John McCalle78aac42010-03-10 03:28:59 +00001743#ifndef NDEBUG
1744static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1745 if (!isa<CXXRecordDecl>(D)) return false;
1746 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1747 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1748 return true;
1749 if (RD->getDescribedClassTemplate() &&
1750 !isa<ClassTemplateSpecializationDecl>(RD))
1751 return true;
1752 return false;
1753}
1754#endif
1755
1756/// getInjectedClassNameType - Return the unique reference to the
1757/// injected class name type for the specified templated declaration.
1758QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1759 QualType TST) {
1760 assert(NeedsInjectedClassNameType(Decl));
1761 if (Decl->TypeForDecl) {
1762 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001763 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001764 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1765 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1766 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1767 } else {
John McCall2408e322010-04-27 00:57:59 +00001768 Decl->TypeForDecl =
1769 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001770 Types.push_back(Decl->TypeForDecl);
1771 }
1772 return QualType(Decl->TypeForDecl, 0);
1773}
1774
Douglas Gregor83a586e2008-04-13 21:07:44 +00001775/// getTypeDeclType - Return the unique reference to the type for the
1776/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001777QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001778 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001779 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001780
John McCall81e38502010-02-16 03:57:14 +00001781 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001782 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001783
John McCall96f0b5f2010-03-10 06:48:02 +00001784 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1785 "Template type parameter types are always available.");
1786
John McCall81e38502010-02-16 03:57:14 +00001787 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001788 assert(!Record->getPreviousDeclaration() &&
1789 "struct/union has previous declaration");
1790 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001791 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001792 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001793 assert(!Enum->getPreviousDeclaration() &&
1794 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001795 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001796 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001797 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1798 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001799 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001800 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001801
John McCall96f0b5f2010-03-10 06:48:02 +00001802 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001803 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001804}
1805
Chris Lattner32d920b2007-01-26 02:01:53 +00001806/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001807/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001808QualType
1809ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001810 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001811
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001812 if (Canonical.isNull())
1813 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001814 Decl->TypeForDecl = new(*this, TypeAlignment)
1815 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001816 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001817 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001818}
1819
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001820QualType ASTContext::getRecordType(const RecordDecl *Decl) {
1821 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1822
1823 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
1824 if (PrevDecl->TypeForDecl)
1825 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1826
1827 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl);
1828 Types.push_back(Decl->TypeForDecl);
1829 return QualType(Decl->TypeForDecl, 0);
1830}
1831
1832QualType ASTContext::getEnumType(const EnumDecl *Decl) {
1833 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1834
1835 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
1836 if (PrevDecl->TypeForDecl)
1837 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
1838
1839 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl);
1840 Types.push_back(Decl->TypeForDecl);
1841 return QualType(Decl->TypeForDecl, 0);
1842}
1843
John McCallcebee162009-10-18 09:09:24 +00001844/// \brief Retrieve a substitution-result type.
1845QualType
1846ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1847 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001848 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001849 && "replacement types must always be canonical");
1850
1851 llvm::FoldingSetNodeID ID;
1852 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1853 void *InsertPos = 0;
1854 SubstTemplateTypeParmType *SubstParm
1855 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1856
1857 if (!SubstParm) {
1858 SubstParm = new (*this, TypeAlignment)
1859 SubstTemplateTypeParmType(Parm, Replacement);
1860 Types.push_back(SubstParm);
1861 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1862 }
1863
1864 return QualType(SubstParm, 0);
1865}
1866
Douglas Gregoreff93e02009-02-05 23:33:38 +00001867/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001868/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001869/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001870QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001871 bool ParameterPack,
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001872 IdentifierInfo *Name) {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001873 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001874 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001875 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001876 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001877 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1878
1879 if (TypeParm)
1880 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001881
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001882 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001883 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001884 TypeParm = new (*this, TypeAlignment)
1885 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001886
1887 TemplateTypeParmType *TypeCheck
1888 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1889 assert(!TypeCheck && "Template type parameter canonical type broken");
1890 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001891 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001892 TypeParm = new (*this, TypeAlignment)
1893 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001894
1895 Types.push_back(TypeParm);
1896 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1897
1898 return QualType(TypeParm, 0);
1899}
1900
John McCalle78aac42010-03-10 03:28:59 +00001901TypeSourceInfo *
1902ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1903 SourceLocation NameLoc,
1904 const TemplateArgumentListInfo &Args,
1905 QualType CanonType) {
1906 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1907
1908 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1909 TemplateSpecializationTypeLoc TL
1910 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1911 TL.setTemplateNameLoc(NameLoc);
1912 TL.setLAngleLoc(Args.getLAngleLoc());
1913 TL.setRAngleLoc(Args.getRAngleLoc());
1914 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1915 TL.setArgLocInfo(i, Args[i].getLocInfo());
1916 return DI;
1917}
1918
Mike Stump11289f42009-09-09 15:08:12 +00001919QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001920ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001921 const TemplateArgumentListInfo &Args,
John McCall30576cd2010-06-13 09:25:03 +00001922 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00001923 unsigned NumArgs = Args.size();
1924
John McCall0ad16662009-10-29 08:12:44 +00001925 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1926 ArgVec.reserve(NumArgs);
1927 for (unsigned i = 0; i != NumArgs; ++i)
1928 ArgVec.push_back(Args[i].getArgument());
1929
John McCall2408e322010-04-27 00:57:59 +00001930 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001931 Canon);
John McCall0ad16662009-10-29 08:12:44 +00001932}
1933
1934QualType
1935ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001936 const TemplateArgument *Args,
1937 unsigned NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001938 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00001939 if (!Canon.isNull())
1940 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001941 else
1942 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00001943
Douglas Gregora8e02e72009-07-28 23:00:59 +00001944 // Allocate the (non-canonical) template specialization type, but don't
1945 // try to unique it: these types typically have location information that
1946 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001947 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001948 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001949 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001950 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00001951 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00001952 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001953 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001954
Douglas Gregor8bf42052009-02-09 18:46:07 +00001955 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001956 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001957}
1958
Mike Stump11289f42009-09-09 15:08:12 +00001959QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00001960ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
1961 const TemplateArgument *Args,
1962 unsigned NumArgs) {
1963 // Build the canonical template specialization type.
1964 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1965 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1966 CanonArgs.reserve(NumArgs);
1967 for (unsigned I = 0; I != NumArgs; ++I)
1968 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1969
1970 // Determine whether this canonical template specialization type already
1971 // exists.
1972 llvm::FoldingSetNodeID ID;
1973 TemplateSpecializationType::Profile(ID, CanonTemplate,
1974 CanonArgs.data(), NumArgs, *this);
1975
1976 void *InsertPos = 0;
1977 TemplateSpecializationType *Spec
1978 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1979
1980 if (!Spec) {
1981 // Allocate a new canonical template specialization type.
1982 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1983 sizeof(TemplateArgument) * NumArgs),
1984 TypeAlignment);
1985 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1986 CanonArgs.data(), NumArgs,
1987 QualType());
1988 Types.push_back(Spec);
1989 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1990 }
1991
1992 assert(Spec->isDependentType() &&
1993 "Non-dependent template-id type must have a canonical type");
1994 return QualType(Spec, 0);
1995}
1996
1997QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00001998ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1999 NestedNameSpecifier *NNS,
2000 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00002001 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002002 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002003
2004 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002005 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002006 if (T)
2007 return QualType(T, 0);
2008
Douglas Gregorc42075a2010-02-04 18:10:26 +00002009 QualType Canon = NamedType;
2010 if (!Canon.isCanonical()) {
2011 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002012 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2013 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002014 (void)CheckT;
2015 }
2016
Abramo Bagnara6150c882010-05-11 21:36:43 +00002017 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002018 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002019 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002020 return QualType(T, 0);
2021}
2022
Douglas Gregor02085352010-03-31 20:19:30 +00002023QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2024 NestedNameSpecifier *NNS,
2025 const IdentifierInfo *Name,
2026 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00002027 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2028
2029 if (Canon.isNull()) {
2030 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002031 ElaboratedTypeKeyword CanonKeyword = Keyword;
2032 if (Keyword == ETK_None)
2033 CanonKeyword = ETK_Typename;
2034
2035 if (CanonNNS != NNS || CanonKeyword != Keyword)
2036 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002037 }
2038
2039 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002040 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002041
2042 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002043 DependentNameType *T
2044 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002045 if (T)
2046 return QualType(T, 0);
2047
Douglas Gregor02085352010-03-31 20:19:30 +00002048 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002049 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002050 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002051 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002052}
2053
Mike Stump11289f42009-09-09 15:08:12 +00002054QualType
John McCallc392f372010-06-11 00:33:02 +00002055ASTContext::getDependentTemplateSpecializationType(
2056 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002057 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002058 const IdentifierInfo *Name,
2059 const TemplateArgumentListInfo &Args) {
2060 // TODO: avoid this copy
2061 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2062 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2063 ArgCopy.push_back(Args[I].getArgument());
2064 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2065 ArgCopy.size(),
2066 ArgCopy.data());
2067}
2068
2069QualType
2070ASTContext::getDependentTemplateSpecializationType(
2071 ElaboratedTypeKeyword Keyword,
2072 NestedNameSpecifier *NNS,
2073 const IdentifierInfo *Name,
2074 unsigned NumArgs,
2075 const TemplateArgument *Args) {
Douglas Gregordce2b622009-04-01 00:28:59 +00002076 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2077
Douglas Gregorc42075a2010-02-04 18:10:26 +00002078 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002079 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2080 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002081
2082 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002083 DependentTemplateSpecializationType *T
2084 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002085 if (T)
2086 return QualType(T, 0);
2087
John McCallc392f372010-06-11 00:33:02 +00002088 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002089
John McCallc392f372010-06-11 00:33:02 +00002090 ElaboratedTypeKeyword CanonKeyword = Keyword;
2091 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2092
2093 bool AnyNonCanonArgs = false;
2094 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2095 for (unsigned I = 0; I != NumArgs; ++I) {
2096 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2097 if (!CanonArgs[I].structurallyEquals(Args[I]))
2098 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002099 }
2100
John McCallc392f372010-06-11 00:33:02 +00002101 QualType Canon;
2102 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2103 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2104 Name, NumArgs,
2105 CanonArgs.data());
2106
2107 // Find the insert position again.
2108 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2109 }
2110
2111 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2112 sizeof(TemplateArgument) * NumArgs),
2113 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002114 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002115 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002116 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002117 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002118 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002119}
2120
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002121/// CmpProtocolNames - Comparison predicate for sorting protocols
2122/// alphabetically.
2123static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2124 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002125 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002126}
2127
John McCall8b07ec22010-05-15 11:32:37 +00002128static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002129 unsigned NumProtocols) {
2130 if (NumProtocols == 0) return true;
2131
2132 for (unsigned i = 1; i != NumProtocols; ++i)
2133 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2134 return false;
2135 return true;
2136}
2137
2138static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002139 unsigned &NumProtocols) {
2140 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002141
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002142 // Sort protocols, keyed by name.
2143 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2144
2145 // Remove duplicates.
2146 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2147 NumProtocols = ProtocolsEnd-Protocols;
2148}
2149
John McCall8b07ec22010-05-15 11:32:37 +00002150QualType ASTContext::getObjCObjectType(QualType BaseType,
2151 ObjCProtocolDecl * const *Protocols,
2152 unsigned NumProtocols) {
2153 // If the base type is an interface and there aren't any protocols
2154 // to add, then the interface type will do just fine.
2155 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2156 return BaseType;
2157
2158 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002159 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002160 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002161 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002162 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2163 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002164
John McCall8b07ec22010-05-15 11:32:37 +00002165 // Build the canonical type, which has the canonical base type and
2166 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002167 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002168 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2169 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2170 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002171 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2172 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002173 unsigned UniqueCount = NumProtocols;
2174
John McCallfc93cf92009-10-22 22:37:11 +00002175 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002176 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2177 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002178 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002179 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2180 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002181 }
2182
2183 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002184 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2185 }
2186
2187 unsigned Size = sizeof(ObjCObjectTypeImpl);
2188 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2189 void *Mem = Allocate(Size, TypeAlignment);
2190 ObjCObjectTypeImpl *T =
2191 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2192
2193 Types.push_back(T);
2194 ObjCObjectTypes.InsertNode(T, InsertPos);
2195 return QualType(T, 0);
2196}
2197
2198/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2199/// the given object type.
2200QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2201 llvm::FoldingSetNodeID ID;
2202 ObjCObjectPointerType::Profile(ID, ObjectT);
2203
2204 void *InsertPos = 0;
2205 if (ObjCObjectPointerType *QT =
2206 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2207 return QualType(QT, 0);
2208
2209 // Find the canonical object type.
2210 QualType Canonical;
2211 if (!ObjectT.isCanonical()) {
2212 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2213
2214 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002215 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2216 }
2217
Douglas Gregorf85bee62010-02-08 22:59:26 +00002218 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002219 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2220 ObjCObjectPointerType *QType =
2221 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002222
Steve Narofffb4330f2009-06-17 22:40:22 +00002223 Types.push_back(QType);
2224 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002225 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002226}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002227
Douglas Gregor1c283312010-08-11 12:19:30 +00002228/// getObjCInterfaceType - Return the unique reference to the type for the
2229/// specified ObjC interface decl. The list of protocols is optional.
2230QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2231 if (Decl->TypeForDecl)
2232 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002233
Douglas Gregor1c283312010-08-11 12:19:30 +00002234 // FIXME: redeclarations?
2235 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2236 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2237 Decl->TypeForDecl = T;
2238 Types.push_back(T);
2239 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002240}
2241
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002242/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2243/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002244/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002245/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002246/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002247QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002248 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002249 if (tofExpr->isTypeDependent()) {
2250 llvm::FoldingSetNodeID ID;
2251 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002252
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002253 void *InsertPos = 0;
2254 DependentTypeOfExprType *Canon
2255 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2256 if (Canon) {
2257 // We already have a "canonical" version of an identical, dependent
2258 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002259 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002260 QualType((TypeOfExprType*)Canon, 0));
2261 }
2262 else {
2263 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002264 Canon
2265 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002266 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2267 toe = Canon;
2268 }
2269 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002270 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002271 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002272 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002273 Types.push_back(toe);
2274 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002275}
2276
Steve Naroffa773cd52007-08-01 18:02:17 +00002277/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2278/// TypeOfType AST's. The only motivation to unique these nodes would be
2279/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002280/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002281/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002282QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002283 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002284 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002285 Types.push_back(tot);
2286 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002287}
2288
Anders Carlssonad6bd352009-06-24 21:24:56 +00002289/// getDecltypeForExpr - Given an expr, will return the decltype for that
2290/// expression, according to the rules in C++0x [dcl.type.simple]p4
2291static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002292 if (e->isTypeDependent())
2293 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002294
Anders Carlssonad6bd352009-06-24 21:24:56 +00002295 // If e is an id expression or a class member access, decltype(e) is defined
2296 // as the type of the entity named by e.
2297 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2298 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2299 return VD->getType();
2300 }
2301 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2302 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2303 return FD->getType();
2304 }
2305 // If e is a function call or an invocation of an overloaded operator,
2306 // (parentheses around e are ignored), decltype(e) is defined as the
2307 // return type of that function.
2308 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2309 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002310
Anders Carlssonad6bd352009-06-24 21:24:56 +00002311 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002312
2313 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002314 // defined as T&, otherwise decltype(e) is defined as T.
2315 if (e->isLvalue(Context) == Expr::LV_Valid)
2316 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002317
Anders Carlssonad6bd352009-06-24 21:24:56 +00002318 return T;
2319}
2320
Anders Carlsson81df7b82009-06-24 19:06:50 +00002321/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2322/// DecltypeType AST's. The only motivation to unique these nodes would be
2323/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002324/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002325/// on canonical type's (which are always unique).
2326QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002327 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002328 if (e->isTypeDependent()) {
2329 llvm::FoldingSetNodeID ID;
2330 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002331
Douglas Gregora21f6c32009-07-30 23:36:40 +00002332 void *InsertPos = 0;
2333 DependentDecltypeType *Canon
2334 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2335 if (Canon) {
2336 // We already have a "canonical" version of an equivalent, dependent
2337 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002338 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002339 QualType((DecltypeType*)Canon, 0));
2340 }
2341 else {
2342 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002343 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002344 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2345 dt = Canon;
2346 }
2347 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002348 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002349 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002350 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002351 Types.push_back(dt);
2352 return QualType(dt, 0);
2353}
2354
Chris Lattnerfb072462007-01-23 05:45:31 +00002355/// getTagDeclType - Return the unique reference to the type for the
2356/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002357QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002358 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002359 // FIXME: What is the design on getTagDeclType when it requires casting
2360 // away const? mutable?
2361 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002362}
2363
Mike Stump11289f42009-09-09 15:08:12 +00002364/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2365/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2366/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002367CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002368 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002369}
Chris Lattnerfb072462007-01-23 05:45:31 +00002370
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002371/// getSignedWCharType - Return the type of "signed wchar_t".
2372/// Used when in C++, as a GCC extension.
2373QualType ASTContext::getSignedWCharType() const {
2374 // FIXME: derive from "Target" ?
2375 return WCharTy;
2376}
2377
2378/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2379/// Used when in C++, as a GCC extension.
2380QualType ASTContext::getUnsignedWCharType() const {
2381 // FIXME: derive from "Target" ?
2382 return UnsignedIntTy;
2383}
2384
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002385/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2386/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2387QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002388 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002389}
2390
Chris Lattnera21ad802008-04-02 05:18:44 +00002391//===----------------------------------------------------------------------===//
2392// Type Operators
2393//===----------------------------------------------------------------------===//
2394
John McCallfc93cf92009-10-22 22:37:11 +00002395CanQualType ASTContext::getCanonicalParamType(QualType T) {
2396 // Push qualifiers into arrays, and then discard any remaining
2397 // qualifiers.
2398 T = getCanonicalType(T);
2399 const Type *Ty = T.getTypePtr();
2400
2401 QualType Result;
2402 if (isa<ArrayType>(Ty)) {
2403 Result = getArrayDecayedType(QualType(Ty,0));
2404 } else if (isa<FunctionType>(Ty)) {
2405 Result = getPointerType(QualType(Ty, 0));
2406 } else {
2407 Result = QualType(Ty, 0);
2408 }
2409
2410 return CanQualType::CreateUnsafe(Result);
2411}
2412
Chris Lattnered0d0792008-04-06 22:41:35 +00002413/// getCanonicalType - Return the canonical (structural) type corresponding to
2414/// the specified potentially non-canonical type. The non-canonical version
2415/// of a type may have many "decorated" versions of types. Decorators can
2416/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2417/// to be free of any of these, allowing two canonical types to be compared
2418/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002419CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002420 QualifierCollector Quals;
2421 const Type *Ptr = Quals.strip(T);
2422 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002423
John McCall8ccfcb52009-09-24 19:53:00 +00002424 // The canonical internal type will be the canonical type *except*
2425 // that we push type qualifiers down through array types.
2426
2427 // If there are no new qualifiers to push down, stop here.
2428 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002429 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002430
John McCall8ccfcb52009-09-24 19:53:00 +00002431 // If the type qualifiers are on an array type, get the canonical
2432 // type of the array with the qualifiers applied to the element
2433 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002434 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2435 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002436 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002437
Chris Lattner7adf0762008-08-04 07:31:14 +00002438 // Get the canonical version of the element with the extra qualifiers on it.
2439 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002440 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002441 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002442
Chris Lattner7adf0762008-08-04 07:31:14 +00002443 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002444 return CanQualType::CreateUnsafe(
2445 getConstantArrayType(NewEltTy, CAT->getSize(),
2446 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002447 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002448 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002449 return CanQualType::CreateUnsafe(
2450 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002451 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002452
Douglas Gregor4619e432008-12-05 23:32:09 +00002453 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002454 return CanQualType::CreateUnsafe(
2455 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002456 DSAT->getSizeExpr() ?
2457 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002458 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002459 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002460 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002461
Chris Lattner7adf0762008-08-04 07:31:14 +00002462 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002463 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002464 VAT->getSizeExpr() ?
2465 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002466 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002467 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002468 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002469}
2470
Chandler Carruth607f38e2009-12-29 07:16:59 +00002471QualType ASTContext::getUnqualifiedArrayType(QualType T,
2472 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002473 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002474 const ArrayType *AT = getAsArrayType(T);
2475 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002476 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002477 }
2478
Chandler Carruth607f38e2009-12-29 07:16:59 +00002479 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002480 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002481 if (Elt == UnqualElt)
2482 return T;
2483
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002484 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002485 return getConstantArrayType(UnqualElt, CAT->getSize(),
2486 CAT->getSizeModifier(), 0);
2487 }
2488
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002489 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002490 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2491 }
2492
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002493 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2494 return getVariableArrayType(UnqualElt,
2495 VAT->getSizeExpr() ?
2496 VAT->getSizeExpr()->Retain() : 0,
2497 VAT->getSizeModifier(),
2498 VAT->getIndexTypeCVRQualifiers(),
2499 VAT->getBracketsRange());
2500 }
2501
2502 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002503 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2504 DSAT->getSizeModifier(), 0,
2505 SourceRange());
2506}
2507
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002508/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2509/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2510/// they point to and return true. If T1 and T2 aren't pointer types
2511/// or pointer-to-member types, or if they are not similar at this
2512/// level, returns false and leaves T1 and T2 unchanged. Top-level
2513/// qualifiers on T1 and T2 are ignored. This function will typically
2514/// be called in a loop that successively "unwraps" pointer and
2515/// pointer-to-member types to compare them at each level.
2516bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2517 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2518 *T2PtrType = T2->getAs<PointerType>();
2519 if (T1PtrType && T2PtrType) {
2520 T1 = T1PtrType->getPointeeType();
2521 T2 = T2PtrType->getPointeeType();
2522 return true;
2523 }
2524
2525 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2526 *T2MPType = T2->getAs<MemberPointerType>();
2527 if (T1MPType && T2MPType &&
2528 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2529 QualType(T2MPType->getClass(), 0))) {
2530 T1 = T1MPType->getPointeeType();
2531 T2 = T2MPType->getPointeeType();
2532 return true;
2533 }
2534
2535 if (getLangOptions().ObjC1) {
2536 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2537 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2538 if (T1OPType && T2OPType) {
2539 T1 = T1OPType->getPointeeType();
2540 T2 = T2OPType->getPointeeType();
2541 return true;
2542 }
2543 }
2544
2545 // FIXME: Block pointers, too?
2546
2547 return false;
2548}
2549
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002550DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name,
2551 SourceLocation NameLoc) {
John McCall847e2a12009-11-24 18:42:40 +00002552 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002553 // DNInfo work in progress: CHECKME: what about DNLoc?
2554 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2555
John McCall847e2a12009-11-24 18:42:40 +00002556 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002557 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002558 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002559 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2560 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002561 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002562 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2563 // DNInfo work in progress: FIXME: source locations?
2564 DeclarationNameLoc DNLoc;
2565 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2566 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2567 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002568 }
2569 }
2570
John McCalld28ae272009-12-02 08:04:21 +00002571 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2572 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002573 // DNInfo work in progress: CHECKME: what about DNLoc?
2574 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002575}
2576
Douglas Gregor6bc50582009-05-07 06:41:52 +00002577TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002578 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2579 if (TemplateTemplateParmDecl *TTP
2580 = dyn_cast<TemplateTemplateParmDecl>(Template))
2581 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2582
2583 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002584 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002585 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002586
John McCalld28ae272009-12-02 08:04:21 +00002587 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002588
Douglas Gregor6bc50582009-05-07 06:41:52 +00002589 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2590 assert(DTN && "Non-dependent template names must refer to template decls.");
2591 return DTN->CanonicalTemplateName;
2592}
2593
Douglas Gregoradee3e32009-11-11 23:06:43 +00002594bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2595 X = getCanonicalTemplateName(X);
2596 Y = getCanonicalTemplateName(Y);
2597 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2598}
2599
Mike Stump11289f42009-09-09 15:08:12 +00002600TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002601ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2602 switch (Arg.getKind()) {
2603 case TemplateArgument::Null:
2604 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002605
Douglas Gregora8e02e72009-07-28 23:00:59 +00002606 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002607 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002608
Douglas Gregora8e02e72009-07-28 23:00:59 +00002609 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002610 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002611
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002612 case TemplateArgument::Template:
2613 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2614
Douglas Gregora8e02e72009-07-28 23:00:59 +00002615 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002616 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002617 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002618
Douglas Gregora8e02e72009-07-28 23:00:59 +00002619 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002620 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002621
Douglas Gregora8e02e72009-07-28 23:00:59 +00002622 case TemplateArgument::Pack: {
2623 // FIXME: Allocate in ASTContext
2624 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2625 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002626 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002627 AEnd = Arg.pack_end();
2628 A != AEnd; (void)++A, ++Idx)
2629 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002630
Douglas Gregora8e02e72009-07-28 23:00:59 +00002631 TemplateArgument Result;
2632 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2633 return Result;
2634 }
2635 }
2636
2637 // Silence GCC warning
2638 assert(false && "Unhandled template argument kind");
2639 return TemplateArgument();
2640}
2641
Douglas Gregor333489b2009-03-27 23:10:48 +00002642NestedNameSpecifier *
2643ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002644 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002645 return 0;
2646
2647 switch (NNS->getKind()) {
2648 case NestedNameSpecifier::Identifier:
2649 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002650 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002651 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2652 NNS->getAsIdentifier());
2653
2654 case NestedNameSpecifier::Namespace:
2655 // A namespace is canonical; build a nested-name-specifier with
2656 // this namespace and no prefix.
2657 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2658
2659 case NestedNameSpecifier::TypeSpec:
2660 case NestedNameSpecifier::TypeSpecWithTemplate: {
2661 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002662 return NestedNameSpecifier::Create(*this, 0,
2663 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002664 T.getTypePtr());
2665 }
2666
2667 case NestedNameSpecifier::Global:
2668 // The global specifier is canonical and unique.
2669 return NNS;
2670 }
2671
2672 // Required to silence a GCC warning
2673 return 0;
2674}
2675
Chris Lattner7adf0762008-08-04 07:31:14 +00002676
2677const ArrayType *ASTContext::getAsArrayType(QualType T) {
2678 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002679 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002680 // Handle the common positive case fast.
2681 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2682 return AT;
2683 }
Mike Stump11289f42009-09-09 15:08:12 +00002684
John McCall8ccfcb52009-09-24 19:53:00 +00002685 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002686 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002687 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002688 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002689
John McCall8ccfcb52009-09-24 19:53:00 +00002690 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002691 // implements C99 6.7.3p8: "If the specification of an array type includes
2692 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002693
Chris Lattner7adf0762008-08-04 07:31:14 +00002694 // If we get here, we either have type qualifiers on the type, or we have
2695 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002696 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002697
John McCall8ccfcb52009-09-24 19:53:00 +00002698 QualifierCollector Qs;
2699 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002700
Chris Lattner7adf0762008-08-04 07:31:14 +00002701 // If we have a simple case, just return now.
2702 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002703 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002704 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002705
Chris Lattner7adf0762008-08-04 07:31:14 +00002706 // Otherwise, we have an array and we have qualifiers on it. Push the
2707 // qualifiers into the array element type and return a new array type.
2708 // Get the canonical version of the element with the extra qualifiers on it.
2709 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002710 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002711
Chris Lattner7adf0762008-08-04 07:31:14 +00002712 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2713 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2714 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002715 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002716 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2717 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2718 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002719 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002720
Mike Stump11289f42009-09-09 15:08:12 +00002721 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002722 = dyn_cast<DependentSizedArrayType>(ATy))
2723 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002724 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002725 DSAT->getSizeExpr() ?
2726 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002727 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002728 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002729 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002730
Chris Lattner7adf0762008-08-04 07:31:14 +00002731 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002732 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002733 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002734 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002735 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002736 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002737 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002738}
2739
2740
Chris Lattnera21ad802008-04-02 05:18:44 +00002741/// getArrayDecayedType - Return the properly qualified result of decaying the
2742/// specified array type to a pointer. This operation is non-trivial when
2743/// handling typedefs etc. The canonical type of "T" must be an array type,
2744/// this returns a pointer to a properly qualified element of the array.
2745///
2746/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2747QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002748 // Get the element type with 'getAsArrayType' so that we don't lose any
2749 // typedefs in the element type of the array. This also handles propagation
2750 // of type qualifiers from the array type into the element type if present
2751 // (C99 6.7.3p8).
2752 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2753 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002754
Chris Lattner7adf0762008-08-04 07:31:14 +00002755 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002756
2757 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002758 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002759}
2760
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002761QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002762 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002763 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2764 QT = AT->getElementType();
2765 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002766}
2767
Anders Carlsson4bf82142009-09-25 01:23:32 +00002768QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2769 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002770
Anders Carlsson4bf82142009-09-25 01:23:32 +00002771 if (const ArrayType *AT = getAsArrayType(ElemTy))
2772 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002773
Anders Carlssone0808df2008-12-21 03:44:36 +00002774 return ElemTy;
2775}
2776
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002777/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002778uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002779ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2780 uint64_t ElementCount = 1;
2781 do {
2782 ElementCount *= CA->getSize().getZExtValue();
2783 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2784 } while (CA);
2785 return ElementCount;
2786}
2787
Steve Naroff0af91202007-04-27 21:51:21 +00002788/// getFloatingRank - Return a relative rank for floating point types.
2789/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002790static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002791 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002792 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002793
John McCall9dd450b2009-09-21 23:43:11 +00002794 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2795 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002796 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002797 case BuiltinType::Float: return FloatRank;
2798 case BuiltinType::Double: return DoubleRank;
2799 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002800 }
2801}
2802
Mike Stump11289f42009-09-09 15:08:12 +00002803/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2804/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002805/// 'typeDomain' is a real floating point or complex type.
2806/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002807QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2808 QualType Domain) const {
2809 FloatingRank EltRank = getFloatingRank(Size);
2810 if (Domain->isComplexType()) {
2811 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002812 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002813 case FloatRank: return FloatComplexTy;
2814 case DoubleRank: return DoubleComplexTy;
2815 case LongDoubleRank: return LongDoubleComplexTy;
2816 }
Steve Naroff0af91202007-04-27 21:51:21 +00002817 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002818
2819 assert(Domain->isRealFloatingType() && "Unknown domain!");
2820 switch (EltRank) {
2821 default: assert(0 && "getFloatingRank(): illegal value for rank");
2822 case FloatRank: return FloatTy;
2823 case DoubleRank: return DoubleTy;
2824 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002825 }
Steve Naroffe4718892007-04-27 18:30:00 +00002826}
2827
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002828/// getFloatingTypeOrder - Compare the rank of the two specified floating
2829/// point types, ignoring the domain of the type (i.e. 'double' ==
2830/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002831/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002832int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2833 FloatingRank LHSR = getFloatingRank(LHS);
2834 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002835
Chris Lattnerb90739d2008-04-06 23:38:49 +00002836 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002837 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002838 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002839 return 1;
2840 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002841}
2842
Chris Lattner76a00cf2008-04-06 22:59:24 +00002843/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2844/// routine will assert if passed a built-in type that isn't an integer or enum,
2845/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002846unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002847 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002848 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002849 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002850
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002851 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2852 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2853
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002854 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2855 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2856
2857 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2858 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2859
Chris Lattner76a00cf2008-04-06 22:59:24 +00002860 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002861 default: assert(0 && "getIntegerRank(): not a built-in integer");
2862 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002863 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002864 case BuiltinType::Char_S:
2865 case BuiltinType::Char_U:
2866 case BuiltinType::SChar:
2867 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002868 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002869 case BuiltinType::Short:
2870 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002871 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002872 case BuiltinType::Int:
2873 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002874 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002875 case BuiltinType::Long:
2876 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002877 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002878 case BuiltinType::LongLong:
2879 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002880 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002881 case BuiltinType::Int128:
2882 case BuiltinType::UInt128:
2883 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002884 }
2885}
2886
Eli Friedman629ffb92009-08-20 04:21:42 +00002887/// \brief Whether this is a promotable bitfield reference according
2888/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2889///
2890/// \returns the type this bit-field will promote to, or NULL if no
2891/// promotion occurs.
2892QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00002893 if (E->isTypeDependent() || E->isValueDependent())
2894 return QualType();
2895
Eli Friedman629ffb92009-08-20 04:21:42 +00002896 FieldDecl *Field = E->getBitField();
2897 if (!Field)
2898 return QualType();
2899
2900 QualType FT = Field->getType();
2901
2902 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2903 uint64_t BitWidth = BitWidthAP.getZExtValue();
2904 uint64_t IntSize = getTypeSize(IntTy);
2905 // GCC extension compatibility: if the bit-field size is less than or equal
2906 // to the size of int, it gets promoted no matter what its type is.
2907 // For instance, unsigned long bf : 4 gets promoted to signed int.
2908 if (BitWidth < IntSize)
2909 return IntTy;
2910
2911 if (BitWidth == IntSize)
2912 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2913
2914 // Types bigger than int are not subject to promotions, and therefore act
2915 // like the base type.
2916 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2917 // is ridiculous.
2918 return QualType();
2919}
2920
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002921/// getPromotedIntegerType - Returns the type that Promotable will
2922/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2923/// integer type.
2924QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2925 assert(!Promotable.isNull());
2926 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002927 if (const EnumType *ET = Promotable->getAs<EnumType>())
2928 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002929 if (Promotable->isSignedIntegerType())
2930 return IntTy;
2931 uint64_t PromotableSize = getTypeSize(Promotable);
2932 uint64_t IntSize = getTypeSize(IntTy);
2933 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2934 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2935}
2936
Mike Stump11289f42009-09-09 15:08:12 +00002937/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002938/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002939/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002940int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002941 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2942 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002943 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002944
Chris Lattner76a00cf2008-04-06 22:59:24 +00002945 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2946 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002947
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002948 unsigned LHSRank = getIntegerRank(LHSC);
2949 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002950
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002951 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2952 if (LHSRank == RHSRank) return 0;
2953 return LHSRank > RHSRank ? 1 : -1;
2954 }
Mike Stump11289f42009-09-09 15:08:12 +00002955
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002956 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2957 if (LHSUnsigned) {
2958 // If the unsigned [LHS] type is larger, return it.
2959 if (LHSRank >= RHSRank)
2960 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002961
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002962 // If the signed type can represent all values of the unsigned type, it
2963 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002964 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002965 return -1;
2966 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002967
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002968 // If the unsigned [RHS] type is larger, return it.
2969 if (RHSRank >= LHSRank)
2970 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002971
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002972 // If the signed type can represent all values of the unsigned type, it
2973 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002974 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002975 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002976}
Anders Carlsson98f07902007-08-17 05:31:46 +00002977
Anders Carlsson6d417272009-11-14 21:45:58 +00002978static RecordDecl *
2979CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2980 SourceLocation L, IdentifierInfo *Id) {
2981 if (Ctx.getLangOptions().CPlusPlus)
2982 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2983 else
2984 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2985}
2986
Mike Stump11289f42009-09-09 15:08:12 +00002987// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002988QualType ASTContext::getCFConstantStringType() {
2989 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002990 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002991 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002992 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002993 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002994
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002995 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002996
Anders Carlsson98f07902007-08-17 05:31:46 +00002997 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002998 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002999 // int flags;
3000 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003001 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003002 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003003 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003004 FieldTypes[3] = LongTy;
3005
Anders Carlsson98f07902007-08-17 05:31:46 +00003006 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003007 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003008 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003009 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003010 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003011 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003012 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003013 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003014 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003015 }
3016
Douglas Gregord5058122010-02-11 01:19:42 +00003017 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003018 }
Mike Stump11289f42009-09-09 15:08:12 +00003019
Anders Carlsson98f07902007-08-17 05:31:46 +00003020 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003021}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003022
Douglas Gregor512b0772009-04-23 22:29:11 +00003023void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003024 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003025 assert(Rec && "Invalid CFConstantStringType");
3026 CFConstantStringTypeDecl = Rec->getDecl();
3027}
3028
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003029// getNSConstantStringType - Return the type used for constant NSStrings.
3030QualType ASTContext::getNSConstantStringType() {
3031 if (!NSConstantStringTypeDecl) {
3032 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003033 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003034 &Idents.get("__builtin_NSString"));
3035 NSConstantStringTypeDecl->startDefinition();
3036
3037 QualType FieldTypes[3];
3038
3039 // const int *isa;
3040 FieldTypes[0] = getPointerType(IntTy.withConst());
3041 // const char *str;
3042 FieldTypes[1] = getPointerType(CharTy.withConst());
3043 // unsigned int length;
3044 FieldTypes[2] = UnsignedIntTy;
3045
3046 // Create fields
3047 for (unsigned i = 0; i < 3; ++i) {
3048 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3049 SourceLocation(), 0,
3050 FieldTypes[i], /*TInfo=*/0,
3051 /*BitWidth=*/0,
3052 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003053 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003054 NSConstantStringTypeDecl->addDecl(Field);
3055 }
3056
3057 NSConstantStringTypeDecl->completeDefinition();
3058 }
3059
3060 return getTagDeclType(NSConstantStringTypeDecl);
3061}
3062
3063void ASTContext::setNSConstantStringType(QualType T) {
3064 const RecordType *Rec = T->getAs<RecordType>();
3065 assert(Rec && "Invalid NSConstantStringType");
3066 NSConstantStringTypeDecl = Rec->getDecl();
3067}
3068
Mike Stump11289f42009-09-09 15:08:12 +00003069QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003070 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003071 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003072 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003073 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003074 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003075
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003076 QualType FieldTypes[] = {
3077 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003078 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003079 getPointerType(UnsignedLongTy),
3080 getConstantArrayType(UnsignedLongTy,
3081 llvm::APInt(32, 5), ArrayType::Normal, 0)
3082 };
Mike Stump11289f42009-09-09 15:08:12 +00003083
Douglas Gregor91f84212008-12-11 16:49:14 +00003084 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003085 FieldDecl *Field = FieldDecl::Create(*this,
3086 ObjCFastEnumerationStateTypeDecl,
3087 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003088 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003089 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003090 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003091 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003092 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003093 }
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003094 if (getLangOptions().CPlusPlus)
Fariborz Jahanianc77f0f32010-05-27 16:35:00 +00003095 if (CXXRecordDecl *CXXRD =
3096 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003097 CXXRD->setEmpty(false);
Mike Stump11289f42009-09-09 15:08:12 +00003098
Douglas Gregord5058122010-02-11 01:19:42 +00003099 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003100 }
Mike Stump11289f42009-09-09 15:08:12 +00003101
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003102 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3103}
3104
Mike Stumpd0153282009-10-20 02:12:22 +00003105QualType ASTContext::getBlockDescriptorType() {
3106 if (BlockDescriptorType)
3107 return getTagDeclType(BlockDescriptorType);
3108
3109 RecordDecl *T;
3110 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003111 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003112 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003113 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003114
3115 QualType FieldTypes[] = {
3116 UnsignedLongTy,
3117 UnsignedLongTy,
3118 };
3119
3120 const char *FieldNames[] = {
3121 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003122 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003123 };
3124
3125 for (size_t i = 0; i < 2; ++i) {
3126 FieldDecl *Field = FieldDecl::Create(*this,
3127 T,
3128 SourceLocation(),
3129 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003130 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003131 /*BitWidth=*/0,
3132 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003133 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003134 T->addDecl(Field);
3135 }
3136
Douglas Gregord5058122010-02-11 01:19:42 +00003137 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003138
3139 BlockDescriptorType = T;
3140
3141 return getTagDeclType(BlockDescriptorType);
3142}
3143
3144void ASTContext::setBlockDescriptorType(QualType T) {
3145 const RecordType *Rec = T->getAs<RecordType>();
3146 assert(Rec && "Invalid BlockDescriptorType");
3147 BlockDescriptorType = Rec->getDecl();
3148}
3149
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003150QualType ASTContext::getBlockDescriptorExtendedType() {
3151 if (BlockDescriptorExtendedType)
3152 return getTagDeclType(BlockDescriptorExtendedType);
3153
3154 RecordDecl *T;
3155 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003156 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003157 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003158 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003159
3160 QualType FieldTypes[] = {
3161 UnsignedLongTy,
3162 UnsignedLongTy,
3163 getPointerType(VoidPtrTy),
3164 getPointerType(VoidPtrTy)
3165 };
3166
3167 const char *FieldNames[] = {
3168 "reserved",
3169 "Size",
3170 "CopyFuncPtr",
3171 "DestroyFuncPtr"
3172 };
3173
3174 for (size_t i = 0; i < 4; ++i) {
3175 FieldDecl *Field = FieldDecl::Create(*this,
3176 T,
3177 SourceLocation(),
3178 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003179 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003180 /*BitWidth=*/0,
3181 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003182 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003183 T->addDecl(Field);
3184 }
3185
Douglas Gregord5058122010-02-11 01:19:42 +00003186 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003187
3188 BlockDescriptorExtendedType = T;
3189
3190 return getTagDeclType(BlockDescriptorExtendedType);
3191}
3192
3193void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3194 const RecordType *Rec = T->getAs<RecordType>();
3195 assert(Rec && "Invalid BlockDescriptorType");
3196 BlockDescriptorExtendedType = Rec->getDecl();
3197}
3198
Mike Stump94967902009-10-21 18:16:27 +00003199bool ASTContext::BlockRequiresCopying(QualType Ty) {
3200 if (Ty->isBlockPointerType())
3201 return true;
3202 if (isObjCNSObjectType(Ty))
3203 return true;
3204 if (Ty->isObjCObjectPointerType())
3205 return true;
3206 return false;
3207}
3208
Daniel Dunbar56df9772010-08-17 22:39:59 +00003209QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) {
Mike Stump94967902009-10-21 18:16:27 +00003210 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003211 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003212 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003213 // unsigned int __flags;
3214 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003215 // void *__copy_helper; // as needed
3216 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003217 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003218 // } *
3219
Mike Stump94967902009-10-21 18:16:27 +00003220 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3221
3222 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003223 llvm::SmallString<36> Name;
3224 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3225 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003226 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003227 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003228 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003229 T->startDefinition();
3230 QualType Int32Ty = IntTy;
3231 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3232 QualType FieldTypes[] = {
3233 getPointerType(VoidPtrTy),
3234 getPointerType(getTagDeclType(T)),
3235 Int32Ty,
3236 Int32Ty,
3237 getPointerType(VoidPtrTy),
3238 getPointerType(VoidPtrTy),
3239 Ty
3240 };
3241
Daniel Dunbar56df9772010-08-17 22:39:59 +00003242 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003243 "__isa",
3244 "__forwarding",
3245 "__flags",
3246 "__size",
3247 "__copy_helper",
3248 "__destroy_helper",
3249 DeclName,
3250 };
3251
3252 for (size_t i = 0; i < 7; ++i) {
3253 if (!HasCopyAndDispose && i >=4 && i <= 5)
3254 continue;
3255 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3256 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003257 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003258 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003259 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003260 T->addDecl(Field);
3261 }
3262
Douglas Gregord5058122010-02-11 01:19:42 +00003263 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003264
3265 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003266}
3267
3268
3269QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003270 bool BlockHasCopyDispose,
John McCall87fe5d52010-05-20 01:18:31 +00003271 llvm::SmallVectorImpl<const Expr *> &Layout) {
3272
Mike Stumpd0153282009-10-20 02:12:22 +00003273 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003274 llvm::SmallString<36> Name;
3275 llvm::raw_svector_ostream(Name) << "__block_literal_"
3276 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003277 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003278 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003279 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003280 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003281 QualType FieldTypes[] = {
3282 getPointerType(VoidPtrTy),
3283 IntTy,
3284 IntTy,
3285 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003286 (BlockHasCopyDispose ?
3287 getPointerType(getBlockDescriptorExtendedType()) :
3288 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003289 };
3290
3291 const char *FieldNames[] = {
3292 "__isa",
3293 "__flags",
3294 "__reserved",
3295 "__FuncPtr",
3296 "__descriptor"
3297 };
3298
3299 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003300 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003301 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003302 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003303 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003304 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003305 T->addDecl(Field);
3306 }
3307
John McCall87fe5d52010-05-20 01:18:31 +00003308 for (unsigned i = 0; i < Layout.size(); ++i) {
3309 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003310
John McCall87fe5d52010-05-20 01:18:31 +00003311 QualType FieldType = E->getType();
3312 IdentifierInfo *FieldName = 0;
3313 if (isa<CXXThisExpr>(E)) {
3314 FieldName = &Idents.get("this");
3315 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3316 const ValueDecl *D = BDRE->getDecl();
3317 FieldName = D->getIdentifier();
3318 if (BDRE->isByRef())
Daniel Dunbar56df9772010-08-17 22:39:59 +00003319 FieldType = BuildByRefType(D->getName(), FieldType);
John McCall87fe5d52010-05-20 01:18:31 +00003320 } else {
3321 // Padding.
3322 assert(isa<ConstantArrayType>(FieldType) &&
3323 isa<DeclRefExpr>(E) &&
3324 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3325 "doesn't match characteristics of padding decl");
3326 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003327
3328 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003329 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003330 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003331 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003332 T->addDecl(Field);
3333 }
3334
Douglas Gregord5058122010-02-11 01:19:42 +00003335 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003336
3337 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003338}
3339
Douglas Gregor512b0772009-04-23 22:29:11 +00003340void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003341 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003342 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3343 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3344}
3345
Anders Carlsson18acd442007-10-29 06:33:42 +00003346// This returns true if a type has been typedefed to BOOL:
3347// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003348static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003349 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003350 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3351 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003352
Anders Carlssond8499822007-10-29 05:01:08 +00003353 return false;
3354}
3355
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003356/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003357/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003358CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003359 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003360
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003361 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003362 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003363 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003364 // Treat arrays as pointers, since that's how they're passed in.
3365 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003366 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003367 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003368}
3369
3370static inline
3371std::string charUnitsToString(const CharUnits &CU) {
3372 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003373}
3374
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003375/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003376/// declaration.
3377void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3378 std::string& S) {
3379 const BlockDecl *Decl = Expr->getBlockDecl();
3380 QualType BlockTy =
3381 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3382 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003383 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003384 // Compute size of all parameters.
3385 // Start with computing size of a pointer in number of bytes.
3386 // FIXME: There might(should) be a better way of doing this computation!
3387 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003388 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3389 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003390 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003391 E = Decl->param_end(); PI != E; ++PI) {
3392 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003393 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003394 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003395 ParmOffset += sz;
3396 }
3397 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003398 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003399 // Block pointer and offset.
3400 S += "@?0";
3401 ParmOffset = PtrSize;
3402
3403 // Argument types.
3404 ParmOffset = PtrSize;
3405 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3406 Decl->param_end(); PI != E; ++PI) {
3407 ParmVarDecl *PVDecl = *PI;
3408 QualType PType = PVDecl->getOriginalType();
3409 if (const ArrayType *AT =
3410 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3411 // Use array's original type only if it has known number of
3412 // elements.
3413 if (!isa<ConstantArrayType>(AT))
3414 PType = PVDecl->getType();
3415 } else if (PType->isFunctionType())
3416 PType = PVDecl->getType();
3417 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003418 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003419 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003420 }
3421}
3422
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003423/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003424/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003425void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003426 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003427 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003428 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003429 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003430 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003431 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003432 // Compute size of all parameters.
3433 // Start with computing size of a pointer in number of bytes.
3434 // FIXME: There might(should) be a better way of doing this computation!
3435 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003436 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003437 // The first two arguments (self and _cmd) are pointers; account for
3438 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003439 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003440 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003441 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003442 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003443 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003444 assert (sz.isPositive() &&
3445 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003446 ParmOffset += sz;
3447 }
Ken Dyck40775002010-01-11 17:06:35 +00003448 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003449 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003450 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003451
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003452 // Argument types.
3453 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003454 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003455 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003456 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003457 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003458 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003459 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3460 // Use array's original type only if it has known number of
3461 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003462 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003463 PType = PVDecl->getType();
3464 } else if (PType->isFunctionType())
3465 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003466 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003467 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003468 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003469 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003470 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003471 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003472 }
3473}
3474
Daniel Dunbar4932b362008-08-28 04:38:10 +00003475/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003476/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003477/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3478/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003479/// Property attributes are stored as a comma-delimited C string. The simple
3480/// attributes readonly and bycopy are encoded as single characters. The
3481/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3482/// encoded as single characters, followed by an identifier. Property types
3483/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003484/// these attributes are defined by the following enumeration:
3485/// @code
3486/// enum PropertyAttributes {
3487/// kPropertyReadOnly = 'R', // property is read-only.
3488/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3489/// kPropertyByref = '&', // property is a reference to the value last assigned
3490/// kPropertyDynamic = 'D', // property is dynamic
3491/// kPropertyGetter = 'G', // followed by getter selector name
3492/// kPropertySetter = 'S', // followed by setter selector name
3493/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3494/// kPropertyType = 't' // followed by old-style type encoding.
3495/// kPropertyWeak = 'W' // 'weak' property
3496/// kPropertyStrong = 'P' // property GC'able
3497/// kPropertyNonAtomic = 'N' // property non-atomic
3498/// };
3499/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003500void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003501 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003502 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003503 // Collect information from the property implementation decl(s).
3504 bool Dynamic = false;
3505 ObjCPropertyImplDecl *SynthesizePID = 0;
3506
3507 // FIXME: Duplicated code due to poor abstraction.
3508 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003509 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003510 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3511 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003512 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003513 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003514 ObjCPropertyImplDecl *PID = *i;
3515 if (PID->getPropertyDecl() == PD) {
3516 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3517 Dynamic = true;
3518 } else {
3519 SynthesizePID = PID;
3520 }
3521 }
3522 }
3523 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003524 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003525 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003526 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003527 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003528 ObjCPropertyImplDecl *PID = *i;
3529 if (PID->getPropertyDecl() == PD) {
3530 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3531 Dynamic = true;
3532 } else {
3533 SynthesizePID = PID;
3534 }
3535 }
Mike Stump11289f42009-09-09 15:08:12 +00003536 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003537 }
3538 }
3539
3540 // FIXME: This is not very efficient.
3541 S = "T";
3542
3543 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003544 // GCC has some special rules regarding encoding of properties which
3545 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003546 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003547 true /* outermost type */,
3548 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003549
3550 if (PD->isReadOnly()) {
3551 S += ",R";
3552 } else {
3553 switch (PD->getSetterKind()) {
3554 case ObjCPropertyDecl::Assign: break;
3555 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003556 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003557 }
3558 }
3559
3560 // It really isn't clear at all what this means, since properties
3561 // are "dynamic by default".
3562 if (Dynamic)
3563 S += ",D";
3564
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003565 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3566 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003567
Daniel Dunbar4932b362008-08-28 04:38:10 +00003568 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3569 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003570 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003571 }
3572
3573 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3574 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003575 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003576 }
3577
3578 if (SynthesizePID) {
3579 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3580 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003581 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003582 }
3583
3584 // FIXME: OBJCGC: weak & strong
3585}
3586
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003587/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003588/// Another legacy compatibility encoding: 32-bit longs are encoded as
3589/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003590/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3591///
3592void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003593 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003594 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003595 if (BT->getKind() == BuiltinType::ULong &&
3596 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003597 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003598 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003599 if (BT->getKind() == BuiltinType::Long &&
3600 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003601 PointeeTy = IntTy;
3602 }
3603 }
3604}
3605
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003606void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003607 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003608 // We follow the behavior of gcc, expanding structures which are
3609 // directly pointed to, and expanding embedded structures. Note that
3610 // these rules are sufficient to prevent recursive encoding of the
3611 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003612 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003613 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003614}
3615
David Chisnallb190a2c2010-06-04 01:10:52 +00003616static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3617 switch (T->getAs<BuiltinType>()->getKind()) {
3618 default: assert(0 && "Unhandled builtin type kind");
3619 case BuiltinType::Void: return 'v';
3620 case BuiltinType::Bool: return 'B';
3621 case BuiltinType::Char_U:
3622 case BuiltinType::UChar: return 'C';
3623 case BuiltinType::UShort: return 'S';
3624 case BuiltinType::UInt: return 'I';
3625 case BuiltinType::ULong:
3626 return
3627 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3628 case BuiltinType::UInt128: return 'T';
3629 case BuiltinType::ULongLong: return 'Q';
3630 case BuiltinType::Char_S:
3631 case BuiltinType::SChar: return 'c';
3632 case BuiltinType::Short: return 's';
John McCalldad856d2010-06-11 10:11:05 +00003633 case BuiltinType::WChar:
David Chisnallb190a2c2010-06-04 01:10:52 +00003634 case BuiltinType::Int: return 'i';
3635 case BuiltinType::Long:
3636 return
3637 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3638 case BuiltinType::LongLong: return 'q';
3639 case BuiltinType::Int128: return 't';
3640 case BuiltinType::Float: return 'f';
3641 case BuiltinType::Double: return 'd';
3642 case BuiltinType::LongDouble: return 'd';
3643 }
3644}
3645
Mike Stump11289f42009-09-09 15:08:12 +00003646static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003647 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003648 const Expr *E = FD->getBitWidth();
3649 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3650 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003651 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003652 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3653 // The GNU runtime requires more information; bitfields are encoded as b,
3654 // then the offset (in bits) of the first element, then the type of the
3655 // bitfield, then the size in bits. For example, in this structure:
3656 //
3657 // struct
3658 // {
3659 // int integer;
3660 // int flags:2;
3661 // };
3662 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3663 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3664 // information is not especially sensible, but we're stuck with it for
3665 // compatibility with GCC, although providing it breaks anything that
3666 // actually uses runtime introspection and wants to work on both runtimes...
3667 if (!Ctx->getLangOptions().NeXTRuntime) {
3668 const RecordDecl *RD = FD->getParent();
3669 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3670 // FIXME: This same linear search is also used in ExprConstant - it might
3671 // be better if the FieldDecl stored its offset. We'd be increasing the
3672 // size of the object slightly, but saving some time every time it is used.
3673 unsigned i = 0;
3674 for (RecordDecl::field_iterator Field = RD->field_begin(),
3675 FieldEnd = RD->field_end();
3676 Field != FieldEnd; (void)++Field, ++i) {
3677 if (*Field == FD)
3678 break;
3679 }
3680 S += llvm::utostr(RL.getFieldOffset(i));
3681 S += ObjCEncodingForPrimitiveKind(Context, T);
3682 }
3683 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003684 S += llvm::utostr(N);
3685}
3686
Daniel Dunbar07d07852009-10-18 21:17:35 +00003687// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003688void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3689 bool ExpandPointedToStructures,
3690 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003691 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003692 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003693 bool EncodingProperty) {
David Chisnallb190a2c2010-06-04 01:10:52 +00003694 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003695 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003696 return EncodeBitField(this, S, T, FD);
3697 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003698 return;
3699 }
Mike Stump11289f42009-09-09 15:08:12 +00003700
John McCall9dd450b2009-09-21 23:43:11 +00003701 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003702 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003703 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003704 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003705 return;
3706 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003707
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003708 // encoding for pointer or r3eference types.
3709 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003710 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003711 if (PT->isObjCSelType()) {
3712 S += ':';
3713 return;
3714 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003715 PointeeTy = PT->getPointeeType();
3716 }
3717 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3718 PointeeTy = RT->getPointeeType();
3719 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003720 bool isReadOnly = false;
3721 // For historical/compatibility reasons, the read-only qualifier of the
3722 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3723 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003724 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003725 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003726 if (OutermostType && T.isConstQualified()) {
3727 isReadOnly = true;
3728 S += 'r';
3729 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003730 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003731 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003732 while (P->getAs<PointerType>())
3733 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003734 if (P.isConstQualified()) {
3735 isReadOnly = true;
3736 S += 'r';
3737 }
3738 }
3739 if (isReadOnly) {
3740 // Another legacy compatibility encoding. Some ObjC qualifier and type
3741 // combinations need to be rearranged.
3742 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003743 if (llvm::StringRef(S).endswith("nr"))
3744 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003745 }
Mike Stump11289f42009-09-09 15:08:12 +00003746
Anders Carlssond8499822007-10-29 05:01:08 +00003747 if (PointeeTy->isCharType()) {
3748 // char pointer types should be encoded as '*' unless it is a
3749 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003750 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003751 S += '*';
3752 return;
3753 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003754 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003755 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3756 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3757 S += '#';
3758 return;
3759 }
3760 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3761 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3762 S += '@';
3763 return;
3764 }
3765 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003766 }
Anders Carlssond8499822007-10-29 05:01:08 +00003767 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003768 getLegacyIntegralTypeEncoding(PointeeTy);
3769
Mike Stump11289f42009-09-09 15:08:12 +00003770 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003771 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003772 return;
3773 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003774
Chris Lattnere7cabb92009-07-13 00:10:46 +00003775 if (const ArrayType *AT =
3776 // Ignore type qualifiers etc.
3777 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003778 if (isa<IncompleteArrayType>(AT)) {
3779 // Incomplete arrays are encoded as a pointer to the array element.
3780 S += '^';
3781
Mike Stump11289f42009-09-09 15:08:12 +00003782 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003783 false, ExpandStructures, FD);
3784 } else {
3785 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003786
Anders Carlssond05f44b2009-02-22 01:38:57 +00003787 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3788 S += llvm::utostr(CAT->getSize().getZExtValue());
3789 else {
3790 //Variable length arrays are encoded as a regular array with 0 elements.
3791 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3792 S += '0';
3793 }
Mike Stump11289f42009-09-09 15:08:12 +00003794
3795 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003796 false, ExpandStructures, FD);
3797 S += ']';
3798 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003799 return;
3800 }
Mike Stump11289f42009-09-09 15:08:12 +00003801
John McCall9dd450b2009-09-21 23:43:11 +00003802 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003803 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003804 return;
3805 }
Mike Stump11289f42009-09-09 15:08:12 +00003806
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003807 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003808 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003809 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003810 // Anonymous structures print as '?'
3811 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3812 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003813 if (ClassTemplateSpecializationDecl *Spec
3814 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3815 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3816 std::string TemplateArgsStr
3817 = TemplateSpecializationType::PrintTemplateArgumentList(
3818 TemplateArgs.getFlatArgumentList(),
3819 TemplateArgs.flat_size(),
3820 (*this).PrintingPolicy);
3821
3822 S += TemplateArgsStr;
3823 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003824 } else {
3825 S += '?';
3826 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003827 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003828 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003829 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3830 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003831 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003832 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003833 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003834 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003835 S += '"';
3836 }
Mike Stump11289f42009-09-09 15:08:12 +00003837
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003838 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003839 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003840 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003841 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003842 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003843 QualType qt = Field->getType();
3844 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003845 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003846 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003847 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003848 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003849 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003850 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003851 return;
3852 }
Mike Stump11289f42009-09-09 15:08:12 +00003853
Chris Lattnere7cabb92009-07-13 00:10:46 +00003854 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003855 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003856 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003857 else
3858 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003859 return;
3860 }
Mike Stump11289f42009-09-09 15:08:12 +00003861
Chris Lattnere7cabb92009-07-13 00:10:46 +00003862 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003863 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003864 return;
3865 }
Mike Stump11289f42009-09-09 15:08:12 +00003866
John McCall8b07ec22010-05-15 11:32:37 +00003867 // Ignore protocol qualifiers when mangling at this level.
3868 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3869 T = OT->getBaseType();
3870
John McCall8ccfcb52009-09-24 19:53:00 +00003871 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003872 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003873 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003874 S += '{';
3875 const IdentifierInfo *II = OI->getIdentifier();
3876 S += II->getName();
3877 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00003878 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
3879 DeepCollectObjCIvars(OI, true, Ivars);
3880 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
3881 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
3882 if (Field->isBitField())
3883 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003884 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00003885 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003886 }
3887 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003888 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003889 }
Mike Stump11289f42009-09-09 15:08:12 +00003890
John McCall9dd450b2009-09-21 23:43:11 +00003891 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003892 if (OPT->isObjCIdType()) {
3893 S += '@';
3894 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003895 }
Mike Stump11289f42009-09-09 15:08:12 +00003896
Steve Narofff0c86112009-10-28 22:03:49 +00003897 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3898 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3899 // Since this is a binary compatibility issue, need to consult with runtime
3900 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003901 S += '#';
3902 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003903 }
Mike Stump11289f42009-09-09 15:08:12 +00003904
Chris Lattnere7cabb92009-07-13 00:10:46 +00003905 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003906 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003907 ExpandPointedToStructures,
3908 ExpandStructures, FD);
3909 if (FD || EncodingProperty) {
3910 // Note that we do extended encoding of protocol qualifer list
3911 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003912 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003913 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3914 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003915 S += '<';
3916 S += (*I)->getNameAsString();
3917 S += '>';
3918 }
3919 S += '"';
3920 }
3921 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003922 }
Mike Stump11289f42009-09-09 15:08:12 +00003923
Chris Lattnere7cabb92009-07-13 00:10:46 +00003924 QualType PointeeTy = OPT->getPointeeType();
3925 if (!EncodingProperty &&
3926 isa<TypedefType>(PointeeTy.getTypePtr())) {
3927 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003928 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003929 // {...};
3930 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003931 getObjCEncodingForTypeImpl(PointeeTy, S,
3932 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003933 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003934 return;
3935 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003936
3937 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003938 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003939 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003940 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003941 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3942 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003943 S += '<';
3944 S += (*I)->getNameAsString();
3945 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003946 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003947 S += '"';
3948 }
3949 return;
3950 }
Mike Stump11289f42009-09-09 15:08:12 +00003951
John McCalla9e6e8d2010-05-17 23:56:34 +00003952 // gcc just blithely ignores member pointers.
3953 // TODO: maybe there should be a mangling for these
3954 if (T->getAs<MemberPointerType>())
3955 return;
3956
Chris Lattnere7cabb92009-07-13 00:10:46 +00003957 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003958}
3959
Mike Stump11289f42009-09-09 15:08:12 +00003960void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003961 std::string& S) const {
3962 if (QT & Decl::OBJC_TQ_In)
3963 S += 'n';
3964 if (QT & Decl::OBJC_TQ_Inout)
3965 S += 'N';
3966 if (QT & Decl::OBJC_TQ_Out)
3967 S += 'o';
3968 if (QT & Decl::OBJC_TQ_Bycopy)
3969 S += 'O';
3970 if (QT & Decl::OBJC_TQ_Byref)
3971 S += 'R';
3972 if (QT & Decl::OBJC_TQ_Oneway)
3973 S += 'V';
3974}
3975
Chris Lattnere7cabb92009-07-13 00:10:46 +00003976void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003977 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003978
Anders Carlsson87c149b2007-10-11 01:00:40 +00003979 BuiltinVaListType = T;
3980}
3981
Chris Lattnere7cabb92009-07-13 00:10:46 +00003982void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003983 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003984}
3985
Chris Lattnere7cabb92009-07-13 00:10:46 +00003986void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003987 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003988}
3989
Chris Lattnere7cabb92009-07-13 00:10:46 +00003990void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003991 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003992}
3993
Chris Lattnere7cabb92009-07-13 00:10:46 +00003994void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003995 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003996}
3997
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003998void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003999 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004000 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004001
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004002 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004003}
4004
John McCalld28ae272009-12-02 08:04:21 +00004005/// \brief Retrieve the template name that corresponds to a non-empty
4006/// lookup.
John McCallad371252010-01-20 00:46:10 +00004007TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4008 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00004009 unsigned size = End - Begin;
4010 assert(size > 1 && "set is not overloaded!");
4011
4012 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4013 size * sizeof(FunctionTemplateDecl*));
4014 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4015
4016 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004017 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004018 NamedDecl *D = *I;
4019 assert(isa<FunctionTemplateDecl>(D) ||
4020 (isa<UsingShadowDecl>(D) &&
4021 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4022 *Storage++ = D;
4023 }
4024
4025 return TemplateName(OT);
4026}
4027
Douglas Gregordc572a32009-03-30 22:58:21 +00004028/// \brief Retrieve the template name that represents a qualified
4029/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00004030TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004031 bool TemplateKeyword,
4032 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00004033 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004034 llvm::FoldingSetNodeID ID;
4035 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4036
4037 void *InsertPos = 0;
4038 QualifiedTemplateName *QTN =
4039 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4040 if (!QTN) {
4041 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4042 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4043 }
4044
4045 return TemplateName(QTN);
4046}
4047
4048/// \brief Retrieve the template name that represents a dependent
4049/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00004050TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00004051 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00004052 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004053 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004054
4055 llvm::FoldingSetNodeID ID;
4056 DependentTemplateName::Profile(ID, NNS, Name);
4057
4058 void *InsertPos = 0;
4059 DependentTemplateName *QTN =
4060 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4061
4062 if (QTN)
4063 return TemplateName(QTN);
4064
4065 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4066 if (CanonNNS == NNS) {
4067 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4068 } else {
4069 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4070 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004071 DependentTemplateName *CheckQTN =
4072 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4073 assert(!CheckQTN && "Dependent type name canonicalization broken");
4074 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004075 }
4076
4077 DependentTemplateNames.InsertNode(QTN, InsertPos);
4078 return TemplateName(QTN);
4079}
4080
Douglas Gregor71395fa2009-11-04 00:56:37 +00004081/// \brief Retrieve the template name that represents a dependent
4082/// template name such as \c MetaFun::template operator+.
4083TemplateName
4084ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4085 OverloadedOperatorKind Operator) {
4086 assert((!NNS || NNS->isDependent()) &&
4087 "Nested name specifier must be dependent");
4088
4089 llvm::FoldingSetNodeID ID;
4090 DependentTemplateName::Profile(ID, NNS, Operator);
4091
4092 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004093 DependentTemplateName *QTN
4094 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004095
4096 if (QTN)
4097 return TemplateName(QTN);
4098
4099 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4100 if (CanonNNS == NNS) {
4101 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4102 } else {
4103 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4104 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004105
4106 DependentTemplateName *CheckQTN
4107 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4108 assert(!CheckQTN && "Dependent template name canonicalization broken");
4109 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004110 }
4111
4112 DependentTemplateNames.InsertNode(QTN, InsertPos);
4113 return TemplateName(QTN);
4114}
4115
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004116/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004117/// TargetInfo, produce the corresponding type. The unsigned @p Type
4118/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004119CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004120 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004121 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004122 case TargetInfo::SignedShort: return ShortTy;
4123 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4124 case TargetInfo::SignedInt: return IntTy;
4125 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4126 case TargetInfo::SignedLong: return LongTy;
4127 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4128 case TargetInfo::SignedLongLong: return LongLongTy;
4129 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4130 }
4131
4132 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004133 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004134}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004135
4136//===----------------------------------------------------------------------===//
4137// Type Predicates.
4138//===----------------------------------------------------------------------===//
4139
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004140/// isObjCNSObjectType - Return true if this is an NSObject object using
4141/// NSObject attribute on a c-style pointer type.
4142/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004143/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004144///
4145bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4146 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4147 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004148 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004149 return true;
4150 }
Mike Stump11289f42009-09-09 15:08:12 +00004151 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004152}
4153
Fariborz Jahanian96207692009-02-18 21:49:28 +00004154/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4155/// garbage collection attribute.
4156///
John McCall8ccfcb52009-09-24 19:53:00 +00004157Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4158 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004159 if (getLangOptions().ObjC1 &&
4160 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004161 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004162 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004163 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004164 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004165 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004166 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004167 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004168 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004169 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004170 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004171 // Non-pointers have none gc'able attribute regardless of the attribute
4172 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004173 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004174 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004175 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004176 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004177}
4178
Chris Lattner49af6a42008-04-07 06:51:04 +00004179//===----------------------------------------------------------------------===//
4180// Type Compatibility Testing
4181//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004182
Mike Stump11289f42009-09-09 15:08:12 +00004183/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004184/// compatible.
4185static bool areCompatVectorTypes(const VectorType *LHS,
4186 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004187 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004188 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004189 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004190}
4191
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004192bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4193 QualType SecondVec) {
4194 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4195 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4196
4197 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4198 return true;
4199
4200 // AltiVec vectors types are identical to equivalent GCC vector types
4201 const VectorType *First = FirstVec->getAs<VectorType>();
4202 const VectorType *Second = SecondVec->getAs<VectorType>();
4203 if ((((First->getAltiVecSpecific() == VectorType::AltiVec) &&
4204 (Second->getAltiVecSpecific() == VectorType::NotAltiVec)) ||
4205 ((First->getAltiVecSpecific() == VectorType::NotAltiVec) &&
4206 (Second->getAltiVecSpecific() == VectorType::AltiVec))) &&
4207 hasSameType(First->getElementType(), Second->getElementType()) &&
4208 (First->getNumElements() == Second->getNumElements()))
4209 return true;
4210
4211 return false;
4212}
4213
Steve Naroff8e6aee52009-07-23 01:01:38 +00004214//===----------------------------------------------------------------------===//
4215// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4216//===----------------------------------------------------------------------===//
4217
4218/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4219/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004220bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4221 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004222 if (lProto == rProto)
4223 return true;
4224 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4225 E = rProto->protocol_end(); PI != E; ++PI)
4226 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4227 return true;
4228 return false;
4229}
4230
Steve Naroff8e6aee52009-07-23 01:01:38 +00004231/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4232/// return true if lhs's protocols conform to rhs's protocol; false
4233/// otherwise.
4234bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4235 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4236 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4237 return false;
4238}
4239
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004240/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4241/// Class<p1, ...>.
4242bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4243 QualType rhs) {
4244 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4245 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4246 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4247
4248 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4249 E = lhsQID->qual_end(); I != E; ++I) {
4250 bool match = false;
4251 ObjCProtocolDecl *lhsProto = *I;
4252 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4253 E = rhsOPT->qual_end(); J != E; ++J) {
4254 ObjCProtocolDecl *rhsProto = *J;
4255 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4256 match = true;
4257 break;
4258 }
4259 }
4260 if (!match)
4261 return false;
4262 }
4263 return true;
4264}
4265
Steve Naroff8e6aee52009-07-23 01:01:38 +00004266/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4267/// ObjCQualifiedIDType.
4268bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4269 bool compare) {
4270 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004271 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004272 lhs->isObjCIdType() || lhs->isObjCClassType())
4273 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004274 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004275 rhs->isObjCIdType() || rhs->isObjCClassType())
4276 return true;
4277
4278 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004279 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004280
Steve Naroff8e6aee52009-07-23 01:01:38 +00004281 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004282
Steve Naroff8e6aee52009-07-23 01:01:38 +00004283 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004284 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004285 // make sure we check the class hierarchy.
4286 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4287 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4288 E = lhsQID->qual_end(); I != E; ++I) {
4289 // when comparing an id<P> on lhs with a static type on rhs,
4290 // see if static class implements all of id's protocols, directly or
4291 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004292 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004293 return false;
4294 }
4295 }
4296 // If there are no qualifiers and no interface, we have an 'id'.
4297 return true;
4298 }
Mike Stump11289f42009-09-09 15:08:12 +00004299 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004300 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4301 E = lhsQID->qual_end(); I != E; ++I) {
4302 ObjCProtocolDecl *lhsProto = *I;
4303 bool match = false;
4304
4305 // when comparing an id<P> on lhs with a static type on rhs,
4306 // see if static class implements all of id's protocols, directly or
4307 // through its super class and categories.
4308 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4309 E = rhsOPT->qual_end(); J != E; ++J) {
4310 ObjCProtocolDecl *rhsProto = *J;
4311 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4312 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4313 match = true;
4314 break;
4315 }
4316 }
Mike Stump11289f42009-09-09 15:08:12 +00004317 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004318 // make sure we check the class hierarchy.
4319 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4320 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4321 E = lhsQID->qual_end(); I != E; ++I) {
4322 // when comparing an id<P> on lhs with a static type on rhs,
4323 // see if static class implements all of id's protocols, directly or
4324 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004325 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004326 match = true;
4327 break;
4328 }
4329 }
4330 }
4331 if (!match)
4332 return false;
4333 }
Mike Stump11289f42009-09-09 15:08:12 +00004334
Steve Naroff8e6aee52009-07-23 01:01:38 +00004335 return true;
4336 }
Mike Stump11289f42009-09-09 15:08:12 +00004337
Steve Naroff8e6aee52009-07-23 01:01:38 +00004338 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4339 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4340
Mike Stump11289f42009-09-09 15:08:12 +00004341 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004342 lhs->getAsObjCInterfacePointerType()) {
4343 if (lhsOPT->qual_empty()) {
4344 bool match = false;
4345 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4346 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4347 E = rhsQID->qual_end(); I != E; ++I) {
Fariborz Jahanianec430222010-08-09 18:21:43 +00004348 // when comparing an id<P> on rhs with a static type on lhs,
4349 // static class must implement all of id's protocols directly or
4350 // indirectly through its super class.
Fariborz Jahanian753783a2010-08-12 20:46:12 +00004351 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004352 match = true;
4353 break;
4354 }
4355 }
4356 if (!match)
4357 return false;
4358 }
4359 return true;
4360 }
Mike Stump11289f42009-09-09 15:08:12 +00004361 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004362 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4363 E = lhsOPT->qual_end(); I != E; ++I) {
4364 ObjCProtocolDecl *lhsProto = *I;
4365 bool match = false;
4366
4367 // when comparing an id<P> on lhs with a static type on rhs,
4368 // see if static class implements all of id's protocols, directly or
4369 // through its super class and categories.
4370 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4371 E = rhsQID->qual_end(); J != E; ++J) {
4372 ObjCProtocolDecl *rhsProto = *J;
4373 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4374 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4375 match = true;
4376 break;
4377 }
4378 }
4379 if (!match)
4380 return false;
4381 }
4382 return true;
4383 }
4384 return false;
4385}
4386
Eli Friedman47f77112008-08-22 00:56:42 +00004387/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004388/// compatible for assignment from RHS to LHS. This handles validation of any
4389/// protocol qualifiers on the LHS or RHS.
4390///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004391bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4392 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004393 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4394 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4395
Steve Naroff1329fa02009-07-15 18:40:39 +00004396 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004397 if (LHS->isObjCUnqualifiedIdOrClass() ||
4398 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004399 return true;
4400
John McCall8b07ec22010-05-15 11:32:37 +00004401 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004402 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4403 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004404 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004405
4406 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4407 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4408 QualType(RHSOPT,0));
4409
John McCall8b07ec22010-05-15 11:32:37 +00004410 // If we have 2 user-defined types, fall into that path.
4411 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004412 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004413
Steve Naroff8e6aee52009-07-23 01:01:38 +00004414 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004415}
4416
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004417/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4418/// for providing type-safty for objective-c pointers used to pass/return
4419/// arguments in block literals. When passed as arguments, passing 'A*' where
4420/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4421/// not OK. For the return type, the opposite is not OK.
4422bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4423 const ObjCObjectPointerType *LHSOPT,
4424 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004425 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004426 return true;
4427
4428 if (LHSOPT->isObjCBuiltinType()) {
4429 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4430 }
4431
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004432 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004433 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4434 QualType(RHSOPT,0),
4435 false);
4436
4437 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4438 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4439 if (LHS && RHS) { // We have 2 user-defined types.
4440 if (LHS != RHS) {
4441 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4442 return false;
4443 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4444 return true;
4445 }
4446 else
4447 return true;
4448 }
4449 return false;
4450}
4451
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004452/// getIntersectionOfProtocols - This routine finds the intersection of set
4453/// of protocols inherited from two distinct objective-c pointer objects.
4454/// It is used to build composite qualifier list of the composite type of
4455/// the conditional expression involving two objective-c pointer objects.
4456static
4457void getIntersectionOfProtocols(ASTContext &Context,
4458 const ObjCObjectPointerType *LHSOPT,
4459 const ObjCObjectPointerType *RHSOPT,
4460 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4461
John McCall8b07ec22010-05-15 11:32:37 +00004462 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4463 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4464 assert(LHS->getInterface() && "LHS must have an interface base");
4465 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004466
4467 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4468 unsigned LHSNumProtocols = LHS->getNumProtocols();
4469 if (LHSNumProtocols > 0)
4470 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4471 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004472 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004473 Context.CollectInheritedProtocols(LHS->getInterface(),
4474 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004475 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4476 LHSInheritedProtocols.end());
4477 }
4478
4479 unsigned RHSNumProtocols = RHS->getNumProtocols();
4480 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004481 ObjCProtocolDecl **RHSProtocols =
4482 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004483 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4484 if (InheritedProtocolSet.count(RHSProtocols[i]))
4485 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4486 }
4487 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004488 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004489 Context.CollectInheritedProtocols(RHS->getInterface(),
4490 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004491 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4492 RHSInheritedProtocols.begin(),
4493 E = RHSInheritedProtocols.end(); I != E; ++I)
4494 if (InheritedProtocolSet.count((*I)))
4495 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004496 }
4497}
4498
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004499/// areCommonBaseCompatible - Returns common base class of the two classes if
4500/// one found. Note that this is O'2 algorithm. But it will be called as the
4501/// last type comparison in a ?-exp of ObjC pointer types before a
4502/// warning is issued. So, its invokation is extremely rare.
4503QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004504 const ObjCObjectPointerType *Lptr,
4505 const ObjCObjectPointerType *Rptr) {
4506 const ObjCObjectType *LHS = Lptr->getObjectType();
4507 const ObjCObjectType *RHS = Rptr->getObjectType();
4508 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4509 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4510 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004511 return QualType();
4512
John McCall8b07ec22010-05-15 11:32:37 +00004513 while ((LDecl = LDecl->getSuperClass())) {
4514 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004515 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004516 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4517 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4518
4519 QualType Result = QualType(LHS, 0);
4520 if (!Protocols.empty())
4521 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4522 Result = getObjCObjectPointerType(Result);
4523 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004524 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004525 }
4526
4527 return QualType();
4528}
4529
John McCall8b07ec22010-05-15 11:32:37 +00004530bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4531 const ObjCObjectType *RHS) {
4532 assert(LHS->getInterface() && "LHS is not an interface type");
4533 assert(RHS->getInterface() && "RHS is not an interface type");
4534
Chris Lattner49af6a42008-04-07 06:51:04 +00004535 // Verify that the base decls are compatible: the RHS must be a subclass of
4536 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004537 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004538 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004539
Chris Lattner49af6a42008-04-07 06:51:04 +00004540 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4541 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004542 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004543 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004544
Chris Lattner49af6a42008-04-07 06:51:04 +00004545 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4546 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004547 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004548 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004549
John McCall8b07ec22010-05-15 11:32:37 +00004550 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4551 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004552 LHSPI != LHSPE; LHSPI++) {
4553 bool RHSImplementsProtocol = false;
4554
4555 // If the RHS doesn't implement the protocol on the left, the types
4556 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004557 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4558 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004559 RHSPI != RHSPE; RHSPI++) {
4560 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004561 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004562 break;
4563 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004564 }
4565 // FIXME: For better diagnostics, consider passing back the protocol name.
4566 if (!RHSImplementsProtocol)
4567 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004568 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004569 // The RHS implements all protocols listed on the LHS.
4570 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004571}
4572
Steve Naroffb7605152009-02-12 17:52:19 +00004573bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4574 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004575 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4576 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004577
Steve Naroff7cae42b2009-07-10 23:34:53 +00004578 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004579 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004580
4581 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4582 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004583}
4584
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004585bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4586 return canAssignObjCInterfaces(
4587 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4588 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4589}
4590
Mike Stump11289f42009-09-09 15:08:12 +00004591/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004592/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004593/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004594/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004595bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
4596 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004597 if (getLangOptions().CPlusPlus)
4598 return hasSameType(LHS, RHS);
4599
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004600 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00004601}
4602
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004603bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4604 return !mergeTypes(LHS, RHS, true).isNull();
4605}
4606
4607QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004608 bool OfBlockPointer,
4609 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00004610 const FunctionType *lbase = lhs->getAs<FunctionType>();
4611 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004612 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4613 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004614 bool allLTypes = true;
4615 bool allRTypes = true;
4616
4617 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004618 QualType retType;
4619 if (OfBlockPointer)
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004620 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
4621 Unqualified);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004622 else
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004623 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(),
4624 false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004625 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004626
4627 if (Unqualified)
4628 retType = retType.getUnqualifiedType();
4629
4630 CanQualType LRetType = getCanonicalType(lbase->getResultType());
4631 CanQualType RRetType = getCanonicalType(rbase->getResultType());
4632 if (Unqualified) {
4633 LRetType = LRetType.getUnqualifiedType();
4634 RRetType = RRetType.getUnqualifiedType();
4635 }
4636
4637 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004638 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004639 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00004640 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004641 // FIXME: double check this
4642 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4643 // rbase->getRegParmAttr() != 0 &&
4644 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004645 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4646 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004647 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4648 lbaseInfo.getRegParm();
4649 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4650 if (NoReturn != lbaseInfo.getNoReturn() ||
4651 RegParm != lbaseInfo.getRegParm())
4652 allLTypes = false;
4653 if (NoReturn != rbaseInfo.getNoReturn() ||
4654 RegParm != rbaseInfo.getRegParm())
4655 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004656 CallingConv lcc = lbaseInfo.getCC();
4657 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004658 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004659 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004660 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004661
Eli Friedman47f77112008-08-22 00:56:42 +00004662 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004663 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4664 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004665 unsigned lproto_nargs = lproto->getNumArgs();
4666 unsigned rproto_nargs = rproto->getNumArgs();
4667
4668 // Compatible functions must have the same number of arguments
4669 if (lproto_nargs != rproto_nargs)
4670 return QualType();
4671
4672 // Variadic and non-variadic functions aren't compatible
4673 if (lproto->isVariadic() != rproto->isVariadic())
4674 return QualType();
4675
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004676 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4677 return QualType();
4678
Eli Friedman47f77112008-08-22 00:56:42 +00004679 // Check argument compatibility
4680 llvm::SmallVector<QualType, 10> types;
4681 for (unsigned i = 0; i < lproto_nargs; i++) {
4682 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4683 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004684 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer,
4685 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004686 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004687
4688 if (Unqualified)
4689 argtype = argtype.getUnqualifiedType();
4690
Eli Friedman47f77112008-08-22 00:56:42 +00004691 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004692 if (Unqualified) {
4693 largtype = largtype.getUnqualifiedType();
4694 rargtype = rargtype.getUnqualifiedType();
4695 }
4696
Chris Lattner465fa322008-10-05 17:34:18 +00004697 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4698 allLTypes = false;
4699 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4700 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004701 }
4702 if (allLTypes) return lhs;
4703 if (allRTypes) return rhs;
4704 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004705 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004706 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004707 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004708 }
4709
4710 if (lproto) allRTypes = false;
4711 if (rproto) allLTypes = false;
4712
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004713 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004714 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004715 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004716 if (proto->isVariadic()) return QualType();
4717 // Check that the types are compatible with the types that
4718 // would result from default argument promotions (C99 6.7.5.3p15).
4719 // The only types actually affected are promotable integer
4720 // types and floats, which would be passed as a different
4721 // type depending on whether the prototype is visible.
4722 unsigned proto_nargs = proto->getNumArgs();
4723 for (unsigned i = 0; i < proto_nargs; ++i) {
4724 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004725
4726 // Look at the promotion type of enum types, since that is the type used
4727 // to pass enum values.
4728 if (const EnumType *Enum = argTy->getAs<EnumType>())
4729 argTy = Enum->getDecl()->getPromotionType();
4730
Eli Friedman47f77112008-08-22 00:56:42 +00004731 if (argTy->isPromotableIntegerType() ||
4732 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4733 return QualType();
4734 }
4735
4736 if (allLTypes) return lhs;
4737 if (allRTypes) return rhs;
4738 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004739 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004740 proto->getTypeQuals(),
4741 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004742 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004743 }
4744
4745 if (allLTypes) return lhs;
4746 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004747 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004748 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004749}
4750
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004751QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004752 bool OfBlockPointer,
4753 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004754 // C++ [expr]: If an expression initially has the type "reference to T", the
4755 // type is adjusted to "T" prior to any further analysis, the expression
4756 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004757 // expression is an lvalue unless the reference is an rvalue reference and
4758 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004759 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4760 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004761
4762 if (Unqualified) {
4763 LHS = LHS.getUnqualifiedType();
4764 RHS = RHS.getUnqualifiedType();
4765 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00004766
Eli Friedman47f77112008-08-22 00:56:42 +00004767 QualType LHSCan = getCanonicalType(LHS),
4768 RHSCan = getCanonicalType(RHS);
4769
4770 // If two types are identical, they are compatible.
4771 if (LHSCan == RHSCan)
4772 return LHS;
4773
John McCall8ccfcb52009-09-24 19:53:00 +00004774 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004775 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4776 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004777 if (LQuals != RQuals) {
4778 // If any of these qualifiers are different, we have a type
4779 // mismatch.
4780 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4781 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4782 return QualType();
4783
4784 // Exactly one GC qualifier difference is allowed: __strong is
4785 // okay if the other type has no GC qualifier but is an Objective
4786 // C object pointer (i.e. implicitly strong by default). We fix
4787 // this by pretending that the unqualified type was actually
4788 // qualified __strong.
4789 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4790 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4791 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4792
4793 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4794 return QualType();
4795
4796 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4797 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4798 }
4799 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4800 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4801 }
Eli Friedman47f77112008-08-22 00:56:42 +00004802 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004803 }
4804
4805 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004806
Eli Friedmandcca6332009-06-01 01:22:52 +00004807 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4808 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004809
Chris Lattnerfd652912008-01-14 05:45:46 +00004810 // We want to consider the two function types to be the same for these
4811 // comparisons, just force one to the other.
4812 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4813 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004814
4815 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004816 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4817 LHSClass = Type::ConstantArray;
4818 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4819 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004820
John McCall8b07ec22010-05-15 11:32:37 +00004821 // ObjCInterfaces are just specialized ObjCObjects.
4822 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4823 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4824
Nate Begemance4d7fc2008-04-18 23:10:10 +00004825 // Canonicalize ExtVector -> Vector.
4826 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4827 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004828
Chris Lattner95554662008-04-07 05:43:21 +00004829 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004830 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004831 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004832 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004833 // Compatibility is based on the underlying type, not the promotion
4834 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004835 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004836 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4837 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004838 }
John McCall9dd450b2009-09-21 23:43:11 +00004839 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004840 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4841 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004842 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004843
Eli Friedman47f77112008-08-22 00:56:42 +00004844 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004845 }
Eli Friedman47f77112008-08-22 00:56:42 +00004846
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004847 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004848 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004849#define TYPE(Class, Base)
4850#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004851#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004852#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4853#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4854#include "clang/AST/TypeNodes.def"
4855 assert(false && "Non-canonical and dependent types shouldn't get here");
4856 return QualType();
4857
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004858 case Type::LValueReference:
4859 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004860 case Type::MemberPointer:
4861 assert(false && "C++ should never be in mergeTypes");
4862 return QualType();
4863
John McCall8b07ec22010-05-15 11:32:37 +00004864 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004865 case Type::IncompleteArray:
4866 case Type::VariableArray:
4867 case Type::FunctionProto:
4868 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004869 assert(false && "Types are eliminated above");
4870 return QualType();
4871
Chris Lattnerfd652912008-01-14 05:45:46 +00004872 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004873 {
4874 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004875 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4876 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004877 if (Unqualified) {
4878 LHSPointee = LHSPointee.getUnqualifiedType();
4879 RHSPointee = RHSPointee.getUnqualifiedType();
4880 }
4881 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
4882 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004883 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004884 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004885 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004886 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004887 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004888 return getPointerType(ResultType);
4889 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004890 case Type::BlockPointer:
4891 {
4892 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004893 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4894 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004895 if (Unqualified) {
4896 LHSPointee = LHSPointee.getUnqualifiedType();
4897 RHSPointee = RHSPointee.getUnqualifiedType();
4898 }
4899 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
4900 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00004901 if (ResultType.isNull()) return QualType();
4902 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4903 return LHS;
4904 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4905 return RHS;
4906 return getBlockPointerType(ResultType);
4907 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004908 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004909 {
4910 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4911 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4912 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4913 return QualType();
4914
4915 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4916 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004917 if (Unqualified) {
4918 LHSElem = LHSElem.getUnqualifiedType();
4919 RHSElem = RHSElem.getUnqualifiedType();
4920 }
4921
4922 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00004923 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004924 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4925 return LHS;
4926 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4927 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004928 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4929 ArrayType::ArraySizeModifier(), 0);
4930 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4931 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004932 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4933 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004934 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4935 return LHS;
4936 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4937 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004938 if (LVAT) {
4939 // FIXME: This isn't correct! But tricky to implement because
4940 // the array's size has to be the size of LHS, but the type
4941 // has to be different.
4942 return LHS;
4943 }
4944 if (RVAT) {
4945 // FIXME: This isn't correct! But tricky to implement because
4946 // the array's size has to be the size of RHS, but the type
4947 // has to be different.
4948 return RHS;
4949 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004950 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4951 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004952 return getIncompleteArrayType(ResultType,
4953 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004954 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004955 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00004956 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004957 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004958 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004959 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004960 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004961 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004962 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004963 case Type::Complex:
4964 // Distinct complex types are incompatible.
4965 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004966 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004967 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004968 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4969 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004970 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004971 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00004972 case Type::ObjCObject: {
4973 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004974 // FIXME: This should be type compatibility, e.g. whether
4975 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00004976 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4977 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4978 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00004979 return LHS;
4980
Eli Friedman47f77112008-08-22 00:56:42 +00004981 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004982 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004983 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004984 if (OfBlockPointer) {
4985 if (canAssignObjCInterfacesInBlockPointer(
4986 LHS->getAs<ObjCObjectPointerType>(),
4987 RHS->getAs<ObjCObjectPointerType>()))
4988 return LHS;
4989 return QualType();
4990 }
John McCall9dd450b2009-09-21 23:43:11 +00004991 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4992 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004993 return LHS;
4994
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004995 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004996 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004997 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004998
4999 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005000}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005001
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005002/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5003/// 'RHS' attributes and returns the merged version; including for function
5004/// return types.
5005QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5006 QualType LHSCan = getCanonicalType(LHS),
5007 RHSCan = getCanonicalType(RHS);
5008 // If two types are identical, they are compatible.
5009 if (LHSCan == RHSCan)
5010 return LHS;
5011 if (RHSCan->isFunctionType()) {
5012 if (!LHSCan->isFunctionType())
5013 return QualType();
5014 QualType OldReturnType =
5015 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5016 QualType NewReturnType =
5017 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5018 QualType ResReturnType =
5019 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5020 if (ResReturnType.isNull())
5021 return QualType();
5022 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5023 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5024 // In either case, use OldReturnType to build the new function type.
5025 const FunctionType *F = LHS->getAs<FunctionType>();
5026 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
5027 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
5028 QualType ResultType
5029 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
5030 FPT->getNumArgs(), FPT->isVariadic(),
5031 FPT->getTypeQuals(),
5032 FPT->hasExceptionSpec(),
5033 FPT->hasAnyExceptionSpec(),
5034 FPT->getNumExceptions(),
5035 FPT->exception_begin(),
5036 Info);
5037 return ResultType;
5038 }
5039 }
5040 return QualType();
5041 }
5042
5043 // If the qualifiers are different, the types can still be merged.
5044 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5045 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5046 if (LQuals != RQuals) {
5047 // If any of these qualifiers are different, we have a type mismatch.
5048 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5049 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5050 return QualType();
5051
5052 // Exactly one GC qualifier difference is allowed: __strong is
5053 // okay if the other type has no GC qualifier but is an Objective
5054 // C object pointer (i.e. implicitly strong by default). We fix
5055 // this by pretending that the unqualified type was actually
5056 // qualified __strong.
5057 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5058 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5059 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5060
5061 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5062 return QualType();
5063
5064 if (GC_L == Qualifiers::Strong)
5065 return LHS;
5066 if (GC_R == Qualifiers::Strong)
5067 return RHS;
5068 return QualType();
5069 }
5070
5071 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5072 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5073 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5074 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5075 if (ResQT == LHSBaseQT)
5076 return LHS;
5077 if (ResQT == RHSBaseQT)
5078 return RHS;
5079 }
5080 return QualType();
5081}
5082
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005083//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005084// Integer Predicates
5085//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005086
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005087unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00005088 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005089 return 1;
John McCall56774992009-12-09 09:09:27 +00005090 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005091 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00005092 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005093 return (unsigned)getTypeSize(T);
5094}
5095
5096QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005097 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005098
5099 // Turn <4 x signed int> -> <4 x unsigned int>
5100 if (const VectorType *VTy = T->getAs<VectorType>())
5101 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Chris Lattner37141f42010-06-23 06:00:24 +00005102 VTy->getNumElements(), VTy->getAltiVecSpecific());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005103
5104 // For enums, we return the unsigned version of the base type.
5105 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005106 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005107
5108 const BuiltinType *BTy = T->getAs<BuiltinType>();
5109 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005110 switch (BTy->getKind()) {
5111 case BuiltinType::Char_S:
5112 case BuiltinType::SChar:
5113 return UnsignedCharTy;
5114 case BuiltinType::Short:
5115 return UnsignedShortTy;
5116 case BuiltinType::Int:
5117 return UnsignedIntTy;
5118 case BuiltinType::Long:
5119 return UnsignedLongTy;
5120 case BuiltinType::LongLong:
5121 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005122 case BuiltinType::Int128:
5123 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005124 default:
5125 assert(0 && "Unexpected signed integer type");
5126 return QualType();
5127 }
5128}
5129
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005130ExternalASTSource::~ExternalASTSource() { }
5131
5132void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00005133
5134
5135//===----------------------------------------------------------------------===//
5136// Builtin Type Computation
5137//===----------------------------------------------------------------------===//
5138
5139/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5140/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00005141static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005142 ASTContext::GetBuiltinTypeError &Error,
5143 bool AllowTypeModifiers = true) {
5144 // Modifiers.
5145 int HowLong = 0;
5146 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00005147
Chris Lattnerecd79c62009-06-14 00:45:47 +00005148 // Read the modifiers first.
5149 bool Done = false;
5150 while (!Done) {
5151 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005152 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005153 case 'S':
5154 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5155 assert(!Signed && "Can't use 'S' modifier multiple times!");
5156 Signed = true;
5157 break;
5158 case 'U':
5159 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5160 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5161 Unsigned = true;
5162 break;
5163 case 'L':
5164 assert(HowLong <= 2 && "Can't have LLLL modifier");
5165 ++HowLong;
5166 break;
5167 }
5168 }
5169
5170 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005171
Chris Lattnerecd79c62009-06-14 00:45:47 +00005172 // Read the base type.
5173 switch (*Str++) {
5174 default: assert(0 && "Unknown builtin type letter!");
5175 case 'v':
5176 assert(HowLong == 0 && !Signed && !Unsigned &&
5177 "Bad modifiers used with 'v'!");
5178 Type = Context.VoidTy;
5179 break;
5180 case 'f':
5181 assert(HowLong == 0 && !Signed && !Unsigned &&
5182 "Bad modifiers used with 'f'!");
5183 Type = Context.FloatTy;
5184 break;
5185 case 'd':
5186 assert(HowLong < 2 && !Signed && !Unsigned &&
5187 "Bad modifiers used with 'd'!");
5188 if (HowLong)
5189 Type = Context.LongDoubleTy;
5190 else
5191 Type = Context.DoubleTy;
5192 break;
5193 case 's':
5194 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5195 if (Unsigned)
5196 Type = Context.UnsignedShortTy;
5197 else
5198 Type = Context.ShortTy;
5199 break;
5200 case 'i':
5201 if (HowLong == 3)
5202 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5203 else if (HowLong == 2)
5204 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5205 else if (HowLong == 1)
5206 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5207 else
5208 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5209 break;
5210 case 'c':
5211 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5212 if (Signed)
5213 Type = Context.SignedCharTy;
5214 else if (Unsigned)
5215 Type = Context.UnsignedCharTy;
5216 else
5217 Type = Context.CharTy;
5218 break;
5219 case 'b': // boolean
5220 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5221 Type = Context.BoolTy;
5222 break;
5223 case 'z': // size_t.
5224 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5225 Type = Context.getSizeType();
5226 break;
5227 case 'F':
5228 Type = Context.getCFConstantStringType();
5229 break;
5230 case 'a':
5231 Type = Context.getBuiltinVaListType();
5232 assert(!Type.isNull() && "builtin va list type not initialized!");
5233 break;
5234 case 'A':
5235 // This is a "reference" to a va_list; however, what exactly
5236 // this means depends on how va_list is defined. There are two
5237 // different kinds of va_list: ones passed by value, and ones
5238 // passed by reference. An example of a by-value va_list is
5239 // x86, where va_list is a char*. An example of by-ref va_list
5240 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5241 // we want this argument to be a char*&; for x86-64, we want
5242 // it to be a __va_list_tag*.
5243 Type = Context.getBuiltinVaListType();
5244 assert(!Type.isNull() && "builtin va list type not initialized!");
5245 if (Type->isArrayType()) {
5246 Type = Context.getArrayDecayedType(Type);
5247 } else {
5248 Type = Context.getLValueReferenceType(Type);
5249 }
5250 break;
5251 case 'V': {
5252 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005253 unsigned NumElements = strtoul(Str, &End, 10);
5254 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00005255
Chris Lattnerecd79c62009-06-14 00:45:47 +00005256 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005257
Chris Lattnerecd79c62009-06-14 00:45:47 +00005258 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00005259 // FIXME: Don't know what to do about AltiVec.
Chris Lattner37141f42010-06-23 06:00:24 +00005260 Type = Context.getVectorType(ElementType, NumElements,
5261 VectorType::NotAltiVec);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005262 break;
5263 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005264 case 'X': {
5265 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5266 Type = Context.getComplexType(ElementType);
5267 break;
5268 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005269 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005270 Type = Context.getFILEType();
5271 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005272 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005273 return QualType();
5274 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005275 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005276 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005277 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005278 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005279 else
5280 Type = Context.getjmp_bufType();
5281
Mike Stump2adb4da2009-07-28 23:47:15 +00005282 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005283 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005284 return QualType();
5285 }
5286 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005287 }
Mike Stump11289f42009-09-09 15:08:12 +00005288
Chris Lattnerecd79c62009-06-14 00:45:47 +00005289 if (!AllowTypeModifiers)
5290 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00005291
Chris Lattnerecd79c62009-06-14 00:45:47 +00005292 Done = false;
5293 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005294 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005295 default: Done = true; --Str; break;
5296 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00005297 case '&':
John McCallb8b94662010-03-12 04:21:28 +00005298 {
5299 // Both pointers and references can have their pointee types
5300 // qualified with an address space.
5301 char *End;
5302 unsigned AddrSpace = strtoul(Str, &End, 10);
5303 if (End != Str && AddrSpace != 0) {
5304 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5305 Str = End;
5306 }
5307 }
5308 if (c == '*')
5309 Type = Context.getPointerType(Type);
5310 else
5311 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005312 break;
5313 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5314 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00005315 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00005316 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005317 case 'D':
5318 Type = Context.getVolatileType(Type);
5319 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005320 }
5321 }
Mike Stump11289f42009-09-09 15:08:12 +00005322
Chris Lattnerecd79c62009-06-14 00:45:47 +00005323 return Type;
5324}
5325
5326/// GetBuiltinType - Return the type for the specified builtin.
5327QualType ASTContext::GetBuiltinType(unsigned id,
5328 GetBuiltinTypeError &Error) {
5329 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005330
Chris Lattnerecd79c62009-06-14 00:45:47 +00005331 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005332
Chris Lattnerecd79c62009-06-14 00:45:47 +00005333 Error = GE_None;
5334 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5335 if (Error != GE_None)
5336 return QualType();
5337 while (TypeStr[0] && TypeStr[0] != '.') {
5338 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5339 if (Error != GE_None)
5340 return QualType();
5341
5342 // Do array -> pointer decay. The builtin should use the decayed type.
5343 if (Ty->isArrayType())
5344 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005345
Chris Lattnerecd79c62009-06-14 00:45:47 +00005346 ArgTypes.push_back(Ty);
5347 }
5348
5349 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5350 "'.' should only occur at end of builtin type list!");
5351
5352 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5353 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5354 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005355
5356 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005357 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005358 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005359 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005360}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005361
5362QualType
5363ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5364 // Perform the usual unary conversions. We do this early so that
5365 // integral promotions to "int" can allow us to exit early, in the
5366 // lhs == rhs check. Also, for conversion purposes, we ignore any
5367 // qualifiers. For example, "const float" and "float" are
5368 // equivalent.
5369 if (lhs->isPromotableIntegerType())
5370 lhs = getPromotedIntegerType(lhs);
5371 else
5372 lhs = lhs.getUnqualifiedType();
5373 if (rhs->isPromotableIntegerType())
5374 rhs = getPromotedIntegerType(rhs);
5375 else
5376 rhs = rhs.getUnqualifiedType();
5377
5378 // If both types are identical, no conversion is needed.
5379 if (lhs == rhs)
5380 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005381
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005382 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5383 // The caller can deal with this (e.g. pointer + int).
5384 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5385 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005386
5387 // At this point, we have two different arithmetic types.
5388
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005389 // Handle complex types first (C99 6.3.1.8p1).
5390 if (lhs->isComplexType() || rhs->isComplexType()) {
5391 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005392 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005393 // convert the rhs to the lhs complex type.
5394 return lhs;
5395 }
Mike Stump11289f42009-09-09 15:08:12 +00005396 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005397 // convert the lhs to the rhs complex type.
5398 return rhs;
5399 }
5400 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005401 // When both operands are complex, the shorter operand is converted to the
5402 // type of the longer, and that is the type of the result. This corresponds
5403 // to what is done when combining two real floating-point operands.
5404 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005405 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005406 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005407 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005408 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005409 // "double _Complex" is promoted to "long double _Complex".
5410 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005411
5412 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005413 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005414 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005415 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005416 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005417 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5418 // domains match. This is a requirement for our implementation, C99
5419 // does not require this promotion.
5420 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5421 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5422 return rhs;
5423 } else { // handle "_Complex double, double".
5424 return lhs;
5425 }
5426 }
5427 return lhs; // The domain/size match exactly.
5428 }
5429 // Now handle "real" floating types (i.e. float, double, long double).
5430 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5431 // if we have an integer operand, the result is the real floating type.
5432 if (rhs->isIntegerType()) {
5433 // convert rhs to the lhs floating point type.
5434 return lhs;
5435 }
5436 if (rhs->isComplexIntegerType()) {
5437 // convert rhs to the complex floating point type.
5438 return getComplexType(lhs);
5439 }
5440 if (lhs->isIntegerType()) {
5441 // convert lhs to the rhs floating point type.
5442 return rhs;
5443 }
Mike Stump11289f42009-09-09 15:08:12 +00005444 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005445 // convert lhs to the complex floating point type.
5446 return getComplexType(rhs);
5447 }
5448 // We have two real floating types, float/complex combos were handled above.
5449 // Convert the smaller operand to the bigger result.
5450 int result = getFloatingTypeOrder(lhs, rhs);
5451 if (result > 0) // convert the rhs
5452 return lhs;
5453 assert(result < 0 && "illegal float comparison");
5454 return rhs; // convert the lhs
5455 }
5456 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5457 // Handle GCC complex int extension.
5458 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5459 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5460
5461 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005462 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005463 rhsComplexInt->getElementType()) >= 0)
5464 return lhs; // convert the rhs
5465 return rhs;
5466 } else if (lhsComplexInt && rhs->isIntegerType()) {
5467 // convert the rhs to the lhs complex type.
5468 return lhs;
5469 } else if (rhsComplexInt && lhs->isIntegerType()) {
5470 // convert the lhs to the rhs complex type.
5471 return rhs;
5472 }
5473 }
5474 // Finally, we have two differing integer types.
5475 // The rules for this case are in C99 6.3.1.8
5476 int compare = getIntegerTypeOrder(lhs, rhs);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005477 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
5478 rhsSigned = rhs->hasSignedIntegerRepresentation();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005479 QualType destType;
5480 if (lhsSigned == rhsSigned) {
5481 // Same signedness; use the higher-ranked type
5482 destType = compare >= 0 ? lhs : rhs;
5483 } else if (compare != (lhsSigned ? 1 : -1)) {
5484 // The unsigned type has greater than or equal rank to the
5485 // signed type, so use the unsigned type
5486 destType = lhsSigned ? rhs : lhs;
5487 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5488 // The two types are different widths; if we are here, that
5489 // means the signed type is larger than the unsigned type, so
5490 // use the signed type.
5491 destType = lhsSigned ? lhs : rhs;
5492 } else {
5493 // The signed type is higher-ranked than the unsigned type,
5494 // but isn't actually any bigger (like unsigned int and long
5495 // on most 32-bit systems). Use the unsigned type corresponding
5496 // to the signed type.
5497 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5498 }
5499 return destType;
5500}
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005501
5502GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5503 GVALinkage External = GVA_StrongExternal;
5504
5505 Linkage L = FD->getLinkage();
5506 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5507 FD->getType()->getLinkage() == UniqueExternalLinkage)
5508 L = UniqueExternalLinkage;
5509
5510 switch (L) {
5511 case NoLinkage:
5512 case InternalLinkage:
5513 case UniqueExternalLinkage:
5514 return GVA_Internal;
5515
5516 case ExternalLinkage:
5517 switch (FD->getTemplateSpecializationKind()) {
5518 case TSK_Undeclared:
5519 case TSK_ExplicitSpecialization:
5520 External = GVA_StrongExternal;
5521 break;
5522
5523 case TSK_ExplicitInstantiationDefinition:
5524 return GVA_ExplicitTemplateInstantiation;
5525
5526 case TSK_ExplicitInstantiationDeclaration:
5527 case TSK_ImplicitInstantiation:
5528 External = GVA_TemplateInstantiation;
5529 break;
5530 }
5531 }
5532
5533 if (!FD->isInlined())
5534 return External;
5535
5536 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5537 // GNU or C99 inline semantics. Determine whether this symbol should be
5538 // externally visible.
5539 if (FD->isInlineDefinitionExternallyVisible())
5540 return External;
5541
5542 // C99 inline semantics, where the symbol is not externally visible.
5543 return GVA_C99Inline;
5544 }
5545
5546 // C++0x [temp.explicit]p9:
5547 // [ Note: The intent is that an inline function that is the subject of
5548 // an explicit instantiation declaration will still be implicitly
5549 // instantiated when used so that the body can be considered for
5550 // inlining, but that no out-of-line copy of the inline function would be
5551 // generated in the translation unit. -- end note ]
5552 if (FD->getTemplateSpecializationKind()
5553 == TSK_ExplicitInstantiationDeclaration)
5554 return GVA_C99Inline;
5555
5556 return GVA_CXXInline;
5557}
5558
5559GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5560 // If this is a static data member, compute the kind of template
5561 // specialization. Otherwise, this variable is not part of a
5562 // template.
5563 TemplateSpecializationKind TSK = TSK_Undeclared;
5564 if (VD->isStaticDataMember())
5565 TSK = VD->getTemplateSpecializationKind();
5566
5567 Linkage L = VD->getLinkage();
5568 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5569 VD->getType()->getLinkage() == UniqueExternalLinkage)
5570 L = UniqueExternalLinkage;
5571
5572 switch (L) {
5573 case NoLinkage:
5574 case InternalLinkage:
5575 case UniqueExternalLinkage:
5576 return GVA_Internal;
5577
5578 case ExternalLinkage:
5579 switch (TSK) {
5580 case TSK_Undeclared:
5581 case TSK_ExplicitSpecialization:
5582 return GVA_StrongExternal;
5583
5584 case TSK_ExplicitInstantiationDeclaration:
5585 llvm_unreachable("Variable should not be instantiated");
5586 // Fall through to treat this like any other instantiation.
5587
5588 case TSK_ExplicitInstantiationDefinition:
5589 return GVA_ExplicitTemplateInstantiation;
5590
5591 case TSK_ImplicitInstantiation:
5592 return GVA_TemplateInstantiation;
5593 }
5594 }
5595
5596 return GVA_StrongExternal;
5597}
5598
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005599bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005600 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5601 if (!VD->isFileVarDecl())
5602 return false;
5603 } else if (!isa<FunctionDecl>(D))
5604 return false;
5605
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005606 // Weak references don't produce any output by themselves.
5607 if (D->hasAttr<WeakRefAttr>())
5608 return false;
5609
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005610 // Aliases and used decls are required.
5611 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5612 return true;
5613
5614 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5615 // Forward declarations aren't required.
5616 if (!FD->isThisDeclarationADefinition())
5617 return false;
5618
5619 // Constructors and destructors are required.
5620 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5621 return true;
5622
5623 // The key function for a class is required.
5624 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5625 const CXXRecordDecl *RD = MD->getParent();
5626 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5627 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5628 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5629 return true;
5630 }
5631 }
5632
5633 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5634
5635 // static, static inline, always_inline, and extern inline functions can
5636 // always be deferred. Normal inline functions can be deferred in C99/C++.
5637 // Implicit template instantiations can also be deferred in C++.
5638 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5639 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5640 return false;
5641 return true;
5642 }
5643
5644 const VarDecl *VD = cast<VarDecl>(D);
5645 assert(VD->isFileVarDecl() && "Expected file scoped var");
5646
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005647 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
5648 return false;
5649
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005650 // Structs that have non-trivial constructors or destructors are required.
5651
5652 // FIXME: Handle references.
5653 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
5654 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00005655 if (RD->hasDefinition() &&
5656 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005657 return true;
5658 }
5659 }
5660
5661 GVALinkage L = GetGVALinkageForVariable(VD);
5662 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
5663 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
5664 return false;
5665 }
5666
5667 return true;
5668}
Charles Davis53c59df2010-08-16 03:33:14 +00005669
5670CXXABI::~CXXABI() {}